mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge remote-tracking branch 'upstream/main' into fix/remaining-type-envelopes
# Conflicts: # docs/file-format-parity.md # docs/target-app-parity.md
This commit is contained in:
commit
0e91edc4d2
222 files changed
+12533
-1259
No files matched your search
Generated
+1
@@ -6326,6 +6326,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"log",
|
||||
"muda",
|
||||
|
||||
@@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
|
||||
@@ -107,6 +107,9 @@ wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
|
||||
# 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
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::tablet;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::{linux_screen_color, tablet};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_save_format, mac_screen_color, mac_tablet};
|
||||
|
||||
@@ -354,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
@@ -381,6 +383,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
write_shared: Some(std::sync::Arc::new(write_file)),
|
||||
save_write: Some(std::sync::Arc::new(fileio::write_save_file)),
|
||||
save_stream: Some(std::sync::Arc::new(fileio::write_save_file_with)),
|
||||
// Native saves stream into the file as they are encoded.
|
||||
stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
|
||||
@@ -406,6 +410,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
|
||||
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
|
||||
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
|
||||
//! 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 {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (ui, window) = (ui.clone(), parent.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
// The thread names the window and holds it until the export that names it is dropped.
|
||||
let (handle, export) = match window.as_deref() {
|
||||
Some(window) => {
|
||||
let (handle, export) = super::portal_save::exported_parent(window);
|
||||
(handle, Some(export))
|
||||
}
|
||||
None => (String::new(), None),
|
||||
};
|
||||
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
|
||||
drop(export);
|
||||
drop(window);
|
||||
let answer = picked.map_err(|failure| {
|
||||
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
|
||||
failure.message().to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
"the screen color sampler failed".to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! The XDG desktop portal's `Screenshot.PickColor`
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
|
||||
//! the call returns a request path at once, and the request's `Response` signal later carries the
|
||||
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
|
||||
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
|
||||
/// the sampler, so the person's time with the sampler does not count.
|
||||
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
|
||||
|
||||
/// Why no color came back, as the status bar shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Failure {
|
||||
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
|
||||
Unavailable(String),
|
||||
/// The portal did not return a request path in time, or it left the bus before it answered.
|
||||
NoAnswer(String),
|
||||
/// The portal ended the request without a color, or its answer can't be read.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// The status bar's message (English; the status bar translates it).
|
||||
pub(super) fn message(&self) -> &'static str {
|
||||
match self {
|
||||
Failure::Unavailable(_) => "this system has no screen color sampler",
|
||||
Failure::NoAnswer(_) => "the screen color sampler did not answer",
|
||||
Failure::Failed(_) => "the screen color sampler failed",
|
||||
}
|
||||
}
|
||||
|
||||
/// What went wrong, for the log.
|
||||
pub(super) fn detail(&self) -> &str {
|
||||
match self {
|
||||
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
|
||||
const UNAVAILABLE: &[&str] = &[
|
||||
"org.freedesktop.DBus.Error.ServiceUnknown",
|
||||
"org.freedesktop.DBus.Error.NameHasNoOwner",
|
||||
"org.freedesktop.DBus.Error.UnknownMethod",
|
||||
"org.freedesktop.DBus.Error.UnknownInterface",
|
||||
"org.freedesktop.DBus.Error.UnknownObject",
|
||||
];
|
||||
|
||||
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
|
||||
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
|
||||
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
|
||||
}
|
||||
|
||||
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
|
||||
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
|
||||
/// 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)?;
|
||||
// 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 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()))]);
|
||||
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
|
||||
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
answer(code, &results)
|
||||
}
|
||||
|
||||
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
|
||||
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
|
||||
fn call_failure(e: &zbus::Error) -> Failure {
|
||||
match e {
|
||||
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
|
||||
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
|
||||
_ => Failure::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
|
||||
/// any other code ends the request without one. The components are passed on as given;
|
||||
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
|
||||
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
|
||||
match code {
|
||||
0 => {}
|
||||
1 => return Ok(None),
|
||||
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
|
||||
}
|
||||
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
|
||||
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
|
||||
match &**color {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
},
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
|
||||
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
|
||||
}
|
||||
|
||||
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
|
||||
matches!(r, Err(Failure::Failed(_)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picked_color_keeps_its_srgb_values() {
|
||||
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
|
||||
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
|
||||
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_needs_no_color() {
|
||||
assert_eq!(answer(1, &HashMap::new()), Ok(None));
|
||||
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_response_codes_are_failures() {
|
||||
for code in [2, 3, u32::MAX] {
|
||||
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_success_without_a_valid_color_is_a_failure() {
|
||||
assert!(failed(answer(0, &HashMap::new())));
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
// Fewer fields, more fields, and fields of another type: an error, not a panic.
|
||||
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_errors_say_whether_the_system_has_a_sampler() {
|
||||
let reply = |name: &str| {
|
||||
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
|
||||
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
|
||||
zbus::Error::from(error)
|
||||
};
|
||||
for name in UNAVAILABLE {
|
||||
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
|
||||
}
|
||||
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
|
||||
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
|
||||
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
|
||||
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
|
||||
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
|
||||
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
|
||||
assert_eq!(
|
||||
messages,
|
||||
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
|
||||
);
|
||||
assert_eq!(call_failure(&broken).detail(), broken.to_string());
|
||||
}
|
||||
|
||||
/// Every language that translates the sampler's other messages translates these too. The
|
||||
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
|
||||
#[test]
|
||||
fn the_messages_are_translated_where_the_sampler_is() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
const OPEN: &str = "the screen color sampler is already open";
|
||||
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
|
||||
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
|
||||
for lang in langs {
|
||||
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
|
||||
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
|
||||
/// starts an installed portal in its place.
|
||||
fn portal(address: &str) -> Connection {
|
||||
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
|
||||
/// other request paths or from other connections are ignored; a cancel gives no color; and a
|
||||
/// portal that leaves the bus while the person picks ends the wait.
|
||||
#[test]
|
||||
fn the_answer_is_the_portals_response_on_the_returned_path() {
|
||||
use zbus::blocking::MessageIterator;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
|
||||
let incoming = MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut calls = Vec::new();
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
|
||||
continue;
|
||||
}
|
||||
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
|
||||
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
|
||||
assert!(token.starts_with("vectorcraft_color_"));
|
||||
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
|
||||
assert!(!calls.iter().any(|(_, old)| old == &token));
|
||||
calls.push((parent, token));
|
||||
// A portal older than version 0.9 answers on a path of its own, not the token's.
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
|
||||
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
|
||||
if calls.len() == 4 {
|
||||
server.reply(&header, &handle).unwrap();
|
||||
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
|
||||
break;
|
||||
}
|
||||
let to = header.sender().cloned().map(zbus::names::BusName::from);
|
||||
// Another connection can't end the wait by claiming the portal left.
|
||||
impostor
|
||||
.emit_signal(
|
||||
to.clone(),
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameOwnerChanged",
|
||||
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
|
||||
)
|
||||
.unwrap();
|
||||
let wrong = color((1.0, 0.0, 0.0));
|
||||
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
|
||||
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
|
||||
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
|
||||
// The reply that names the path goes last: every answer above came before it.
|
||||
server.reply(&header, &handle).unwrap();
|
||||
}
|
||||
calls
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(pick(&client, "wayland:example"), Ok(None));
|
||||
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
|
||||
let calls = worker.join().unwrap();
|
||||
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
|
||||
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
|
||||
#[test]
|
||||
fn a_portal_without_pick_color_ends_the_request() {
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let incoming = zbus::blocking::MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.member().map(|m| m.as_str()) == Some("PickColor") {
|
||||
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
|
||||
let failure = pick(&client, "");
|
||||
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ mod cursor_theme;
|
||||
mod gpu;
|
||||
mod hang_watch;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_screen_color;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_stylus;
|
||||
mod logging;
|
||||
#[cfg(all(target_os = "macos", feature = "wgpu"))]
|
||||
|
||||
@@ -102,13 +102,22 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
|
||||
log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved");
|
||||
return Ok(None);
|
||||
};
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = results.get("current_filter").and_then(|v| filter_label(v));
|
||||
Ok(Some(Saved { path, filter }))
|
||||
}
|
||||
|
||||
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
|
||||
/// another shape.
|
||||
fn filter_label(value: &Value<'_>) -> Option<String> {
|
||||
match value {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere
|
||||
/// (`file://host/`) or another scheme.
|
||||
fn file_uri_path(uri: &str) -> Option<Vec<u8>> {
|
||||
@@ -233,6 +242,13 @@ fn parent(window: &winit::window::Window) -> (String, Option<wayland::Export>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`):
|
||||
/// the identifier stays valid until the second value is dropped.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) {
|
||||
parent(window)
|
||||
}
|
||||
|
||||
/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off
|
||||
/// Linux).
|
||||
#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
@@ -396,6 +412,36 @@ mod tests {
|
||||
assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]);
|
||||
}
|
||||
|
||||
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more
|
||||
/// fields, a string) gives the path alone; `uris` of another shape is an error.
|
||||
#[test]
|
||||
fn an_answer_of_another_shape_is_not_read() {
|
||||
let malformed = [
|
||||
Value::from(("SVG".to_string(),)),
|
||||
Value::from(("SVG".to_string(), vec![(0u32,)])),
|
||||
Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])),
|
||||
Value::from((1u32, vec![(0u32, "*.svg".to_string())])),
|
||||
Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)),
|
||||
Value::from("SVG"),
|
||||
];
|
||||
for filter in malformed {
|
||||
let mut r = results("file:///tmp/card", None);
|
||||
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
|
||||
assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })));
|
||||
}
|
||||
let malformed = [
|
||||
Value::from(vec![1u32]),
|
||||
Value::from(vec![("file:///tmp/card".to_string(),)]),
|
||||
Value::from(Vec::<String>::new()),
|
||||
Value::from("file:///tmp/card"),
|
||||
];
|
||||
for uris in malformed {
|
||||
let mut r = HashMap::new();
|
||||
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
|
||||
assert!(answer(0, &r).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel (1) and a dialog closed another way (2) answer no file; an answer without a local file
|
||||
/// is an error, and rfd shows the dialog instead.
|
||||
#[test]
|
||||
@@ -486,10 +532,7 @@ mod tests {
|
||||
}
|
||||
let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap<String, OwnedValue>)>() else { break };
|
||||
let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok());
|
||||
let filter = options.get("current_filter").and_then(|v| {
|
||||
let (label, _): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = options.get("current_filter").and_then(|v| filter_label(v));
|
||||
let calls = log.lock().map(|mut l| {
|
||||
l.push((text("current_name"), filter));
|
||||
l.len()
|
||||
|
||||
@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::Color;
|
||||
use crate::freeform::Freeform;
|
||||
|
||||
mod spread;
|
||||
pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum GradientKind {
|
||||
#[default]
|
||||
@@ -94,6 +97,82 @@ impl GradientMethod {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
|
||||
pub enum GradientSpread {
|
||||
/// The first and last stops' colors carry on past the ends, as gradients always did.
|
||||
#[default]
|
||||
Pad,
|
||||
/// The stops start again at each end.
|
||||
Repeat,
|
||||
/// The stops run back the other way at each end, so every other run is mirrored.
|
||||
Reflect,
|
||||
}
|
||||
|
||||
impl GradientSpread {
|
||||
/// Every spread, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect];
|
||||
/// Parse a spread name (`pad`, `repeat`, `reflect`; any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pad => "Pad",
|
||||
Self::Repeat => "Repeat",
|
||||
Self::Reflect => "Reflect",
|
||||
}
|
||||
}
|
||||
pub fn is_pad(&self) -> bool {
|
||||
*self == Self::Pad
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for GradientSpread {
|
||||
/// A spread name; a file's unknown name or other value reads as Pad.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Name(String),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Name(s) => Self::parse(&s).unwrap_or_default(),
|
||||
Raw::Other(_) => Self::Pad,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own
|
||||
/// limit.
|
||||
pub const MAX_REPEATS: u32 = 100;
|
||||
|
||||
fn one_repeat() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_one_repeat(n: &u32) -> bool {
|
||||
*n == 1
|
||||
}
|
||||
|
||||
/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else
|
||||
/// reads as 1.
|
||||
fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Number(f64),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
|
||||
/// expanded stops may stray from the perceptual mix: under half a colour level.
|
||||
const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
@@ -259,6 +338,15 @@ pub struct Gradient {
|
||||
/// How the colours between the stops are mixed (Classic unless set; written only when not).
|
||||
#[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
|
||||
pub method: GradientMethod,
|
||||
/// What it paints past the ends of its stops (Pad unless set; written only when not). A
|
||||
/// freeform gradient has no ends and ignores it.
|
||||
#[serde(default, skip_serializing_if = "GradientSpread::is_pad")]
|
||||
pub spread: GradientSpread,
|
||||
/// How many times the stops run along the vector with Repeat and Reflect, 1 to
|
||||
/// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad
|
||||
/// ignores it. Written only when it is not 1.
|
||||
#[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")]
|
||||
pub repeats: u32,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
@@ -271,7 +359,55 @@ impl Default for Gradient {
|
||||
impl Gradient {
|
||||
/// A gradient of `kind` through `stops`, with the default options.
|
||||
pub fn new(kind: GradientKind, stops: Vec<GradientStop>) -> Self {
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic }
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 }
|
||||
}
|
||||
/// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`].
|
||||
pub fn repeat_count(&self) -> u32 {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
/// for two gradients whose spreads paint alike.
|
||||
pub fn painted_spread(&self) -> (GradientSpread, u32) {
|
||||
if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) }
|
||||
}
|
||||
/// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the
|
||||
/// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops
|
||||
/// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run
|
||||
/// mirrored with Reflect. A `t` that is not finite is returned as it is.
|
||||
pub fn spread_param(&self, t: f64) -> f64 {
|
||||
self.spreader()(t)
|
||||
}
|
||||
/// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where
|
||||
/// `per_turn` would do for stops that run once around: that many for each time the stops run
|
||||
/// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its
|
||||
/// turn.
|
||||
pub fn conic_wedge_count(&self, per_turn: usize) -> usize {
|
||||
let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 };
|
||||
per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES)
|
||||
}
|
||||
/// [`Self::spread_param`] as a function that holds no borrow of the gradient.
|
||||
pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> {
|
||||
let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad };
|
||||
let n = f64::from(self.repeat_count());
|
||||
move |t: f64| {
|
||||
if !t.is_finite() {
|
||||
return t;
|
||||
}
|
||||
match spread {
|
||||
GradientSpread::Pad => t,
|
||||
GradientSpread::Repeat => (t * n).rem_euclid(1.0),
|
||||
GradientSpread::Reflect => {
|
||||
let w = (t * n).rem_euclid(2.0);
|
||||
if w > 1.0 { 2.0 - w } else { w }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Colour and opacity at `t` (honours midpoints and the method).
|
||||
pub fn sample(&self, t: f32) -> (Color, f32) {
|
||||
@@ -544,10 +680,18 @@ impl Gradient {
|
||||
GradientStop { opacity, ..GradientStop::new(offset, color) }
|
||||
};
|
||||
let d = to - from;
|
||||
let mut stops = vec![stop(0.0, from)];
|
||||
let expanded = self.expanded_stops();
|
||||
// Where stops share the offset `from` (a sharp step, as where the runs of a repeating
|
||||
// gradient meet), the piece starts with the color after the step; sampling gives the one
|
||||
// before it.
|
||||
let first = match expanded.iter().rev().find(|(t, ..)| *t == from) {
|
||||
Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) },
|
||||
_ => stop(0.0, from),
|
||||
};
|
||||
let mut stops = vec![first];
|
||||
if d > 1e-6 {
|
||||
stops.extend(
|
||||
self.expanded_stops()
|
||||
expanded
|
||||
.into_iter()
|
||||
.filter(|(t, ..)| *t > from && *t < to)
|
||||
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
|
||||
@@ -954,6 +1098,35 @@ impl GradientGeom {
|
||||
self.set_focal(Some(m * q));
|
||||
}
|
||||
}
|
||||
/// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or
|
||||
/// diamond gradient: the vector `k` times as long from the same start, and for an off-center
|
||||
/// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps
|
||||
/// its placement (its level is a turn).
|
||||
pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom {
|
||||
if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) {
|
||||
return *self;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let mut out = *self;
|
||||
if kind == GradientKind::Radial
|
||||
&& let (Some(f), Some(frame)) = (self.focal, self.unit_frame())
|
||||
{
|
||||
// Level t of an off-center radial is the extent ellipse scaled by t about the line
|
||||
// from the focal point to the center: the new center sits on that line, `k` times as
|
||||
// far from the focal point.
|
||||
let f = (frame.inverse() * f).to_vec2();
|
||||
out.start = frame * (f * (1.0 - k)).to_point();
|
||||
}
|
||||
out.end = out.start + u * k;
|
||||
out
|
||||
}
|
||||
|
||||
/// The placement over which one run of the stops of a gradient that repeats `n` times along
|
||||
/// its vector lies ([`Self::levels_scaled`] by 1/`n`).
|
||||
pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom {
|
||||
self.levels_scaled(kind, 1.0 / f64::from(n.max(1)))
|
||||
}
|
||||
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
let v = self.end - self.start;
|
||||
(-v.y).atan2(v.x).to_degrees()
|
||||
@@ -1148,12 +1321,13 @@ impl GradientPaint {
|
||||
inks: bool,
|
||||
) -> impl Iterator<Item = [u8; N]> + use<N> {
|
||||
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
|
||||
let spread = self.gradient.spreader();
|
||||
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
|
||||
let (x0, y0) = (area.x0, area.y0);
|
||||
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
|
||||
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
|
||||
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
|
||||
let c = ramp.at(geom.param_at(kind, p) as f32);
|
||||
let c = ramp.at(spread(geom.param_at(kind, p)) as f32);
|
||||
std::array::from_fn(|k| {
|
||||
if k + 1 == N {
|
||||
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad
|
||||
//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as
|
||||
//! the painted area needs, and the vector stretched over those runs.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
use super::{Gradient, GradientGeom, GradientKind, GradientSpread, GradientStop};
|
||||
|
||||
/// Most runs of the stops [`Gradient::padded_over`] writes.
|
||||
pub const MAX_SPREAD_RUNS: usize = 256;
|
||||
|
||||
/// Most stops [`Gradient::padded_over`] writes, all runs together.
|
||||
pub const MAX_SPREAD_STOPS: usize = 16384;
|
||||
|
||||
/// The farthest level from its center a radial or diamond gradient's runs are written out to by
|
||||
/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart),
|
||||
/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]).
|
||||
pub const MAX_SPREAD_LEVEL: f64 = 65536.0;
|
||||
|
||||
/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as
|
||||
/// different: sixteen times single precision's step just below 1.
|
||||
const MIN_OFFSET_GAP: f64 = 1e-6;
|
||||
|
||||
/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Padded {
|
||||
/// The gradient with its stops repeated, padding past its ends.
|
||||
pub gradient: Gradient,
|
||||
/// Where those runs lie.
|
||||
pub geom: GradientGeom,
|
||||
/// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the
|
||||
/// first run's level over the last one's outer level for a radial or diamond one.
|
||||
pub first: f64,
|
||||
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
|
||||
pub runs: usize,
|
||||
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or than [`MAX_SPREAD_STOPS`] allows),
|
||||
/// or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
|
||||
pub capped: bool,
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a
|
||||
/// gradient that pads and paints `area` the same way: its stops repeated, each run's
|
||||
/// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or
|
||||
/// diamond from its first level, 0, the first stop's color inside the area's innermost run).
|
||||
/// `None` for a gradient that pads, a conic or
|
||||
/// freeform one, one without stops, and a placement whose levels at the corners are not
|
||||
/// finite.
|
||||
pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option<Padded> {
|
||||
self.padded_within(geom, area, MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run).
|
||||
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
|
||||
let kind = self.kind;
|
||||
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
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));
|
||||
if ts.iter().any(|t| !t.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let centered = kind.is_centered();
|
||||
// The level's range over the area. A linear gradient's extremes lie at corners. Radial and
|
||||
// diamond levels are nested convex rings from level 0: the largest at a corner, the
|
||||
// smallest 0 when the area holds the rings' center, else on its edge.
|
||||
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
|
||||
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
|
||||
let one = whole_run(&self.stops);
|
||||
let most = MAX_SPREAD_RUNS.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
|
||||
let capped = hi - lo > most as f64;
|
||||
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
|
||||
// those around the vector's start where the area reaches it, else the area's runs nearest
|
||||
// to it.
|
||||
let lo = match capped {
|
||||
true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64),
|
||||
_ => lo,
|
||||
};
|
||||
let n = (hi - lo).min(most as f64).max(1.0);
|
||||
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
|
||||
// (single-precision fractions of the outermost level) tell apart only so far out, the
|
||||
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
|
||||
let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min);
|
||||
// A whole level, so the runs keep their places (and Reflect its mirrored ones).
|
||||
let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n);
|
||||
let far = centered && lo + n > farthest;
|
||||
let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) };
|
||||
// `lo` is a whole number, possibly past what an integer holds: its parity in floating point.
|
||||
let first_odd = lo.rem_euclid(2.0) >= 1.0;
|
||||
let (stops, geom) = if centered {
|
||||
// The levels from 0, the runs from level `lo` (the first stop's color inside it).
|
||||
(self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n))
|
||||
} else {
|
||||
let u = period.end - period.start;
|
||||
(
|
||||
self.runs(&one, first_odd, 0.0, n as usize, n),
|
||||
GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period },
|
||||
)
|
||||
};
|
||||
let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() };
|
||||
let first = if centered { lo / (lo + n) } else { 0.0 };
|
||||
Some(Padded { gradient, geom, first, runs: n as usize, capped })
|
||||
}
|
||||
|
||||
/// The gradient as it runs from the start of its vector (0) to its end (1), as one that
|
||||
/// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`]
|
||||
/// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that
|
||||
/// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are.
|
||||
pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> {
|
||||
self.unrolled_within(MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::unrolled`] with at most `max_stops` stops (and at least one run): past the runs
|
||||
/// that fit, the last one pads.
|
||||
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if !self.is_spread() {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
// Without stops there is nothing to repeat: it pads all the same.
|
||||
if self.stops.is_empty() {
|
||||
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let n = self.repeat_count() as usize;
|
||||
let kept = n.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
|
||||
let stops = self.runs(&one, false, 0.0, kept, n as f64);
|
||||
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
|
||||
}
|
||||
|
||||
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
|
||||
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
|
||||
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
|
||||
/// one without stops.
|
||||
pub fn cycle(&self) -> Option<(Gradient, u32)> {
|
||||
if !self.is_spread() || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
/// `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).
|
||||
fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec<GradientStop> {
|
||||
let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one));
|
||||
let mut stops = Vec::with_capacity(one.len() * n);
|
||||
for j in 0..n {
|
||||
let run = match &mirrored_run {
|
||||
Some(m) if (j % 2 == 1) != first_odd => m.as_slice(),
|
||||
_ => one,
|
||||
};
|
||||
stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() }));
|
||||
}
|
||||
stops
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding):
|
||||
/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the
|
||||
/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather
|
||||
/// than from samples along them, so a long side does not hide a run near it. 0 for a placement
|
||||
/// without a frame.
|
||||
fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 {
|
||||
let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start };
|
||||
if area.contains(center) {
|
||||
return 0.0;
|
||||
}
|
||||
let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() };
|
||||
let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 };
|
||||
let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2());
|
||||
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)]
|
||||
.map(|p| (to_unit * p).to_vec2());
|
||||
let mut least = f64::INFINITY;
|
||||
for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) {
|
||||
let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) };
|
||||
least = least.min(side);
|
||||
}
|
||||
if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the
|
||||
/// level is linear between the points where the segment crosses an axis, so the smallest is at
|
||||
/// an end or at one of those crossings.
|
||||
fn diamond_least(a: Vec2, b: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)];
|
||||
[Some(0.0), Some(1.0), crossings[0], crossings[1]]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|u| (0.0..=1.0).contains(u))
|
||||
.map(|u| {
|
||||
let p = a + d * u;
|
||||
p.x.abs() + p.y.abs()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level.
|
||||
const RADIAL_HALVINGS: usize = 1100;
|
||||
|
||||
/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter
|
||||
/// level under it: the distance to the center for a centered radial. An off-center radial's level
|
||||
/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance
|
||||
/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the
|
||||
/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the
|
||||
/// extent ellipse.
|
||||
fn radial_least(a: Vec2, b: Vec2, focal: Option<Vec2>) -> f64 {
|
||||
let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) };
|
||||
let reach = f.hypot();
|
||||
if reach.is_nan() || reach >= 1.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t;
|
||||
// At this level the circle reaches the segment's nearest point to the ellipse's center.
|
||||
let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0);
|
||||
let mut lo = 0.0;
|
||||
if !hi.is_finite() || past(lo) {
|
||||
return 0.0;
|
||||
}
|
||||
for _ in 0..RADIAL_HALVINGS {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if hi - lo <= 0.25 || mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
if past(mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
/// How far `c` is from the segment from `a` to `b`.
|
||||
fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let along = (c - a).dot(d) / d.hypot2();
|
||||
let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + d * u - c).hypot()
|
||||
}
|
||||
|
||||
/// The stops of one run, from offset 0 to 1: the end colors held out to the ends.
|
||||
fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut out = stops.to_vec();
|
||||
if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() {
|
||||
out.insert(0, GradientStop { offset: 0.0, ..first });
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
// The last stop's midpoint leads nowhere; the copy at 1 takes over.
|
||||
if last.offset < 1.0 {
|
||||
let end = GradientStop { offset: 1.0, ..last.clone() };
|
||||
out.push(end);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
|
||||
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
|
||||
g.reverse();
|
||||
g.stops
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,368 @@
|
||||
use kurbo::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::gradient::{GradientPaint, MAX_REPEATS};
|
||||
use crate::{Color, GradientMethod};
|
||||
|
||||
fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient {
|
||||
Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) }
|
||||
}
|
||||
|
||||
fn black_white() -> Vec<GradientStop> {
|
||||
let mut a = GradientStop::new(0.0, Color::BLACK);
|
||||
a.midpoint = 0.3;
|
||||
vec![a, GradientStop::new(1.0, Color::WHITE)]
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect
|
||||
/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has
|
||||
/// no ends to spread past.
|
||||
#[test]
|
||||
fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] {
|
||||
assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t));
|
||||
}
|
||||
let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] {
|
||||
assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t));
|
||||
}
|
||||
let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3);
|
||||
assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2));
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS);
|
||||
}
|
||||
|
||||
/// The native format writes the spread and count only when they are not Pad and 1, reads a file
|
||||
/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest
|
||||
/// one it can hold.
|
||||
#[test]
|
||||
fn the_file_keeps_the_spread_and_reads_bad_values_leniently() {
|
||||
let plain = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}");
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4)));
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
let read = |spread: serde_json::Value, repeats: serde_json::Value| {
|
||||
let mut v = serde_json::to_value(Gradient::default()).unwrap();
|
||||
v["spread"] = spread;
|
||||
v["repeats"] = repeats;
|
||||
let g: Gradient = serde_json::from_value(v).unwrap();
|
||||
(g.spread, g.repeats)
|
||||
};
|
||||
assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3));
|
||||
assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1));
|
||||
assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS));
|
||||
assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1));
|
||||
let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1));
|
||||
}
|
||||
|
||||
/// One run's placement: a level of the period is the gradient's level times the count, for
|
||||
/// linear, diamond and off-center radial gradients; a conic keeps its placement.
|
||||
#[test]
|
||||
fn a_period_holds_one_run_of_the_stops() {
|
||||
let p = Point::new(72.0, 61.0);
|
||||
let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None };
|
||||
let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) };
|
||||
let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let period = geom.period(kind, 4);
|
||||
assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}");
|
||||
assert_eq!(period.focal, geom.focal, "{kind:?}");
|
||||
}
|
||||
assert_eq!(radial.period(GradientKind::Conic, 4), radial);
|
||||
assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1");
|
||||
}
|
||||
|
||||
/// The stops repeated over the area: as many runs as its corners reach, each in place.
|
||||
#[test]
|
||||
fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap();
|
||||
assert!(!p.capped);
|
||||
// Runs of 10 from -10 to 30: four of them.
|
||||
assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0)));
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]);
|
||||
assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6));
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
// Every point gets the color the gradient gives it.
|
||||
for x in [-4.0, 1.0, 7.5, 13.0, 24.0] {
|
||||
let q = Point::new(x, 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;
|
||||
assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_mirrors_every_other_run_and_its_midpoints() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let colors: Vec<Color> = p.gradient.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]);
|
||||
// Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7.
|
||||
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
|
||||
}
|
||||
|
||||
#[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 };
|
||||
let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]);
|
||||
}
|
||||
|
||||
/// An off-center radial grows about its focal point, a diamond about its center; every point
|
||||
/// keeps its color.
|
||||
#[test]
|
||||
fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) };
|
||||
let diamond = GradientGeom { focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap();
|
||||
assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len());
|
||||
assert_eq!(p.geom.focal, geom.focal);
|
||||
for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of the stops far too short for the area, or a gradient of many stops, is written with at
|
||||
/// most so many runs and stops, and pads past them; a conic, a padding gradient and one without
|
||||
/// stops have nothing to pad.
|
||||
#[test]
|
||||
fn far_repeats_and_many_stops_are_capped() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS);
|
||||
let many: Vec<GradientStop> = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
|
||||
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
|
||||
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{}", p.gradient.stops.len());
|
||||
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
|
||||
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
|
||||
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) };
|
||||
assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
}
|
||||
|
||||
/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs
|
||||
/// from the area writes the hundred it crosses, not the first 256 from the center; a linear
|
||||
/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it.
|
||||
/// Every point checked gets the color the gradient gives it.
|
||||
#[test]
|
||||
fn the_runs_written_cover_a_distant_area() {
|
||||
let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None };
|
||||
let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None };
|
||||
for (kind, geom, area) in [
|
||||
(GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)),
|
||||
] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}");
|
||||
assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS);
|
||||
for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiny radial centered just outside the area, beside a side between any evenly spaced
|
||||
/// samples of it: the runs written start from the area's true innermost level.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_between_samples() {
|
||||
let c = Point::new(-0.0005, 7.8125);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap();
|
||||
for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's
|
||||
/// center: the runs written start from that side's true innermost level, so the runs beside it
|
||||
/// keep their colors.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_along_a_very_long_side() {
|
||||
let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0);
|
||||
for x in [0.3, 12345.678, -7777.25, 98765.4321] {
|
||||
let c = Point::new(x, -0.00005);
|
||||
let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run };
|
||||
for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert!(p.capped, "{kind:?}");
|
||||
for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] {
|
||||
let level = geom.param_at(kind, q);
|
||||
assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}");
|
||||
let want = g.sample(g.spread_param(level) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart:
|
||||
/// the gradient is written capped, its stops still apart and in order.
|
||||
#[test]
|
||||
fn runs_too_far_from_the_center_are_capped() {
|
||||
let c = Point::new(0.0, 0.0);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order");
|
||||
let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count();
|
||||
assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len());
|
||||
}
|
||||
|
||||
/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around
|
||||
/// level 50,000 it is capped, every stop written apart from the next.
|
||||
#[test]
|
||||
fn close_stops_are_written_only_where_they_stay_apart() {
|
||||
let many: Vec<GradientStop> = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect();
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) };
|
||||
let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap();
|
||||
assert!(p.capped);
|
||||
// Only where one run meets the next do two stops share an offset.
|
||||
let runs = p.gradient.stops.len() / 1001;
|
||||
let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count();
|
||||
assert!(shared < runs, "{shared} stops share an offset in {runs} runs");
|
||||
// Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within
|
||||
// it gets the gradient's colors, Reflect's mirrored runs included.
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap();
|
||||
assert!(p.capped, "past level 123 it pads");
|
||||
for x in [121.3, 121.9, 122.5] {
|
||||
let q = Point::new(x, 0.1);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a
|
||||
/// corner there) starts with the new run's first color, not the old run's last.
|
||||
#[test]
|
||||
fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() {
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) };
|
||||
let piece = g.unrolled().span(0.5, 1.0);
|
||||
assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops);
|
||||
assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK));
|
||||
let before = g.unrolled().span(0.0, 0.5);
|
||||
assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK));
|
||||
}
|
||||
|
||||
/// An area very far past a very short reflecting vector (a file's numbers) is padded without the
|
||||
/// run count overflowing.
|
||||
#[test]
|
||||
fn a_far_area_pads_without_overflowing() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0));
|
||||
assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS));
|
||||
// Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds.
|
||||
let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom };
|
||||
let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom);
|
||||
}
|
||||
|
||||
/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with
|
||||
/// Reflect); one cycle is a run, or a run and its mirror.
|
||||
#[test]
|
||||
fn unrolled_and_cycle_stops() {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let u = g.unrolled();
|
||||
let offsets: Vec<f32> = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect();
|
||||
assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]);
|
||||
let colors: Vec<Color> = u.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]);
|
||||
for t in [0.05, 0.4, 0.71, 0.99] {
|
||||
let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb());
|
||||
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}");
|
||||
}
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
assert_eq!((runs, cycle.stops.len()), (2, 4));
|
||||
let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() };
|
||||
assert_eq!(repeat.cycle().unwrap().1, 1);
|
||||
assert!(Gradient::default().cycle().is_none());
|
||||
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
|
||||
/// PDF write as images) repeat with the stops, for each kind.
|
||||
#[test]
|
||||
fn pixels_repeat_and_reflect_for_every_kind() {
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
let c = Point::new(20.0, 20.0);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
|
||||
for sp in [GradientSpread::Repeat, GradientSpread::Reflect] {
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) });
|
||||
let geom = if kind == GradientKind::Linear {
|
||||
GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None }
|
||||
} else {
|
||||
GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None }
|
||||
};
|
||||
g.geom = Some(geom);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect();
|
||||
for (i, got) in px.iter().enumerate().step_by(37) {
|
||||
let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5);
|
||||
let t = g.gradient.spread_param(geom.param_at(kind, p));
|
||||
// Not where Repeat jumps from the last stop back to the first.
|
||||
if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let want = g.gradient.sample(t as f32).0.to_rgba8(1.0);
|
||||
assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most
|
||||
/// so many.
|
||||
#[test]
|
||||
fn conic_wedges_count_each_run() {
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4);
|
||||
assert_eq!(g.conic_wedge_count(360), 1440);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ pub mod swatch;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop};
|
||||
pub use libraries::SwatchLibrary;
|
||||
pub use swatch::{Swatch, SwatchGroup, default_swatches};
|
||||
|
||||
|
||||
@@ -196,8 +196,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -261,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient swatch that repeats or reflects has its stops written that many times across the
|
||||
/// box, every other run backwards for Reflect.
|
||||
#[test]
|
||||
fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
for (spread, want) in [
|
||||
(crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"),
|
||||
(crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"),
|
||||
] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Bands".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -152,6 +152,11 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Two gradients that repeat (or reflect) step their count from one to the other; a spread
|
||||
// that differs switches halfway, as the method does.
|
||||
if a.gradient.is_spread() && a.gradient.spread == b.gradient.spread {
|
||||
out.gradient.repeats = lerp_f32(a.gradient.repeat_count() as f32, b.gradient.repeat_count() as f32, t).round() as u32;
|
||||
}
|
||||
out.angle = a.angle + (b.angle - a.angle) * t as f64;
|
||||
out.swatch = None;
|
||||
if let (Some(ga), Some(gb)) = (a.geom, b.geom) {
|
||||
@@ -1656,6 +1661,25 @@ mod tests {
|
||||
assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up");
|
||||
}
|
||||
|
||||
/// A blend between two gradients that repeat steps the count; one between a gradient that
|
||||
/// pads and one that repeats switches halfway, as the method does.
|
||||
#[test]
|
||||
fn blend_between_repeating_gradients_steps_the_count() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let spread = |spread, repeats| Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats, ..Gradient::default() })));
|
||||
let at = |a: &Paint, b: &Paint, t: f32| match lerp_paint(a, b, t) {
|
||||
Paint::Gradient(g) => (g.gradient.spread, g.gradient.repeat_count()),
|
||||
p => panic!("a gradient, not {p:?}"),
|
||||
};
|
||||
let (two, twenty) = (spread(GradientSpread::Repeat, 2), spread(GradientSpread::Repeat, 20));
|
||||
assert_eq!(at(&two, &twenty, 0.25), (GradientSpread::Repeat, 7));
|
||||
assert_eq!(at(&two, &twenty, 0.5), (GradientSpread::Repeat, 11));
|
||||
assert_eq!(at(&two, &twenty, 1.0), (GradientSpread::Repeat, 20));
|
||||
let pad = spread(GradientSpread::Pad, 1);
|
||||
assert_eq!(at(&pad, &twenty, 0.25), (GradientSpread::Pad, 1));
|
||||
assert_eq!(at(&pad, &twenty, 0.75), (GradientSpread::Repeat, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_between_tints_of_one_swatch_keeps_the_link() {
|
||||
let tinted = |tint: f32| Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint), swatch: Some("Spot".into()), tint };
|
||||
|
||||
+26
-4
@@ -133,6 +133,13 @@ pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Deco
|
||||
Some((d.colortype().ok()?, d))
|
||||
}
|
||||
|
||||
/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images
|
||||
/// and TIFFs without one. Reads only its header.
|
||||
pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
@@ -309,10 +316,10 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
Inks::new(w, h, read_samples(&mut d, n, 4)?)
|
||||
}
|
||||
|
||||
/// CMYK TIFF `bytes` as Open and Place store them: as they are, or, when they store one plane per
|
||||
/// ink, which the image decoder doesn't read, their ink amounts written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi`. `None` for other images and for CMYK
|
||||
/// TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
|
||||
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
|
||||
/// doesn't read, their ink amounts written again by [`ImageBlob::cmyk_tiff_at`] with the resolution
|
||||
/// `ppi`. `None` for other images and for CMYK TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
let inks = tiff_inks(bytes)?;
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
@@ -322,6 +329,21 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>
|
||||
ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes))
|
||||
}
|
||||
|
||||
/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their
|
||||
/// ink amounts ([`ImageBlob::cmyk`], 8 bits each) turned and written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi` of the turned pixels, with the turned
|
||||
/// width and height. `None` for other images and for CMYK images whose inks [`ImageBlob::cmyk`]
|
||||
/// doesn't read.
|
||||
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
|
||||
let inks = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }?;
|
||||
// Four 8-bit inks to a pixel, turned as four 8-bit channels are.
|
||||
let mut px = image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(inks.width, inks.height, inks.data)?);
|
||||
px.apply_orientation(orientation);
|
||||
let inks = Inks::new(px.width(), px.height(), px.into_bytes())?;
|
||||
let tiff = ImageBlob::cmyk_tiff_at(&inks, ppi)?;
|
||||
Some((Arc::unwrap_or_clone(tiff.bytes), (inks.width, inks.height)))
|
||||
}
|
||||
|
||||
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
|
||||
/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink
|
||||
/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB),
|
||||
|
||||
@@ -119,7 +119,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
{
|
||||
out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps));
|
||||
}
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
// A linked opacity mask bends with the object it masks; an unlinked one stays where it is.
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
m.art = Arc::new(map_node(&m.art, w));
|
||||
}
|
||||
match &mut out.kind {
|
||||
|
||||
@@ -180,6 +180,24 @@ impl ObjectsOnPath {
|
||||
});
|
||||
Some((spacing, start))
|
||||
}
|
||||
/// Move the object `member` to the place on the path of the object `target`: the objects
|
||||
/// between them each move one place toward where `member` was, except the objects for which
|
||||
/// `fixed` is true, which keep their places and are passed over. Only the order changes, not the
|
||||
/// Space or the start. Returns `member`'s new index, or `None` when either one is not an object
|
||||
/// of the group.
|
||||
pub fn move_member(&mut self, member: NodeId, target: NodeId, fixed: impl Fn(NodeId) -> bool) -> Option<usize> {
|
||||
let moves = |id: NodeId| id == member || id == target || !fixed(id);
|
||||
let slots: Vec<usize> = (0..self.members.len()).filter(|&i| moves(self.members[i].id)).collect();
|
||||
let from = slots.iter().position(|&i| self.members[i].id == member)?;
|
||||
let to = slots.iter().position(|&i| self.members[i].id == target)?;
|
||||
let mut moving: Vec<_> = slots.iter().map(|&i| self.members[i]).collect();
|
||||
let m = moving.remove(from);
|
||||
moving.insert(to, m);
|
||||
for (&i, m) in slots.iter().zip(moving) {
|
||||
self.members[i] = m;
|
||||
}
|
||||
Some(slots[to])
|
||||
}
|
||||
/// The children given new ids (a copy of the group): the path and the objects by their new ids.
|
||||
pub fn rename(&mut self, ids: &HashMap<NodeId, NodeId>) {
|
||||
let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id);
|
||||
@@ -487,6 +505,36 @@ mod tests {
|
||||
assert_eq!(layout(400.0, true, 4, Some(300.0), 400.0), (0.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_object_shifts_the_ones_between_it_and_its_new_place() {
|
||||
let (a, b, c) =
|
||||
(rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)), rect(4, Rect::new(40.0, 0.0, 50.0, 10.0)));
|
||||
let rec = ObjectsOnPath { spacing: Some(30.0), start: 5.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b, &c], CENTER, 15.0) };
|
||||
let order = |r: &ObjectsOnPath| r.members.iter().map(|m| m.id.0).collect::<Vec<_>>();
|
||||
let free = |_: NodeId| false;
|
||||
let mut fwd = rec.clone();
|
||||
assert_eq!(fwd.move_member(NodeId(2), NodeId(4), free), Some(2));
|
||||
assert_eq!(order(&fwd), [3, 4, 2], "the first to the last place");
|
||||
assert_eq!((fwd.spacing, fwd.start, fwd.pivot, fwd.rotate), (rec.spacing, rec.start, rec.pivot, rec.rotate));
|
||||
let mut back = rec.clone();
|
||||
assert_eq!(back.move_member(NodeId(4), NodeId(2), free), Some(0));
|
||||
assert_eq!(order(&back), [4, 2, 3], "the last to the first place");
|
||||
let mut same = rec.clone();
|
||||
assert_eq!(same.move_member(NodeId(3), NodeId(3), free), Some(1));
|
||||
assert_eq!(same, rec, "onto its own place");
|
||||
let mut other = rec.clone();
|
||||
assert_eq!(other.move_member(NodeId(1), NodeId(3), free), None, "the path is not one of the objects");
|
||||
assert_eq!(other.move_member(NodeId(3), NodeId(9), free), None);
|
||||
assert_eq!(other, rec);
|
||||
// A fixed object between them keeps its place; the others pass over it.
|
||||
let mut over = rec.clone();
|
||||
assert_eq!(over.move_member(NodeId(2), NodeId(4), |id| id == NodeId(3)), Some(2));
|
||||
assert_eq!(order(&over), [4, 3, 2], "the first and last trade places round the fixed one");
|
||||
let mut back_over = rec.clone();
|
||||
assert_eq!(back_over.move_member(NodeId(4), NodeId(2), |id| id == NodeId(3)), Some(0));
|
||||
assert_eq!(order(&back_over), [4, 3, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_saved_without_space_reads_as_auto() {
|
||||
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
|
||||
@@ -59,6 +59,11 @@ pub struct Selection {
|
||||
/// that object ([`crate::symbol_overrides`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub symbol_part: Option<SymbolPart>,
|
||||
/// An object of an Objects on Path group, chosen with its Select/Move widget: the group is the
|
||||
/// one selected object, and the object is one of its objects on the path
|
||||
/// ([`crate::objects_on_path::ObjectsOnPath::members`]). Any other selection change clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub on_path_member: Option<NodeId>,
|
||||
}
|
||||
|
||||
/// See [`Selection::symbol_part`].
|
||||
@@ -94,6 +99,13 @@ impl Selection {
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
}
|
||||
/// Select only the Objects on Path group `group`, with its object `member` (see
|
||||
/// [`Selection::on_path_member`]).
|
||||
pub fn set_on_path_member(&mut self, group: NodeId, member: NodeId) {
|
||||
self.set([group]);
|
||||
self.on_path_member = Some(member);
|
||||
}
|
||||
/// Select only instance `instance`, with the object at `path` of its symbol's art (see
|
||||
/// [`Selection::symbol_part`]).
|
||||
@@ -115,6 +127,7 @@ impl Selection {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
if !self.objects.contains(&id) {
|
||||
self.objects.push(id);
|
||||
}
|
||||
@@ -123,6 +136,7 @@ impl Selection {
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
self.objects.retain(|x| *x != id);
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
@@ -152,6 +166,7 @@ impl Selection {
|
||||
/// Shift-click on a guide).
|
||||
pub fn toggle_guide(&mut self, i: NodeId) {
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
if let Some(k) = self.guides.iter().position(|g| *g == i) {
|
||||
self.guides.remove(k);
|
||||
if self.key_guide == Some(i) {
|
||||
@@ -258,6 +273,22 @@ impl Selection {
|
||||
if !part_kept {
|
||||
self.symbol_part = None;
|
||||
}
|
||||
// A chosen object on a path needs its Objects on Path group selected alone, with no anchors
|
||||
// or guides, and still one of the group's objects, neither hidden nor locked.
|
||||
let member_kept = self.on_path_member.is_some_and(|m| {
|
||||
let [g] = self.objects.as_slice() else { return false };
|
||||
self.anchors.is_empty()
|
||||
&& self.guides.is_empty()
|
||||
&& doc.is_editable(m)
|
||||
&& found
|
||||
.get(g)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
.and_then(|n| n.extras().objects_on_path.as_deref().filter(|_| crate::objects_on_path::is_objects_on_path(n)))
|
||||
.is_some_and(|rec| rec.members.iter().any(|x| x.id == m))
|
||||
});
|
||||
if !member_kept {
|
||||
self.on_path_member = None;
|
||||
}
|
||||
}
|
||||
/// Deselect the objects that are hidden or locked, themselves or through a group or layer
|
||||
/// around them (and so the key object when it is one): hidden or locked art can't stay
|
||||
|
||||
@@ -179,6 +179,49 @@ fn selection_changes_clear_the_target() {
|
||||
assert_eq!(s.target, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_object_on_a_path_needs_its_group_selected_alone() {
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (line, a, b, g, other) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let line = Node::path(line, shapes::line(Point::new(0.0, 100.0), Point::new(200.0, 100.0)), Default::default());
|
||||
let a = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default());
|
||||
let b = Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Default::default());
|
||||
let rec = crate::objects_on_path::ObjectsOnPath::new(line.id, &[&a, &b], crate::objects_on_path::CENTER, 0.0);
|
||||
let (line_id, a_id) = (line.id, a.id);
|
||||
let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a), Arc::new(b)], clip: false });
|
||||
group.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(other, shapes::rectangle(Rect::new(150.0, 0.0, 160.0, 10.0)), Default::default())).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.set_on_path_member(g, a_id);
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], Some(a_id)));
|
||||
s.add(other);
|
||||
assert_eq!(s.on_path_member, None, "another object joins the selection");
|
||||
s.set_on_path_member(g, a_id);
|
||||
s.set([g]);
|
||||
assert_eq!(s.on_path_member, None, "a new selection");
|
||||
// The path is not one of the objects, nor is an object outside the group.
|
||||
for m in [line_id, other] {
|
||||
s.set_on_path_member(g, m);
|
||||
s.prune(&d);
|
||||
assert_eq!(s.on_path_member, None, "{m:?}");
|
||||
}
|
||||
// A locked object is not chosen.
|
||||
s.set_on_path_member(g, a_id);
|
||||
d.node_mut(a_id).unwrap().locked = true;
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None), "locked");
|
||||
d.node_mut(a_id).unwrap().locked = false;
|
||||
// Once the group is a plain group, no object of it is chosen.
|
||||
s.set_on_path_member(g, a_id);
|
||||
d.node_mut(g).unwrap().extras_mut().objects_on_path = None;
|
||||
s.prune(&d);
|
||||
assert_eq!((s.objects.as_slice(), s.on_path_member), (&[g][..], None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_object_needs_two_or_more_selected_objects() {
|
||||
let mut s = Selection::default();
|
||||
|
||||
@@ -690,6 +690,525 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A white 10 pt square with id `id` at the origin.
|
||||
fn white_square(id: u64) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// `n` masked by `art`, linked or not.
|
||||
fn masked_by(mut n: Node, art: Node, linked: bool) -> Node {
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, true);
|
||||
mask.linked = linked;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// The geometry effects that reshape a group's members, one at a time.
|
||||
fn reshaping_effects() -> Vec<Effect> {
|
||||
let fx = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
|
||||
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
vec![
|
||||
fx("distort.transform", serde_json::json!({"moveH": 30})),
|
||||
fx("distort.transform", serde_json::json!({"rotate": 90})),
|
||||
fx("distort.twist", serde_json::json!({"angle": 90})),
|
||||
fx("distort.freeDistort", corners),
|
||||
fx("warp.arc", serde_json::json!({})),
|
||||
fx("distort.roughen", serde_json::json!({"size": 5, "seed": 3})),
|
||||
fx("distort.zigZag", serde_json::json!({})),
|
||||
fx("distort.puckerBloat", serde_json::json!({"amount": 50})),
|
||||
fx("distort.tweak", serde_json::json!({})),
|
||||
fx("path.offsetPath", serde_json::json!({"offset": 3})),
|
||||
fx("stylize.roundCorners", serde_json::json!({"radius": 3})),
|
||||
]
|
||||
}
|
||||
|
||||
/// A group's geometry effect reshapes the art of a member's linked opacity mask as it reshapes the
|
||||
/// member: a mask drawn over the member still covers it. An unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_a_members_linked_mask_with_it() {
|
||||
let square = white_square(1);
|
||||
let original = square.path_data().cloned();
|
||||
for e in reshaping_effects() {
|
||||
for linked in [true, false] {
|
||||
let member = masked_by(square.clone(), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = member.extras().mask.as_deref().unwrap();
|
||||
assert!(member.path_data().cloned() != original, "{}: the member is reshaped", e.id);
|
||||
let want = if linked { member.path_data().cloned() } else { original.clone() };
|
||||
assert_eq!(mask.art.path_data().cloned(), want, "{} (linked: {linked})", e.id);
|
||||
assert_eq!(mask.linked, linked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask of a group inside the group, the mask of a path in it, a mask inside that mask's art and
|
||||
/// an inverted mask all take the outer group's effect with the paths they mask.
|
||||
#[test]
|
||||
fn a_groups_geometry_effects_reshape_nested_and_inverted_masks() {
|
||||
for e in reshaping_effects() {
|
||||
let innermost = masked_by(white_square(7), white_square(8), true);
|
||||
let path = masked_by(white_square(1), masked_by(white_square(6), innermost, true), true);
|
||||
let mut inner = masked_by(Node::group(NodeId(5), vec![Arc::new(path)]), white_square(4), true);
|
||||
if let Some(m) = inner.extras_if_any().and_then(|x| x.mask.as_mut()) {
|
||||
m.invert = true;
|
||||
}
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let path = &inner.children().unwrap()[0];
|
||||
let want = path.path_data().cloned();
|
||||
let mask_of = |n: &Node| n.extras().mask.as_deref().map(|m| (*m.art).clone()).unwrap();
|
||||
let (outer_mask, path_mask) = (mask_of(inner), mask_of(path));
|
||||
assert!(inner.extras().mask.as_deref().is_some_and(|m| m.invert));
|
||||
assert_eq!(outer_mask.path_data().cloned(), want, "{}: the inner group's inverted mask", e.id);
|
||||
assert_eq!(path_mask.path_data().cloned(), want, "{}: the path's mask", e.id);
|
||||
assert_eq!(mask_of(&path_mask).path_data().cloned(), want, "{}: the mask inside the mask's art", e.id);
|
||||
assert_eq!(mask_of(&mask_of(&path_mask)).path_data().cloned(), want, "{}: one level deeper", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of a path with a linked mask are objects of their own, each with the
|
||||
/// mask moved with it; the original keeps its mask where it was.
|
||||
#[test]
|
||||
fn each_transform_copy_of_a_masked_member_carries_its_mask() {
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
|
||||
assert_eq!(copies.len(), 3);
|
||||
for c in copies {
|
||||
let mask = c.extras().mask.as_deref().unwrap();
|
||||
assert_eq!(mask.art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect's copies of the paths of a member group give the group's linked mask the same
|
||||
/// copies: the mask covers each copy.
|
||||
#[test]
|
||||
fn a_member_groups_mask_takes_the_transform_copies_of_its_paths() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "the path and its copy");
|
||||
assert_eq!(inner.extras().mask.as_deref().unwrap().art.geometric_bounds(), want);
|
||||
}
|
||||
|
||||
/// A mask's art of several objects takes Transform copies whole, as the art it masks does: each copy
|
||||
/// of the mask's art is a group of its objects, so the copies do not interleave object by object.
|
||||
#[test]
|
||||
fn a_masks_art_of_several_objects_is_copied_whole() {
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let copies = mask.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "the mask's art and its copy");
|
||||
for c in copies {
|
||||
let ids: Vec<NodeId> = c.children().into_iter().flatten().map(|m| m.id).collect();
|
||||
assert_eq!(ids, [NodeId(4), NodeId(5)], "each copy holds the mask's objects");
|
||||
}
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)));
|
||||
}
|
||||
|
||||
/// The linked mask of a mask's art that is copied whole takes the same Transform copies.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_takes_its_copies() {
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 1});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)), "the mask's art and its copy");
|
||||
let own = &mask.extras().mask.as_deref().expect("the mask's art keeps its own mask").art;
|
||||
assert_eq!(own.geometric_bounds(), Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "its mask covers the copy too");
|
||||
}
|
||||
|
||||
/// The mask of a mask's art copied whole stays in the budget while that art is copied: when the
|
||||
/// budget has no room for that mask's copy, the art keeps its shape with its masks.
|
||||
#[test]
|
||||
fn the_mask_of_a_masks_art_copied_whole_counts_against_the_budget() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
|
||||
let mask_art = masked_by(parts, white_square(6), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the four squares and the copies of three of them, not for the copy of the fourth.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 7 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(inner.geometric_bounds(), square, "the path keeps its shape");
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 15.0, 10.0)), "and so does its mask");
|
||||
}
|
||||
|
||||
/// When a member group's linked mask can't take all the Transform copies its paths take (past the
|
||||
/// budget), the art keeps its shape under the effect, so the mask still covers the paths.
|
||||
#[test]
|
||||
fn art_whose_mask_would_take_fewer_copies_keeps_its_shape() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
|
||||
let member = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and a copy of the path, not for a copy of the mask.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 3 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert_eq!(member.geometric_bounds(), square, "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), square, "and so does its mask");
|
||||
}
|
||||
|
||||
/// The copies of a path with a linked mask count the art of the mask each copy carries against the
|
||||
/// budget: they stop where the masks would pass it.
|
||||
#[test]
|
||||
fn transform_copies_count_the_art_of_their_masks() {
|
||||
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 2}), visible: true };
|
||||
let member = masked_by(white_square(1), white_square(4), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
|
||||
// Room for the path, its mask and one copy of both, not for a second copy.
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 4 * one };
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
|
||||
let copies = art.children().unwrap()[0].children().expect("the object and its copy are objects of their own");
|
||||
assert_eq!(copies.len(), 2);
|
||||
for c in copies {
|
||||
assert_eq!(c.extras().mask.as_deref().unwrap().art.geometric_bounds(), c.geometric_bounds());
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that scales strokes moves a group's paths as objects, their masks with them.
|
||||
/// The mask of a member group, whose art holds a path with a mask of its own, moves with the group's
|
||||
/// paths too.
|
||||
#[test]
|
||||
fn a_transform_that_moves_paths_as_objects_moves_a_member_groups_nested_mask() {
|
||||
let mask_art = masked_by(white_square(4), white_square(5), true);
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(3, 20.0, Color::BLACK)]);
|
||||
let params = serde_json::json!({"moveH": 30, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let want = inner.children().unwrap()[0].geometric_bounds();
|
||||
assert_eq!(want, Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), want, "the group's mask");
|
||||
assert_eq!(mask.extras().mask.as_deref().unwrap().art.geometric_bounds(), want, "the mask inside its art");
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves an image member's linked opacity mask with the image, and its
|
||||
/// copies' masks with the copies; an unlinked mask stays.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_an_image_members_linked_mask() {
|
||||
for linked in [true, false] {
|
||||
for copies in [0, 2] {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), white_square(4), linked);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": copies});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let first = &art.children().unwrap()[0];
|
||||
let images: Vec<&Node> = match first.children() {
|
||||
Some(ch) => ch.iter().map(|c| &**c).collect(),
|
||||
None => vec![first],
|
||||
};
|
||||
assert_eq!(images.len(), copies + 1);
|
||||
for im in images {
|
||||
let mask = im.extras().mask.as_deref().unwrap();
|
||||
let want = if linked { im.geometric_bounds() } else { Some(Rect::new(0.0, 0.0, 10.0, 10.0)) };
|
||||
assert_eq!(mask.art.geometric_bounds(), want, "linked {linked}, copies {copies}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a path in a member's mask art would pass the effects' budget, the whole mask stays as it
|
||||
/// was, rather than part of its art moving with the member, and the member keeps its shape with it.
|
||||
#[test]
|
||||
fn a_mask_whose_art_passes_the_budget_stays_whole() {
|
||||
// Bloat bends a path's sides into curves drawn with more lines the larger they are: many more
|
||||
// on the mask's large square.
|
||||
let bloat = Effect { id: "distort.puckerBloat".into(), params: serde_json::json!({"amount": 50}), visible: true };
|
||||
let large = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), Appearance::default());
|
||||
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), Arc::new(large.clone())]);
|
||||
let member = masked_by(white_square(1), mask_art.clone(), true);
|
||||
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
// Room for the member and the mask's small square to take the effect, not for the large one.
|
||||
let bounds = art.geometric_bounds().unwrap();
|
||||
let ctx = crate::GeomContext { seed: 10, ..crate::GeomContext::of(&art) };
|
||||
let square = white_square(1).path_data().cloned().unwrap();
|
||||
let made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), &square, bounds, &ctx)).lines;
|
||||
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 2 * made + crate::Budget::of(large.path_data().unwrap()).lines };
|
||||
let large_made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), large.path_data().unwrap(), bounds, &ctx)).lines;
|
||||
assert!(large_made > crate::Budget::of(large.path_data().unwrap()).lines, "the large square's curves cost more lines");
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&bloat], budget, None);
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), Some(&square), "the member keeps its shape with its mask");
|
||||
assert_eq!(*member.extras().mask.as_deref().unwrap().art, mask_art, "the mask stays whole");
|
||||
}
|
||||
|
||||
/// Live objects in a member's linked mask are evaluated before the group's geometry effects run
|
||||
/// over the mask's art, so the mask still covers the member: a Repeat in it moves and bends with
|
||||
/// the member.
|
||||
#[test]
|
||||
fn a_groups_effects_reshape_a_live_object_in_a_members_mask() {
|
||||
let mut grid = vectorcraft_doc::RepeatSpec::grid(vec![Arc::new(white_square(5))], 0.0, 0.0);
|
||||
if let vectorcraft_doc::RepeatKind::Grid { rows, cols, .. } = &mut grid.kind {
|
||||
(*rows, *cols) = (1, 1);
|
||||
}
|
||||
let repeat = Node::new(NodeId(4), NodeKind::Repeat(grid));
|
||||
let drawn: Vec<Node> = crate::expand_live(None, &repeat);
|
||||
let leaf = |n: &Node| {
|
||||
let mut found = None;
|
||||
n.walk(&mut |c| found = found.take().or_else(|| c.path_data().cloned()));
|
||||
found
|
||||
};
|
||||
assert_eq!(drawn.iter().find_map(leaf), white_square(1).path_data().cloned(), "the Repeat draws one square over the member");
|
||||
for e in [reshaping_effects()[0].clone(), reshaping_effects()[4].clone()] {
|
||||
let member = masked_by(white_square(1), repeat.clone(), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert!(member.path_data() != white_square(1).path_data(), "{}: the member is reshaped", e.id);
|
||||
assert_eq!(leaf(mask), member.path_data().cloned(), "{}: the mask's square takes the effect with it", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Type in a member's linked mask is outlined before the group's Transform effect moves the mask's
|
||||
/// art with the member.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_type_in_a_members_mask() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
let member = masked_by(white_square(1), type_h(), true);
|
||||
let before = crate::reshape::outline_text(&type_h()).unwrap().geometric_bounds().unwrap();
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
|
||||
let mut text = false;
|
||||
mask.walk(&mut |c| text |= matches!(c.kind, NodeKind::Text(_)));
|
||||
assert!(!text, "the type is outlined");
|
||||
let after = mask.geometric_bounds().unwrap();
|
||||
assert!((after.x0 - before.x0 - 30.0).abs() < 0.5 && (after.y0 - before.y0).abs() < 0.5, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// The linked mask of a compound path in a group, and of a path in a layer, takes the geometry
|
||||
/// effects with the art it masks.
|
||||
#[test]
|
||||
fn a_compound_paths_and_a_layers_members_masks_take_the_effects() {
|
||||
let geometry = |n: &Node| crate::reshape::leaf_geometry(n).map(|(p, _)| p);
|
||||
for e in reshaping_effects() {
|
||||
let square = white_square(1);
|
||||
let compound = Node::new(NodeId(1), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: FillRule::NonZero });
|
||||
let compound = masked_by(compound, white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(compound), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(geometry(member) != square.path_data().cloned(), "{}: the compound path is reshaped", e.id);
|
||||
assert_eq!(geometry(&member.extras().mask.as_deref().unwrap().art), geometry(member), "{}: compound path", e.id);
|
||||
|
||||
let mut layer = Node::layer(NodeId(10), "Layer", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
ch.extend([Arc::new(masked_by(square.clone(), white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
}
|
||||
layer.appearance.effects.push(e.clone());
|
||||
let art = evaluate_container(None, &layer).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert!(member.path_data() != square.path_data(), "{}: the layer's path is reshaped", e.id);
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.path_data(), member.path_data(), "{}: layer", e.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect moves a symbol instance member's linked mask with the instance.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_symbol_instance_members_linked_mask() {
|
||||
let instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(instance, white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let instance = &art.children().unwrap()[0];
|
||||
let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {instance:?}") };
|
||||
assert!((xf.translation().x - 30.0).abs() < 1e-9, "the instance moves: {xf:?}");
|
||||
let mask = instance.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
assert!((mask.x0 - 30.0).abs() < 1e-9 && (mask.x1 - 40.0).abs() < 1e-9, "its mask moves with it: {mask:?}");
|
||||
}
|
||||
|
||||
/// With Scale Strokes & Effects on, a group's Transform effect scales the stroke of an image
|
||||
/// member's linked mask as it scales that of a path member's mask.
|
||||
#[test]
|
||||
fn a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike() {
|
||||
let stroked =
|
||||
Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0));
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), stroked.clone(), true);
|
||||
let path = masked_by(white_square(2), stroked, true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image), Arc::new(path)]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let width = |n: &Node| n.extras().mask.as_deref().unwrap().art.appearance.stroke().map(|s| s.width);
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(width(&ch[1]), Some(4.0), "the path's mask");
|
||||
assert_eq!(width(&ch[0]), width(&ch[1]), "the image's mask");
|
||||
}
|
||||
|
||||
/// With Transform Objects off and Scale Strokes & Effects on, a group's Transform effect scales the
|
||||
/// strokes of a member's linked mask as it scales the member's, and moves neither.
|
||||
#[test]
|
||||
fn a_transform_of_strokes_only_scales_a_members_mask_strokes() {
|
||||
let stroked = |id: u64| {
|
||||
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0))
|
||||
};
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(stroked(1), stroked(4), true))]);
|
||||
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
let mask = &member.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(member.appearance.stroke().map(|s| s.width), Some(4.0), "the member's stroke");
|
||||
assert_eq!(mask.appearance.stroke().map(|s| s.width), Some(4.0), "the mask's stroke");
|
||||
assert_eq!(mask.geometric_bounds(), member.geometric_bounds());
|
||||
}
|
||||
|
||||
/// The art of a member group's mask is copied as it was before the first effect: a mask of one
|
||||
/// path takes a second Transform effect's copies path by path, as the path it masks does, though
|
||||
/// the first effect (with Scale Strokes & Effects) made it a group of copies.
|
||||
#[test]
|
||||
fn a_masks_art_is_copied_as_it_was_before_the_first_effect() {
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
for strokes in [true, false] {
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2, "strokes": strokes});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds());
|
||||
let kinds = |n: &Node| n.children().unwrap().iter().map(|c| std::mem::discriminant(&c.kind)).collect::<Vec<_>>();
|
||||
let paths = &inner.children().unwrap()[0];
|
||||
assert_eq!(kinds(paths).len(), 3, "the first effect's three paths");
|
||||
assert!(paths.children().unwrap().iter().all(|c| matches!(c.kind, NodeKind::Compound { .. })), "each with its copies");
|
||||
assert_eq!(kinds(mask), kinds(paths), "the mask's art takes the copies as the paths do");
|
||||
}
|
||||
|
||||
/// A 10 × 10 image with id `id` at the origin.
|
||||
fn image_node(id: u64) -> Node {
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: vectorcraft_geom::Affine::IDENTITY,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
Node::new(NodeId(id), NodeKind::Image(Box::new(im)))
|
||||
}
|
||||
|
||||
/// A linked mask whose art is an image moves with the path it masks under a group's Transform
|
||||
/// effect, and a member group's image mask takes the copies its paths take.
|
||||
#[test]
|
||||
fn a_groups_transform_moves_a_linked_mask_whose_art_is_an_image() {
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(white_square(1), image_node(4), true)), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[0].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.geometric_bounds(), Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), member.geometric_bounds());
|
||||
|
||||
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), image_node(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
|
||||
let params = serde_json::json!({"moveH": 30, "copies": 2});
|
||||
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let inner = &art.children().unwrap()[0];
|
||||
assert_eq!(inner.geometric_bounds(), Some(Rect::new(0.0, 0.0, 70.0, 10.0)));
|
||||
let mask = &inner.extras().mask.as_deref().unwrap().art;
|
||||
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds(), "the image and its copies");
|
||||
}
|
||||
|
||||
/// An image in a linked mask's art takes no geometry effect but Transform, so under a Warp effect
|
||||
/// the art keeps its shape with its mask.
|
||||
#[test]
|
||||
fn art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp() {
|
||||
let member = masked_by(white_square(1), Node::group(NodeId(3), vec![Arc::new(image_node(4))]), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let member = &art.children().unwrap()[0];
|
||||
assert_eq!(member.path_data(), white_square(1).path_data(), "the path keeps its shape");
|
||||
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
|
||||
}
|
||||
|
||||
/// A Warp effect bends an image's pixels but not the art of its linked mask, so art with such an
|
||||
/// image keeps its shape under the warp, with the image and its mask.
|
||||
#[test]
|
||||
fn art_with_a_masked_image_keeps_its_shape_under_a_warp() {
|
||||
let image = masked_by(image_node(1), white_square(4), true);
|
||||
let mut g = Node::group(NodeId(10), vec![Arc::new(image.clone()), sq(2, 20.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(reshaping_effects()[4].clone());
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(*ch[0], image, "the image and its mask");
|
||||
assert_eq!(ch[1].path_data(), sq(2, 20.0, Color::BLACK).path_data(), "the path keeps its shape");
|
||||
}
|
||||
|
||||
/// A symbol instance in perspective projects the linked masks of the objects in its art with them.
|
||||
#[test]
|
||||
fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(masked_by(white_square(21), white_square(22), true))]);
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut at = vectorcraft_doc::PerspectiveAttachment::new("left", 0.0);
|
||||
at.projection = Some([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.01, 0.0, 1.0]);
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let mut masked = vec![];
|
||||
out.walk(&mut |c| masked.extend(c.extras().mask.as_deref().map(|m| (c.path_data().cloned(), m.art.path_data().cloned()))));
|
||||
let [(path, mask)] = masked.as_slice() else { panic!("one masked path: {masked:?}") };
|
||||
assert!(path != &white_square(21).path_data().cloned(), "the path is projected");
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
|
||||
+427
-59
@@ -12,7 +12,7 @@
|
||||
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
|
||||
//! them ([`image_rows`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -590,7 +590,7 @@ fn as_art_opts(
|
||||
transform_items(&mut art, paint_doc);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
project_leaves(&mut art, &h);
|
||||
project_leaves(&mut art, &h, paint_doc);
|
||||
}
|
||||
// The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip
|
||||
// group).
|
||||
@@ -608,9 +608,29 @@ fn as_art_opts(
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Map every path under `art` (and its gradients) through the projective map `h`, curves split
|
||||
/// finely enough to follow it.
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
|
||||
/// masks of the objects under it, through the projective map `h`, curves split finely enough to
|
||||
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
|
||||
/// first ([`outlined_members`], with the symbols of `doc`).
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
project_paths(art, h);
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| {
|
||||
*m = outlined_mask_art(doc, m);
|
||||
project_paths(m, h);
|
||||
});
|
||||
}
|
||||
|
||||
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
|
||||
/// ([`outlined_members`]), and as art that keeps its look ([`as_art`]) when it is type itself.
|
||||
fn outlined_mask_art(doc: Option<&Document>, art: &Node) -> Node {
|
||||
match art.kind {
|
||||
NodeKind::Text(_) => as_art(doc, art, None).unwrap_or_else(|| art.clone()),
|
||||
_ => outlined_members(doc, art),
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths of [`project_leaves`] outside the art of masks.
|
||||
fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
let f = |p: vectorcraft_geom::Point| h.apply(p).unwrap_or(p);
|
||||
let piece = art.geometric_bounds().map_or(1.0, |b| (b.width().max(b.height()) / 64.0).max(0.25));
|
||||
let project = |path: &mut PathData| *path = vectorcraft_doc::live::map_nonlinear(path, piece, f);
|
||||
@@ -687,58 +707,151 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// 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
|
||||
/// 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.
|
||||
/// `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
|
||||
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return whole;
|
||||
}
|
||||
let mut leaves_safe = true;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
if !leaves_safe {
|
||||
return;
|
||||
}
|
||||
if let Some((_, rule)) = leaf_geometry(leaf) {
|
||||
let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
if rule != FillRule::NonZero || has_stroke {
|
||||
leaves_safe = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
let masked = has_linked_mask(art, false);
|
||||
if masked {
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| *m = outlined_mask_art(doc, m));
|
||||
}
|
||||
let mut masks_safe = true;
|
||||
each_linked_mask(art, false, 0, &mut |_, m| masks_safe &= leaves_safe(m));
|
||||
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
let style_safe = leaves_safe && !art_stroke;
|
||||
let style_safe = leaves_safe(art) && masks_safe && !art_stroke;
|
||||
let listed = fx;
|
||||
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
|
||||
let fx = opt_fx.as_slice();
|
||||
let seed = art.id.0;
|
||||
let mut used = art_cost(art);
|
||||
each_linked_mask(art, false, 0, &mut |_, m| used = used.plus(art_cost(m)));
|
||||
let max = budget.at_least(used);
|
||||
// Read before the effects run: a path's own copies don't make it art of several objects.
|
||||
// Read before the effects run: a path's own copies don't make it art of several objects. The
|
||||
// same holds for the art of each mask, listed by the object it masks.
|
||||
let copy_whole = copies_whole(art);
|
||||
let mut wholes = HashMap::new();
|
||||
each_linked_mask(art, false, 0, &mut |id, m| {
|
||||
wholes.entry(id).or_insert_with(|| copies_whole(m));
|
||||
});
|
||||
let mut warped = WarpedImages::new();
|
||||
for e in fx {
|
||||
let Some(bounds) = warped.bounds(art) else { break };
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
|
||||
if (ran.masks || ran.short)
|
||||
&& let Some((was, cost)) = before
|
||||
{
|
||||
*art = was;
|
||||
used = cost;
|
||||
continue;
|
||||
}
|
||||
if let Some(carry) = ran.whole {
|
||||
whole.push(carry);
|
||||
}
|
||||
}
|
||||
cut_warped_images(art, &warped);
|
||||
whole
|
||||
}
|
||||
|
||||
/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its
|
||||
/// merged params, the reference box and seed of the object's art, where a deferred live-effect
|
||||
/// plug-in is listed, whether each Transform copy becomes an object, the document that the
|
||||
/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of
|
||||
/// each linked mask before the first effect, by the id of the object it masks.
|
||||
struct Step<'a> {
|
||||
e: &'a Effect,
|
||||
params: &'a serde_json::Value,
|
||||
bounds: Rect,
|
||||
seed: u64,
|
||||
effect: Option<usize>,
|
||||
apart: bool,
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
}
|
||||
|
||||
/// What [`Step::run`] did to a piece of art.
|
||||
struct Ran {
|
||||
/// A path in the art kept its shape (past the budget).
|
||||
kept: 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,
|
||||
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number.
|
||||
short: bool,
|
||||
/// How what paints the art as a whole follows the effect, when it does.
|
||||
whole: Option<crate::Carry>,
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
/// Nothing in the art kept its shape or made fewer copies, and every linked mask in it moved.
|
||||
fn complete(&self) -> bool {
|
||||
!self.kept && !self.masks && !self.short
|
||||
}
|
||||
}
|
||||
|
||||
impl Step<'_> {
|
||||
/// Run the effect over `art`, whose paths and those of the linked opacity masks in it keep to
|
||||
/// `max` together with what they cost so far (`used`). `copy_whole` is [`copies_whole`] of the
|
||||
/// art, or of a mask's art, before the first effect. `warped` lists the images Warp effects
|
||||
/// bend in the art ([`WarpedImages`]); a mask's art has none. With `own`, `art` is the art of a
|
||||
/// mask, and its own linked mask takes the effect too. `depth` counts the masks `art` is in. A
|
||||
/// live-effect plug-in that paints its pieces leaves a mask's art, and art that holds objects
|
||||
/// with linked masks, as they are and reports the masks as stayed: a mask can't take the
|
||||
/// pieces as the art it masks does. So does a Warp effect that bends an image with a linked
|
||||
/// mask.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run(
|
||||
&self,
|
||||
art: &mut Node,
|
||||
max: Budget,
|
||||
used: &mut Budget,
|
||||
copy_whole: bool,
|
||||
mut warped: Option<&mut WarpedImages>,
|
||||
own: bool,
|
||||
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 };
|
||||
if let Some(plugin) = painted_plugin(e) {
|
||||
let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
if own || has_linked_mask(art, false) {
|
||||
return stayed;
|
||||
}
|
||||
let at = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let Some((path, _)) = leaf_geometry(leaf) else { return };
|
||||
let before = Budget::of(&path);
|
||||
let room = max.minus(used.minus(before));
|
||||
if let Some(made) = paint_leaf(leaf, plugin, ¶ms, bounds, room, doc, at) {
|
||||
used = used.minus(before).plus(made);
|
||||
if let Some(made) = paint_leaf(leaf, plugin, params, bounds, room, self.doc, at) {
|
||||
*used = used.minus(before).plus(made);
|
||||
}
|
||||
});
|
||||
continue;
|
||||
return Ran { kept: false, 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.
|
||||
let warp = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).filter(|_| crate::warp::bends(&e.id, params));
|
||||
if warp.is_some() && has_masked_image(art) {
|
||||
return stayed;
|
||||
}
|
||||
// Placed gradients follow a Transform effect, Free Distort and the Warp effects
|
||||
// ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from
|
||||
// its bounds before the effect to its bounds after it. Under those and the other effects,
|
||||
// the placed gradients of type's outlines in `art` (`outline_text`) move and scale with
|
||||
// the outlines' bounds.
|
||||
let follows = crate::Carry::follows(&e.id, ¶ms, bounds, seed);
|
||||
let follows = crate::Carry::follows(&e.id, params, bounds, seed);
|
||||
let boxes = follows && crate::Carry::by_bounds(&e.id);
|
||||
let mut outlines = vec![];
|
||||
if !follows || boxes {
|
||||
@@ -754,30 +867,61 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
// The images earlier Warps bend are measured by their pieces only when a group's
|
||||
// gradient needs the bounds.
|
||||
if !groups.is_empty()
|
||||
&& let Some(images) = warped.when_cut(art)
|
||||
&& let Some(images) = warped.as_deref().and_then(|w| w.when_cut(art))
|
||||
{
|
||||
groups.clear();
|
||||
group_marks(art, &mut vec![], &HashSet::new(), Some(images), &mut groups);
|
||||
}
|
||||
}
|
||||
// The ids of the paths that kept their shape (past the budget), and their places in the
|
||||
// order [`for_each_leaf`] visits the paths.
|
||||
// order [`for_each_leaf`] visits the paths; and the ids of the paths whose linked masks
|
||||
// moved with them as they were transformed as objects.
|
||||
let mut kept_ids = HashSet::new();
|
||||
let mut kept_leaves = HashSet::new();
|
||||
let mut leaf_at = 0usize;
|
||||
let mut moved_ids = HashSet::new();
|
||||
let transform = (e.id == "distort.transform").then(|| {
|
||||
let (m, copies) = crate::distort::transform_map(bounds, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
(m, copies, options, crate::distort::transform_affine(bounds, ¶ms, seed))
|
||||
let (m, copies) = crate::distort::transform_map(bounds, params, seed);
|
||||
let options = crate::distort::TransformOptions::of(params);
|
||||
(m, copies, options, crate::distort::transform_affine(bounds, params, seed))
|
||||
});
|
||||
// In a mask's art, images and symbol instances take only a Transform effect
|
||||
// ([`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 };
|
||||
}
|
||||
// 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.
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& copies > 0
|
||||
&& copy_whole
|
||||
{
|
||||
used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
continue;
|
||||
if !own {
|
||||
*used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
return Ran { kept: false, 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
|
||||
// [`copy_art`] counts only the members.
|
||||
let before = copy_cost(art);
|
||||
let rest = used.minus(before).plus(art.extras().mask.as_deref().map_or(Budget { anchors: 0, lines: 0 }, |k| copy_cost(&k.art)));
|
||||
let made = copy_art(art, m, copies, copy_scaling(options), max.minus(rest));
|
||||
*used = rest.plus(made);
|
||||
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 };
|
||||
}
|
||||
// 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.
|
||||
let watch = transform.is_some_and(|(_, copies, options, _)| copies > 0 && options.objects) && (own || has_linked_mask(art, false));
|
||||
let mut covered = HashSet::new();
|
||||
if watch && !own {
|
||||
masked_ids(art, false, &mut covered);
|
||||
}
|
||||
let counts = |id: NodeId| watch && (own || covered.contains(&id));
|
||||
let mut short = false;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
let at = leaf_at;
|
||||
leaf_at += 1;
|
||||
@@ -790,15 +934,26 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
// strokes; a gradient paints each copy by itself, not the one piece the copies
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
// Each copy of a path with a linked mask carries the mask, moved with it.
|
||||
let separate = copies > 0
|
||||
&& (apart
|
||||
&& (self.apart
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule));
|
||||
|| paints_copies_apart(&leaf.appearance, rule)
|
||||
|| leaf.extras().mask.as_ref().is_some_and(|m| m.linked));
|
||||
// The copies of a path replace it by a group of them, the path included.
|
||||
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
used = used.minus(before).plus(made);
|
||||
if !moved {
|
||||
*used = used.minus(before).plus(made);
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
if options.objects {
|
||||
moved_ids.insert(leaf.id);
|
||||
}
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
} else {
|
||||
kept_ids.insert(leaf.id);
|
||||
}
|
||||
return;
|
||||
@@ -806,20 +961,28 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
if separate {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room);
|
||||
used = used.minus(before).plus(made);
|
||||
*used = used.minus(before).plus(made);
|
||||
moved_ids.insert(leaf.id);
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
return;
|
||||
}
|
||||
}
|
||||
let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
|
||||
let stage = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
|
||||
let Some(out) = apply_one(&e.id, params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
|
||||
kept_ids.insert(leaf.id);
|
||||
kept_leaves.insert(at);
|
||||
return;
|
||||
};
|
||||
used = used.minus(before).plus(Budget::of(&out));
|
||||
// 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
|
||||
{
|
||||
short |= out.anchor_count() < path.anchor_count().saturating_mul(copies.saturating_add(1));
|
||||
}
|
||||
*used = used.minus(before).plus(Budget::of(&out));
|
||||
if follows && !boxes {
|
||||
// A gradient fitted to the path fits the path's own bounds.
|
||||
let carry = crate::Carry::of(&e.id, ¶ms, bounds, path.bounds(), None, seed);
|
||||
let carry = crate::Carry::of(&e.id, params, bounds, path.bounds(), None, seed);
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
@@ -832,36 +995,230 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
// Warp bends images too: each one's pixels follow the warp's map over the same box. The
|
||||
// images are cut into pieces once, after the last effect ([`cut_warped_images`]). An image
|
||||
// whose clipping frame kept its shape (past the budget) keeps its pixels as they are.
|
||||
if let Some(style) = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id)
|
||||
&& crate::warp::bends(&e.id, ¶ms)
|
||||
if let Some(style) = warp
|
||||
&& let Some(warped) = warped.as_deref_mut()
|
||||
{
|
||||
let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, ¶ms));
|
||||
let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, params));
|
||||
warped.reserve(art);
|
||||
mark_warped_images(art, &f, &kept_leaves, false, &mut 0, &mut warped);
|
||||
mark_warped_images(art, &f, &kept_leaves, false, &mut 0, warped);
|
||||
}
|
||||
if let Some((m, copies, options, _)) = transform
|
||||
&& options.objects
|
||||
{
|
||||
transform_placed(art, m, copies);
|
||||
// A mask's art that is one image or symbol instance is placed as the only member of a
|
||||
// group of it.
|
||||
let root = is_placed(art);
|
||||
if root {
|
||||
let id = art.id;
|
||||
let one = std::mem::replace(art, Node::group(id, vec![]));
|
||||
*art = Node::group(id, vec![Arc::new(one)]);
|
||||
}
|
||||
let placed = if watch { masked_placed(art, own) } else { 0 };
|
||||
transform_placed(art, m, copies, copy_scaling(options));
|
||||
short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1));
|
||||
if root && let Some([one]) = art.children().map(Vec::as_slice) {
|
||||
*art = (**one).clone();
|
||||
}
|
||||
}
|
||||
if outlines.iter().any(Option::is_some) {
|
||||
rebase_type_outlines(art, &mut outlines.into_iter());
|
||||
}
|
||||
// Under Transform copies, a mask takes the copies as the paths it masks do; the copies of a
|
||||
// path with a mask of its own each carry it ([`copy_leaf`]).
|
||||
let masks = self.reshape_masks(art, own, &Skip { moved: &moved_ids, kept: &kept_ids }, max, used, depth);
|
||||
// What paints the art as a whole, and the own fills and strokes of the groups inside it,
|
||||
// follow their bounds under Free Distort and Warp (they stay when no path changed them).
|
||||
// Each stays when a path under it that its bounds measure kept its shape (past the budget).
|
||||
let mut after = vec![];
|
||||
let images = if groups.is_empty() { None } else { warped.when_cut(art) };
|
||||
let images = if groups.is_empty() { None } else { warped.as_deref().and_then(|w| w.when_cut(art)) };
|
||||
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, images, &mut after).1;
|
||||
if !groups.is_empty() {
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, ¶ms, bounds, from, to, seed));
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
|
||||
}
|
||||
if follows && !held {
|
||||
whole.push(crate::Carry::of(&e.id, ¶ms, bounds, Some(bounds), warped.bounds(art), seed));
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path,
|
||||
/// compound path, group and layer under it, with the art's reference box, as the paths the mask
|
||||
/// covers take it: the mask moves and bends with what it masks. The mask of an object
|
||||
/// transformed as an object moved with it already and is left as it is. A mask stays as it was
|
||||
/// past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks, and for the reasons
|
||||
/// [`Step::reshape_own_mask`] gives. Returns whether a mask stayed for one of those reasons.
|
||||
fn reshape_masks(&self, n: &mut Node, own: bool, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
|
||||
return false;
|
||||
}
|
||||
let mut stayed = own && self.reshape_own_mask(n, skip, max, used, depth);
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
|
||||
for c in children.iter_mut() {
|
||||
if has_linked_mask(c, true) {
|
||||
stayed |= self.reshape_masks(Arc::make_mut(c), true, skip, max, used, depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
stayed
|
||||
}
|
||||
|
||||
/// Run the effect over the art of the linked opacity mask of `n` itself, when `n` is a path,
|
||||
/// compound path, group or layer that `skip` does not list as moved. The mask stays as it was
|
||||
/// when a path it masks kept its shape, and when its own art could not take the effect whole: a
|
||||
/// path in it would keep its shape, its copies would stop short, or a mask inside it would stay
|
||||
/// (no mask is left half moved). Returns whether the mask stayed for one of those reasons.
|
||||
fn reshape_own_mask(&self, n: &mut Node, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !reshapes_mask_of(n) || skip.moved.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
let stays = holds_any(n, skip.kept);
|
||||
let id = n.id;
|
||||
let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return false };
|
||||
let before = *used;
|
||||
let mut art = (*m.art).clone();
|
||||
let whole = self.wholes.get(&id).copied().unwrap_or_else(|| copies_whole(&art));
|
||||
let ran = (!stays).then(|| self.run(&mut art, max, used, whole, None, true, depth + 1));
|
||||
match ran {
|
||||
Some(ran) if ran.complete() => {
|
||||
// What paints the mask's art as a whole follows the effect as the art does.
|
||||
if let Some(carry) = ran.whole
|
||||
&& carry.moves(&art.appearance)
|
||||
{
|
||||
carry.apply(&mut art.appearance);
|
||||
}
|
||||
m.art = Arc::new(art);
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
*used = before;
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
cut_warped_images(art, &warped);
|
||||
whole
|
||||
}
|
||||
|
||||
/// The objects whose linked masks [`Step::reshape_masks`] leaves as they are: those transformed
|
||||
/// as objects (`moved`), and those holding a path that kept its shape (`kept`).
|
||||
struct Skip<'a> {
|
||||
moved: &'a HashSet<NodeId>,
|
||||
kept: &'a HashSet<NodeId>,
|
||||
}
|
||||
|
||||
/// Is `n` an object whose linked opacity mask a geometry effect on the art it is in reshapes with
|
||||
/// it: a path, compound path, group or layer? An image or symbol instance moves its mask only
|
||||
/// with the map a Transform effect places it by ([`transform_placed`]).
|
||||
fn reshapes_mask_of(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// Does `n` (with `own`) or a path, compound path, group or layer under it carry a linked opacity
|
||||
/// mask that [`Step::reshape_masks`] reshapes?
|
||||
fn has_linked_mask(n: &Node, own: bool) -> bool {
|
||||
let mine = own && reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked);
|
||||
mine || match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_linked_mask(c, true)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` on the id of `n` (with `own`) and of each path, compound path, group and layer under it
|
||||
/// that carries a linked opacity mask, with the art of that mask, and on the masks inside that
|
||||
/// art, as [`Step::reshape_masks`] reaches them: `depth` masks deep already, up to
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`].
|
||||
fn each_linked_mask(n: &Node, own: bool, depth: usize, f: &mut dyn FnMut(NodeId, &Node)) {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
if own
|
||||
&& reshapes_mask_of(n)
|
||||
&& let Some(m) = n.extras().mask.as_deref().filter(|m| m.linked)
|
||||
{
|
||||
f(n.id, &m.art);
|
||||
each_linked_mask(&m.art, true, depth + 1, f);
|
||||
}
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &n.kind {
|
||||
for c in children {
|
||||
each_linked_mask(c, true, depth, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`each_linked_mask`] that changes the art of each mask: `f` runs on a mask's art before the
|
||||
/// masks inside it are reached.
|
||||
fn each_linked_mask_mut(n: &mut Node, own: bool, depth: usize, f: &mut dyn FnMut(&mut Node)) {
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
|
||||
return;
|
||||
}
|
||||
if own
|
||||
&& reshapes_mask_of(n)
|
||||
&& let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
|
||||
{
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
f(art);
|
||||
each_linked_mask_mut(art, true, depth + 1, f);
|
||||
}
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
|
||||
for c in children.iter_mut() {
|
||||
if has_linked_mask(c, true) {
|
||||
each_linked_mask_mut(Arc::make_mut(c), true, depth, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does [`Step::reshape_masks`] reshape the linked opacity mask of `n` itself?
|
||||
fn has_own_linked_mask(n: &Node) -> bool {
|
||||
reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
}
|
||||
|
||||
/// Add to `out` the ids of the objects under `n` that the linked opacity mask of an object above
|
||||
/// them covers (every one of them with `under`).
|
||||
fn masked_ids(n: &Node, under: bool, out: &mut HashSet<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if under {
|
||||
out.insert(c.id);
|
||||
}
|
||||
masked_ids(c, under || has_own_linked_mask(c), out);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many images and symbol instances under `n` the linked opacity mask of an object above them
|
||||
/// covers (every one of them with `under`).
|
||||
fn masked_placed(n: &Node, under: bool) -> usize {
|
||||
n.children().into_iter().flatten().map(|c| usize::from(under && is_placed(c)) + masked_placed(c, under || has_own_linked_mask(c))).sum()
|
||||
}
|
||||
|
||||
/// Is `n`, or anything under it, one of `ids`?
|
||||
fn holds_any(n: &Node, ids: &HashSet<NodeId>) -> bool {
|
||||
if ids.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| any |= ids.contains(&c.id));
|
||||
any
|
||||
}
|
||||
|
||||
/// Do the paths under `n` that [`for_each_leaf`] visits all fill by the non-zero rule without a
|
||||
/// stroke that paints? Effects then reshape their outlines alike in any order that the
|
||||
/// optimization of [`crate::geometry::optimize_geometry_effects`] takes.
|
||||
fn leaves_safe(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => {
|
||||
let has_stroke = n.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
|
||||
leaf_geometry(n).is_none_or(|(_, rule)| rule == FillRule::NonZero && !has_stroke)
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().all(|c| leaves_safe(c)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is there an image with a linked opacity mask among the members of `n`, or among its groups'
|
||||
/// and layers' members, which [`mark_warped_images`] walks?
|
||||
fn has_masked_image(n: &Node) -> bool {
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return false };
|
||||
children.iter().any(|c| match c.kind {
|
||||
NodeKind::Image(_) => c.extras().mask.as_ref().is_some_and(|m| m.linked),
|
||||
_ => has_masked_image(c),
|
||||
})
|
||||
}
|
||||
|
||||
/// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by
|
||||
@@ -1082,7 +1439,9 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
let mut copy = leaf.clone();
|
||||
copy.transform(xf, scaling);
|
||||
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
|
||||
let cost = Budget::of(&moved).plus(effects_cost(©, &moved));
|
||||
let mut cost = Budget::of(&moved).plus(effects_cost(©, &moved));
|
||||
// Each copy carries the art of its linked masks, moved with it.
|
||||
each_linked_mask(©, true, 0, &mut |_, m| cost = cost.plus(art_cost(m)));
|
||||
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
|
||||
break;
|
||||
}
|
||||
@@ -1622,17 +1981,20 @@ fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
|
||||
/// Apply the Transform effect's map `m` to every image and symbol instance under `n`, as
|
||||
/// [`for_each_leaf`] does to paths: the map goes into the object's placement, and `copies` more
|
||||
/// follow, each mapped once more than the last. Without copies the object itself takes the map,
|
||||
/// as a path does.
|
||||
fn transform_placed(n: &mut Node, m: Affine, copies: usize) {
|
||||
transform_placed_within(n, m, copies, crate::distort::MAX_COPY_OBJECTS)
|
||||
/// as a path does. The art of each one's linked opacity mask takes the map with `scaling`, as a
|
||||
/// path's mask does.
|
||||
fn transform_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling) {
|
||||
let mut room = crate::distort::MAX_COPY_OBJECTS.saturating_sub(placed_count(n));
|
||||
copy_placed(n, m, copies, scaling, &mut room);
|
||||
}
|
||||
|
||||
/// [`transform_placed`] whose copies make at most `max` image and symbol instance nodes of the art,
|
||||
/// the originals included: each copy adds the object once more, and a Transform after this one
|
||||
/// copies the lot again, so copies stop where the result would pass `max` (#2042).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn transform_placed_within(n: &mut Node, m: Affine, copies: usize, max: usize) {
|
||||
let mut room = max.saturating_sub(placed_count(n));
|
||||
copy_placed(n, m, copies, &mut room);
|
||||
copy_placed(n, m, copies, vectorcraft_doc::Scaling::default(), &mut room);
|
||||
}
|
||||
|
||||
/// Rows and columns of the pieces a Warp effect cuts an image into (VectorCraft's own number).
|
||||
@@ -1864,11 +2226,11 @@ fn is_placed(n: &Node) -> bool {
|
||||
/// document order, each copy taking one from `room` (what the art can still grow by), until the
|
||||
/// budget is full. As with a path, the copies stop before one reaches past
|
||||
/// [`crate::distort::within_reach`].
|
||||
fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, room: &mut usize) {
|
||||
let Some(children) = n.children_mut() else { return };
|
||||
for c in children.iter_mut() {
|
||||
if !is_placed(c) {
|
||||
copy_placed(Arc::make_mut(c), m, copies, room);
|
||||
copy_placed(Arc::make_mut(c), m, copies, scaling, room);
|
||||
continue;
|
||||
}
|
||||
let src = (**c).clone();
|
||||
@@ -1887,6 +2249,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
|
||||
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
|
||||
one.appearance.transform_gradients(xf);
|
||||
}
|
||||
// So does the art of its linked opacity mask.
|
||||
if xf != Affine::IDENTITY
|
||||
&& let Some(m) = one.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
|
||||
{
|
||||
Arc::make_mut(&mut m.art).transform(xf, scaling);
|
||||
}
|
||||
one
|
||||
};
|
||||
if copies == 0 {
|
||||
|
||||
@@ -29,7 +29,7 @@ const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
|
||||
/// The most face and box tests a group's transparent members' faces take together to rejoin their
|
||||
/// members' last runs; past them each starts a run of its own.
|
||||
const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
pub(crate) const MAX_OVERLAP_TESTS: usize = 1 << 22;
|
||||
|
||||
/// The width of the stroke around each face that covers the seams between faces.
|
||||
const SEAM_WIDTH: f64 = 0.75;
|
||||
@@ -628,14 +628,14 @@ pub(crate) fn scoped<'a>(id: NodeId, surfaces: Vec<(&'a [Scope], Arc<Node>)>, le
|
||||
/// What a face can paint, to tell whether two faces overlap: the convex hull of the points and
|
||||
/// control points of its outline, which holds the outline, and the hull's box grown by half the
|
||||
/// seam stroke.
|
||||
struct Coverage {
|
||||
bounds: Rect,
|
||||
pub(crate) struct Coverage {
|
||||
pub(crate) bounds: Rect,
|
||||
hull: Vec<Point>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// `None` for a face with no outline and no box.
|
||||
fn of(face: &Node) -> Option<Coverage> {
|
||||
pub(crate) fn of(face: &Node) -> Option<Coverage> {
|
||||
let points: Vec<Point> = match face.path_data() {
|
||||
Some(path) => path
|
||||
.to_bezpath()
|
||||
@@ -663,7 +663,7 @@ impl Coverage {
|
||||
/// Do the two faces' hulls, each grown by half the seam stroke, overlap? A test of the
|
||||
/// separating axes of their edges and of the page's axes: `true` whenever they overlap, and
|
||||
/// sometimes near a corner when they don't.
|
||||
fn meets(&self, other: &Coverage) -> bool {
|
||||
pub(crate) fn meets(&self, other: &Coverage) -> bool {
|
||||
fn normals(hull: &[Point]) -> impl Iterator<Item = Vec2> + '_ {
|
||||
(0..hull.len()).filter_map(|i| {
|
||||
let (a, b) = (hull.get(i)?, hull.get((i + 1) % hull.len())?);
|
||||
@@ -710,7 +710,7 @@ fn convex_hull(mut points: Vec<Point>) -> Vec<Point> {
|
||||
}
|
||||
|
||||
/// Do boxes `a` and `b` overlap with some area?
|
||||
fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
}
|
||||
|
||||
|
||||
@@ -700,10 +700,11 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
|
||||
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
|
||||
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance, and with
|
||||
/// caps, a shape's fill walls before the faces of its covering strokes that overlap them:
|
||||
/// [`draw_order`]);
|
||||
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
|
||||
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
|
||||
/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the
|
||||
/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask
|
||||
/// ([`in_runs`]);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
|
||||
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
|
||||
@@ -856,19 +857,21 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
|
||||
}
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets, or carry an
|
||||
// opacity mask, and then it stays whole.
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| {
|
||||
s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())
|
||||
});
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
|
||||
// included, draws whole in member order.
|
||||
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
if !opaque || !plain {
|
||||
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
|
||||
}
|
||||
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
|
||||
// ([`in_runs`]), and each run carries the mask.
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
|
||||
let (mut placed, mut faces) = (vec![], vec![]);
|
||||
for (depths, s, _) in surfaces {
|
||||
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
placed.extend(depths);
|
||||
faces.extend(children.into_iter().map(Some));
|
||||
faces.extend(children.into_iter().map(|face| Some((surface, face))));
|
||||
}
|
||||
}
|
||||
let sealed = match fx.id.as_str() {
|
||||
@@ -877,7 +880,69 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
let order = draw_order(&placed, sealed);
|
||||
Some(vec![Arc::new(Node::group(n.id, order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect()))])
|
||||
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
|
||||
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
|
||||
Some(vec![Arc::new(Node::group(n.id, children))])
|
||||
}
|
||||
|
||||
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
|
||||
/// carry an opacity mask (`masks`, by surface). A face of a surface without one goes in the order
|
||||
/// on its own. The faces of a masked surface share a run, one group with the surface's mask. Such a
|
||||
/// face joins its surface's last run unless a face drawn after that run overlaps it: only then does
|
||||
/// the surface split, where one group can't be both behind and in front of another face.
|
||||
fn in_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, masks: &[Option<Box<OpacityMask>>]) -> Vec<Arc<Node>> {
|
||||
use crate::revolve::{Coverage, overlaps};
|
||||
struct Run {
|
||||
surface: Option<usize>,
|
||||
bounds: Rect,
|
||||
faces: Vec<Arc<Node>>,
|
||||
cover: Vec<Coverage>,
|
||||
}
|
||||
let mut runs: Vec<Run> = vec![];
|
||||
let mut last_run = vec![None; masks.len()];
|
||||
// Past this many tests a face starts a run of its own, which never draws out of order.
|
||||
let mut budget = crate::revolve::MAX_OVERLAP_TESTS;
|
||||
for (surface, face) in faces {
|
||||
let Some(cover) = Coverage::of(&face) else {
|
||||
// A face with no outline and no box overlaps nothing.
|
||||
runs.push(Run { surface: None, bounds: Rect::ZERO, faces: vec![face], cover: vec![] });
|
||||
continue;
|
||||
};
|
||||
if masks.get(surface).is_none_or(Option::is_none) {
|
||||
runs.push(Run { surface: None, bounds: cover.bounds, faces: vec![face], cover: vec![cover] });
|
||||
continue;
|
||||
}
|
||||
let mut clear = |r: &Run| {
|
||||
budget = budget.saturating_sub(1);
|
||||
if !overlaps(r.bounds, cover.bounds) {
|
||||
return budget > 0;
|
||||
}
|
||||
budget = budget.saturating_sub(r.cover.len());
|
||||
budget > 0 && r.cover.iter().all(|c| !overlaps(c.bounds, cover.bounds) || !c.meets(&cover))
|
||||
};
|
||||
let joins = last_run.get(surface).copied().flatten().filter(|&i: &usize| runs.get(i + 1..).is_some_and(|later| later.iter().all(&mut clear)));
|
||||
match joins.and_then(|i| runs.get_mut(i)) {
|
||||
Some(run) => {
|
||||
run.bounds = run.bounds.union(cover.bounds);
|
||||
run.faces.push(face);
|
||||
run.cover.push(cover);
|
||||
}
|
||||
None => {
|
||||
if let Some(last) = last_run.get_mut(surface) {
|
||||
*last = Some(runs.len());
|
||||
}
|
||||
runs.push(Run { surface: Some(surface), bounds: cover.bounds, faces: vec![face], cover: vec![cover] });
|
||||
}
|
||||
}
|
||||
}
|
||||
runs.into_iter()
|
||||
.filter_map(|mut r| {
|
||||
let Some(mask) = r.surface.and_then(|s| masks.get(s)).cloned().flatten() else { return r.faces.pop() };
|
||||
let mut group = Node::group(id, r.faces);
|
||||
group.extras_mut().mask = Some(mask);
|
||||
Some(Arc::new(group))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
|
||||
@@ -415,15 +415,16 @@ fn a_translucent_stroke_is_a_surface_of_its_own() {
|
||||
}
|
||||
|
||||
/// With a light that is not white, a fill in a gradient with transparent stops is drawn with an
|
||||
/// opacity mask over its whole surface: the fill's solid and the stroke's stay surfaces of their
|
||||
/// own, and the mask stays on the fill's. Under a white light the same object is one surface.
|
||||
/// opacity mask: its faces still take their places in the one order of the fill's and the
|
||||
/// stroke's faces, in runs that each carry the mask. Under a white light the faces carry the
|
||||
/// gradient itself and no mask.
|
||||
#[test]
|
||||
fn a_masked_surface_under_a_colored_light_stays_whole() {
|
||||
fn a_masked_surface_under_a_colored_light_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let mut half = GradientStop::new(1.0, RED);
|
||||
half.opacity = 0.5;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), half]));
|
||||
for (lights, surfaces) in [(json!({"lights": [{"color": "#ff8080"}]}), 2), (json!({}), 1)] {
|
||||
for (lights, masked) in [(json!({"lights": [{"color": "#ff8080"}]}), true), (json!({}), false)] {
|
||||
let mut n = stroked_rect(100.0);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.paint = Paint::Gradient(Box::new(gradient.clone()));
|
||||
@@ -431,8 +432,10 @@ fn a_masked_surface_under_a_colored_light_stays_whole() {
|
||||
n.appearance.effects.push(fx(EXTRUDE, lights.clone()));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let drawn = art.children().unwrap();
|
||||
assert_eq!(drawn.len(), surfaces, "{lights}");
|
||||
assert_eq!(drawn[0].extras().mask.is_some(), surfaces == 2, "{lights}");
|
||||
assert_eq!(drawn.len(), 1, "{lights}: one order of faces");
|
||||
let runs: Vec<&Arc<Node>> = drawn[0].children().unwrap().iter().filter(|c| c.extras().mask.is_some()).collect();
|
||||
assert_eq!(!runs.is_empty(), masked, "{lights}");
|
||||
assert!(runs.iter().all(|r| r.children().unwrap().iter().all(|f| !blue(f))), "{lights}: the mask stays on the fill's faces");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -847,7 +850,9 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surface = &art.children().unwrap()[0];
|
||||
assert_eq!(surface.extras().mask.is_some(), masked, "{end}");
|
||||
let mut has_mask = false;
|
||||
surface.walk(&mut |c| has_mask |= c.extras().mask.is_some());
|
||||
assert_eq!(has_mask, masked, "{end}");
|
||||
let mut opaque = true;
|
||||
surface.walk(&mut |c| {
|
||||
for item in &c.appearance.items {
|
||||
@@ -862,6 +867,67 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
|
||||
/// faces are drawn between them where they are in front of some and behind others. Here a square
|
||||
/// frame in the gradient holds a square in its hole: the frame's inner walls are behind the square
|
||||
/// and its front cap is in front of the square's walls.
|
||||
#[test]
|
||||
fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let square = |b: &mut BezPath, x0: f64, x1: f64, clockwise: bool| {
|
||||
let corners = [(x0, x0), (x1, x0), (x1, x1), (x0, x1)];
|
||||
let mut points = corners.to_vec();
|
||||
if !clockwise {
|
||||
points.reverse();
|
||||
}
|
||||
b.move_to(points[0]);
|
||||
for p in &points[1..] {
|
||||
b.line_to(*p);
|
||||
}
|
||||
b.close_path();
|
||||
};
|
||||
let art = |id: &str, params: &Value, end_opacity: f32| {
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = end_opacity;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), end]))));
|
||||
let mut b = BezPath::new();
|
||||
square(&mut b, 100.0, 300.0, true);
|
||||
square(&mut b, 150.0, 250.0, false);
|
||||
let frame = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(gradient, Paint::None, 0.0));
|
||||
let mut b = BezPath::new();
|
||||
square(&mut b, 185.0, 215.0, true);
|
||||
let inner = Node::path(NodeId(2), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0));
|
||||
let mut g = Node::group(NodeId(3), vec![Arc::new(frame), Arc::new(inner)]);
|
||||
g.appearance.effects.push(fx(id, params.clone()));
|
||||
solid_art(&g).unwrap_or_else(|| panic!("{id}"))
|
||||
};
|
||||
// The drawing order: `M` for a group with an opacity mask, `F` for a face outside one.
|
||||
fn visit(n: &Node, order: &mut String) {
|
||||
if n.extras().mask.is_some() {
|
||||
order.push('M');
|
||||
return;
|
||||
}
|
||||
if n.path_data().is_some() {
|
||||
order.push('F');
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, order);
|
||||
}
|
||||
}
|
||||
let order = |art: &Node| {
|
||||
let mut order = String::new();
|
||||
visit(art, &mut order);
|
||||
order
|
||||
};
|
||||
for (id, params) in [(CLASSIC_EXTRUDE, json!({})), (EXTRUDE, json!({"lights": [{"color": "#ff8080"}]}))] {
|
||||
assert!(!order(&art(id, ¶ms, 1.0)).contains('M'), "{id}: an opaque gradient needs no mask");
|
||||
let masked = order(&art(id, ¶ms, 0.5));
|
||||
let (first, last) = (masked.find('M').unwrap(), masked.rfind('M').unwrap());
|
||||
assert!(masked.get(first..last).is_some_and(|between| between.contains('F')), "{id}: faces between the member's runs: {masked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_parameters_are_checked() {
|
||||
let n = classic(json!({}));
|
||||
|
||||
@@ -367,9 +367,12 @@ pub struct Slice {
|
||||
}
|
||||
|
||||
impl Slice {
|
||||
/// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`.
|
||||
pub fn paint(&self, g: &Gradient) -> Paint {
|
||||
let gradient = g.span(self.span.0 as f32, self.span.1 as f32);
|
||||
/// The slice's paint: its piece of `unrolled` as a linear gradient placed from `from` to `to`.
|
||||
/// `unrolled` is the stroke's gradient as [`Gradient::unrolled`] gives it (unrolled once for
|
||||
/// all the slices), so one that repeats or reflects runs its stops that many times along (or
|
||||
/// across) the stroke.
|
||||
pub fn paint(&self, unrolled: &Gradient) -> Paint {
|
||||
let gradient = unrolled.span(self.span.0 as f32, self.span.1 as f32);
|
||||
let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) };
|
||||
let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None };
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) }))
|
||||
@@ -471,35 +474,60 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines:
|
||||
_ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(),
|
||||
};
|
||||
let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 };
|
||||
let unrolled = g.unrolled();
|
||||
let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
let paint = s.paint(g);
|
||||
let paint = s.paint(&unrolled);
|
||||
(s.shape, paint)
|
||||
})
|
||||
.collect();
|
||||
Some(WrittenSlices { clip, slices })
|
||||
}
|
||||
|
||||
/// How far before and after a sharp step between two colors (two stops at one offset, as a
|
||||
/// gradient that repeats has where one run meets the next) [`mesh_marks`] puts a mesh row or
|
||||
/// column, as a fraction of the gradient's length.
|
||||
const STEP_GAP: f64 = 1e-4;
|
||||
|
||||
/// Where along gradient `g` (0 to 1) Outline Stroke's mesh puts a row or column for its stops
|
||||
/// ([`Gradient::expanded_stops`]): at each stop, and for two stops at one offset (a sharp step,
|
||||
/// or where a reflecting gradient turns back) also [`STEP_GAP`] before and after it, so the mesh
|
||||
/// takes the color on each side.
|
||||
fn mesh_marks(g: &Gradient) -> Vec<f64> {
|
||||
let offsets: Vec<f64> = g.expanded_stops().iter().map(|s| f64::from(s.0)).collect();
|
||||
let shared = |i: usize| {
|
||||
let t = offsets.get(i).copied().unwrap_or(0.0);
|
||||
let near = |j: Option<usize>| j.and_then(|j| offsets.get(j)).is_some_and(|&u| (u - t).abs() < 1e-6);
|
||||
near(i.checked_sub(1)) || near(i.checked_add(1))
|
||||
};
|
||||
let mut out = Vec::with_capacity(offsets.len() + 2);
|
||||
for (i, &t) in offsets.iter().enumerate() {
|
||||
out.push(t);
|
||||
if shared(i) {
|
||||
out.extend([(t - STEP_GAP).max(0.0), (t + STEP_GAP).min(1.0)]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
|
||||
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
|
||||
/// stroke's outline), coloured as [`gradient_slices`] paint it.
|
||||
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
|
||||
let g = &*g.unrolled();
|
||||
let across = st.gradient_mode == StrokeGradientMode::Across;
|
||||
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
|
||||
let at_stops = mesh_marks(g);
|
||||
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
|
||||
let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() };
|
||||
let marks: Vec<f64> = if across { vec![] } else { at_stops.clone() };
|
||||
let max_dt = match (across, st.profile.is_some()) {
|
||||
(false, _) => MESH_STEP,
|
||||
(true, true) => PROFILE_STEP,
|
||||
(true, false) => 1.0,
|
||||
};
|
||||
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
|
||||
let mut us: Vec<f64> = if across {
|
||||
(0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect()
|
||||
} else {
|
||||
vec![0.5]
|
||||
};
|
||||
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(at_stops).collect() } else { vec![0.5] };
|
||||
us.sort_by(f64::total_cmp);
|
||||
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
|
||||
|
||||
@@ -286,6 +286,65 @@ fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
|
||||
assert_covered(&hairpin, &st);
|
||||
}
|
||||
|
||||
/// A gradient along or across a stroke that repeats or reflects runs its stops that many times
|
||||
/// along (or across) it: a slice's paint, and Outline Stroke's meshes, give each point the color
|
||||
/// the spread gives its place.
|
||||
#[test]
|
||||
fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
for (mode, spread) in [StrokeGradientMode::Along, StrokeGradientMode::Across]
|
||||
.into_iter()
|
||||
.flat_map(|m| [GradientSpread::Reflect, GradientSpread::Repeat].map(|s| (m, s)))
|
||||
{
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
for s in slices(&bp, &st) {
|
||||
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
|
||||
let geom = p.geom.unwrap();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
let at = s.from + (s.to - s.from) * u;
|
||||
let t = s.span.0 + (s.span.1 - s.span.0) * u;
|
||||
// Where two runs meet, Repeat's color is the next run's start or the last one's end.
|
||||
if (t * 3.0 - (t * 3.0).round()).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(geom.param_at(vectorcraft_color::GradientKind::Linear, at) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-3), "{mode:?} at {t}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
// Outline Stroke: the mesh comes back to white where each run starts again, and reaches
|
||||
// black where each run ends, on both sides of a sharp step between runs.
|
||||
let count = |g: &Gradient, hex: &str| {
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == hex).count()
|
||||
};
|
||||
for hex in ["#ffffff", "#000000"] {
|
||||
let (spread, pad) = (count(&g, hex), count(&Gradient::default(), hex));
|
||||
assert!(spread > pad, "{mode:?} {:?} {hex}: {spread} vs {pad}", g.spread);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a reflecting gradient turns back past a narrow last stop, Outline Stroke's mesh keeps that
|
||||
/// stop's color.
|
||||
#[test]
|
||||
fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.995, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let mut st = stroke(10.0, mode);
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops.clone()) };
|
||||
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
|
||||
let whites =
|
||||
gradient_meshes(&bp, FillRule::NonZero, &st, &g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == "#ffffff").count();
|
||||
// The gradient turns back at white 50 times.
|
||||
assert!(whites >= 50, "{mode:?}: {whites}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
|
||||
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
|
||||
/// 256 do.
|
||||
|
||||
@@ -771,6 +771,7 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, key_location, location_in, location_keys};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -176,6 +176,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -474,6 +475,170 @@ fn energy_beams() -> BrushLibrary {
|
||||
built("Energy Beams", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// The fixed-seed number source of the Dry Media grain: integer steps and plain arithmetic, so the
|
||||
/// art is the same on every run and every platform.
|
||||
struct Grain(u64);
|
||||
|
||||
impl Grain {
|
||||
/// The next number in 0..1.
|
||||
fn next(&mut self) -> f64 {
|
||||
self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
|
||||
(self.0 >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
/// The next number in `a`..`b`.
|
||||
fn range(&mut self, a: f64, b: f64) -> f64 {
|
||||
a + (b - a) * self.next()
|
||||
}
|
||||
}
|
||||
|
||||
/// `floor` at x = `x0` and `x1`, rising smoothly to 1 within `ramp` pt of each.
|
||||
fn ends(x: f64, x0: f64, x1: f64, ramp: f64, floor: f64) -> f64 {
|
||||
let t = ((x - x0).min(x1 - x) / ramp).clamp(0.0, 1.0);
|
||||
floor + (1.0 - floor) * t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// A closed band from x = `x0` to `x1` in `n` steps, at most `half` pt either side of y = 0 times
|
||||
/// `taper(x)`; each edge point is pulled in by up to `rough` of that.
|
||||
fn rough_band(g: &mut Grain, (x0, x1): (f64, f64), n: usize, half: f64, rough: f64, taper: impl Fn(f64) -> f64) -> PathData {
|
||||
let xs: Vec<f64> = (0..=n).map(|i| x0 + (x1 - x0) * i as f64 / n as f64).collect();
|
||||
let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, -half * taper(x) * (1.0 - rough * g.next()))).collect();
|
||||
let bottom: Vec<Point> = xs.iter().rev().map(|&x| Point::new(x, half * taper(x) * (1.0 - rough * g.next()))).collect();
|
||||
pts.extend(bottom);
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// A small four-cornered fleck around (`cx`, `cy`), at most `w` × `h` pt either side; one corner
|
||||
/// in each direction, so its outline never crosses itself.
|
||||
fn fleck(g: &mut Grain, cx: f64, cy: f64, w: f64, h: f64) -> PathData {
|
||||
let mut side = |a: f64, b: f64| g.range(a, b);
|
||||
let pts = [
|
||||
(cx - w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)),
|
||||
(cx + w * side(-0.3, 0.3), cy - h * side(0.6, 1.0)),
|
||||
(cx + w * side(0.6, 1.0), cy + h * side(-0.3, 0.3)),
|
||||
(cx + w * side(-0.3, 0.3), cy + h * side(0.6, 1.0)),
|
||||
];
|
||||
polygon(&pts)
|
||||
}
|
||||
|
||||
/// `body` with `holes` (inside it, apart from each other) cut out, even-odd, in gray `k`: what
|
||||
/// lies under the stroke shows through the holes.
|
||||
fn holed(body: PathData, holes: Vec<PathData>, k: f32) -> Node {
|
||||
let children = std::iter::once(body).chain(holes).map(|p| Arc::new(Node::path(NodeId(0), p, Appearance::default()))).collect();
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Compound { children, rule: FillRule::EvenOdd });
|
||||
n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::gray(k))))], ..Default::default() }.into();
|
||||
n
|
||||
}
|
||||
|
||||
/// Path `p` filled with gray `k` (1 is black).
|
||||
fn ink(p: PathData, k: f32) -> Node {
|
||||
filled(p, Paint::solid(Color::gray(k)))
|
||||
}
|
||||
|
||||
/// Slivers `w` × `h` pt (ranges) in `count` slots along x = 6..94 inside a band `half` pt wide
|
||||
/// times `taper`. Each stays within `reach` of the band's half width from y = 0, taken where the
|
||||
/// band is narrowest over the sliver and the 3 pt either side of it, so with `reach` below the
|
||||
/// band's roughness margin no sliver touches the band's edge or another sliver.
|
||||
fn slivers(g: &mut Grain, count: usize, half: f64, reach: f64, (w, h): ((f64, f64), (f64, f64)), taper: impl Fn(f64) -> f64) -> Vec<PathData> {
|
||||
let slot = 88.0 / count as f64;
|
||||
(0..count)
|
||||
.map(|i| {
|
||||
let cx = 6.0 + slot * (i as f64 + 0.5);
|
||||
let (w, h) = (g.range(w.0, w.1), g.range(h.0, h.1));
|
||||
let room = reach * half * taper(cx - w - 3.0).min(taper(cx + w + 3.0));
|
||||
let cy = g.range(-1.0, 1.0) * (room - h).max(0.0);
|
||||
fleck(g, cx, cy, w, h)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Dry Media: art brushes of grainy dry drawing marks, chalk, pencil, crayon and charcoal (original
|
||||
/// vector grain from fixed seeds; every brush 100 pt long, black and grays that take the stroke
|
||||
/// color as tints, gaps cut out so the paper shows).
|
||||
pub(crate) fn dry_media() -> BrushLibrary {
|
||||
// Chalk Grain, 100 × 8 pt: a soft band with narrow scratches and chips along its edges.
|
||||
let chalk = {
|
||||
let mut g = Grain(0x0c4a_1c0a);
|
||||
let taper = |x: f64| ends(x, 0.0, 100.0, 10.0, 0.35);
|
||||
let body = rough_band(&mut g, (0.0, 100.0), 36, 4.0, 0.25, taper);
|
||||
let scratches = slivers(&mut g, 14, 4.0, 0.7, ((1.2, 2.4), (0.15, 0.3)), taper);
|
||||
let mut parts = vec![holed(body, scratches, 0.8)];
|
||||
for i in 0..18 {
|
||||
let cx = 3.0 + 94.0 * (i as f64 + g.range(0.2, 0.8)) / 18.0;
|
||||
let side = if i % 2 == 0 { -1.0 } else { 1.0 };
|
||||
let cy = side * 4.0 * taper(cx) * g.range(0.7, 0.95);
|
||||
let (w, h) = (g.range(0.3, 0.7), g.range(0.25, 0.5));
|
||||
let f = fleck(&mut g, cx, cy, w, h);
|
||||
parts.push(ink(f, 1.0));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Graphite Pencil, 100 × 2.5 pt: a solid tapered core with fine slanted hatching at its edges.
|
||||
let pencil = {
|
||||
let mut g = Grain(0x009e_4c11);
|
||||
let core = rough_band(&mut g, (0.0, 100.0), 40, 0.8, 0.12, |x| ends(x, 0.0, 100.0, 18.0, 0.25));
|
||||
let mut parts = vec![ink(core, 1.0)];
|
||||
for i in 0..24 {
|
||||
let x0 = 2.0 + 92.0 * (i as f64 + g.range(0.0, 0.4)) / 24.0;
|
||||
let len = g.range(1.5, 3.0);
|
||||
let t = g.range(0.12, 0.2);
|
||||
let slant = g.range(0.1, 0.3);
|
||||
let y0 = if i % 2 == 0 { -g.range(0.85, 1.05) } else { g.range(0.85, 1.25) - t - slant };
|
||||
parts.push(ink(polygon(&[(x0, y0 + slant), (x0 + len, y0), (x0 + len, y0 + t), (x0, y0 + slant + t)]), 0.6));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Wax Crayon, 100 × 6 pt: a dense band with small gaps in its middle and short overlapping
|
||||
// marks along both edges.
|
||||
let crayon = {
|
||||
let mut g = Grain(0x00c0_a7e5);
|
||||
let taper = |x: f64| ends(x, 0.0, 100.0, 6.0, 0.5);
|
||||
let body = rough_band(&mut g, (0.0, 100.0), 30, 2.6, 0.2, taper);
|
||||
let gaps = slivers(&mut g, 16, 2.6, 0.34, ((0.6, 1.6), (0.15, 0.3)), taper);
|
||||
let mut parts = vec![holed(body, gaps, 0.9)];
|
||||
for i in 0..36 {
|
||||
let w = g.range(1.0, 2.2);
|
||||
let cx = (1.0 + w).max(98.0 * (i as f64 + g.range(0.0, 1.0)) / 36.0).min(99.0 - w);
|
||||
let side = if i % 2 == 0 { -1.0 } else { 1.0 };
|
||||
let h = g.range(0.4, 0.6);
|
||||
// Clear of the gaps, which stay within 0.9 pt of the middle.
|
||||
let inner = 0.9 + h;
|
||||
let cy = side * g.range(inner, (2.4 * taper(cx)).max(inner));
|
||||
let f = fleck(&mut g, cx, cy, w, h);
|
||||
parts.push(ink(f, 1.0));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
// Charcoal Dust, 100 × 7 pt: a dark band broken into pieces, with flecks of dust either side.
|
||||
let dust = {
|
||||
let mut g = Grain(0xc4a2_c0a1);
|
||||
let mut parts = vec![];
|
||||
let mut x0 = 0.0;
|
||||
while x0 < 100.0 {
|
||||
let x1 = (x0 + g.range(14.0, 24.0)).min(100.0);
|
||||
let x1 = if 100.0 - x1 < 8.0 { 100.0 } else { x1 };
|
||||
let piece = rough_band(&mut g, (x0, x1), 10, 2.0, 0.3, |x| ends(x, 0.0, 100.0, 8.0, 0.4) * ends(x, x0, x1, 2.0, 0.3));
|
||||
parts.push(ink(piece, 1.0));
|
||||
x0 = x1 + g.range(1.5, 3.0);
|
||||
}
|
||||
for i in 0..30 {
|
||||
let cx = 2.0 + 96.0 * (i as f64 + g.range(0.2, 0.8)) / 30.0;
|
||||
let side = if g.next() < 0.5 { -1.0 } else { 1.0 };
|
||||
let s = g.range(0.15, 0.3);
|
||||
let cy = side * g.range(2.3, 3.5 - s);
|
||||
let f = fleck(&mut g, cx, cy, s, s);
|
||||
parts.push(ink(f, if i % 3 == 0 { 0.7 } else { 1.0 }));
|
||||
}
|
||||
group(parts)
|
||||
};
|
||||
let brushes = vec![
|
||||
art("Chalk Grain", chalk, Colorization::Tints),
|
||||
art("Graphite Pencil", pencil, Colorization::Tints),
|
||||
art("Wax Crayon", crayon, Colorization::Tints),
|
||||
art("Charcoal Dust", dust, Colorization::Tints),
|
||||
];
|
||||
built("Dry Media", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
|
||||
@@ -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, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), 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), 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, 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, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), 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, 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",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -40,7 +40,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
("objects", "Objects"),
|
||||
("graphicStyles", "Graphic Styles"),
|
||||
("brushes", "Brushes"),
|
||||
("spotColors", "Spot Colors"),
|
||||
("spotColors", "Spot Color Objects"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("symbols", "Symbols"),
|
||||
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
const OBJECT_LABELS: [(&str, &str); 18] = [
|
||||
const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
("paths", "Paths"),
|
||||
("compoundPaths", "Compound Paths"),
|
||||
("groups", "Groups"),
|
||||
@@ -63,6 +63,7 @@ const OBJECT_LABELS: [(&str, &str); 18] = [
|
||||
("symbolInstances", "Symbol Instances"),
|
||||
("gradients", "Gradient Objects"),
|
||||
("patterns", "Pattern Objects"),
|
||||
("spots", "Spot Color Objects"),
|
||||
("meshes", "Gradient Meshes"),
|
||||
("blends", "Blends"),
|
||||
("envelopes", "Envelopes"),
|
||||
@@ -131,7 +132,7 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern and with a gradient.
|
||||
/// rows of its objects filled or stroked with a spot color, with a pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
@@ -139,6 +140,7 @@ fn sections(
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
spot_objects: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
gradient_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
@@ -183,7 +185,7 @@ fn sections(
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"spotColors" => spot_objects.to_vec(),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
@@ -273,15 +275,50 @@ fn gradient_label(p: &Paint) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
|
||||
/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
|
||||
/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
|
||||
/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
|
||||
/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
|
||||
/// renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own
|
||||
/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as
|
||||
/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not
|
||||
/// one.
|
||||
fn spot_swatches(d: &Document) -> HashSet<&str> {
|
||||
let mut first: BTreeMap<&str, bool> = BTreeMap::new();
|
||||
for s in d.swatches_iter() {
|
||||
first.entry(s.name.as_str()).or_insert(s.spot && s.paint.color().is_some());
|
||||
}
|
||||
first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect()
|
||||
}
|
||||
|
||||
/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is
|
||||
/// linked to, or those a gradient's stops are linked to, each once, in the order of the stops. A
|
||||
/// link at a tint of 0 prints no ink, a gradient whose stops are all at an opacity of 0 draws
|
||||
/// nothing, and a color that only looks like a spot color is not linked to one.
|
||||
fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
|
||||
let mut out: Vec<String> = vec![];
|
||||
let mut add = |swatch: &Option<String>, tint: f32| {
|
||||
if let Some(name) = swatch
|
||||
&& tint > 0.0
|
||||
&& spots.contains(name.as_str())
|
||||
&& !out.contains(name)
|
||||
{
|
||||
out.push(name.clone());
|
||||
}
|
||||
};
|
||||
match p {
|
||||
Paint::Solid { swatch, tint, .. } => add(swatch, *tint),
|
||||
Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity > 0.0) => g.gradient.stops.iter().for_each(|s| add(&s.swatch, s.tint)),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a spot color, a pattern or
|
||||
/// a gradient (`spots`: [`spot_swatches`]): the runs with a glyph outline (list markers and ruby
|
||||
/// included) or an underline or strikethrough bar. Spaces and line breaks draw no outline. A type
|
||||
/// object's characters carry their own fill and stroke, and the type object's own fills and strokes
|
||||
/// paint on its characters, so only those runs paint. The type is laid out with its inline
|
||||
/// graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
|
||||
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)) || !spot_labels(spots, p).is_empty();
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
|
||||
@@ -297,43 +334,53 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
|
||||
/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
|
||||
/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
|
||||
/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose
|
||||
/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect
|
||||
/// gives them a shape.
|
||||
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
|
||||
/// gradient.
|
||||
type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
|
||||
|
||||
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
|
||||
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
|
||||
/// hidden fill or stroke and a stroke with no width paint nothing, and neither does any fill or
|
||||
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
|
||||
/// compound path's own fills and strokes paint it) or of type whose layout draws nothing
|
||||
/// (`painted_runs`). An image's fills and strokes paint only where an effect gives them a shape.
|
||||
fn own_paints(
|
||||
d: &Document,
|
||||
n: &Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
label: fn(&Paint) -> Option<String>,
|
||||
label: &PaintNames<'_>,
|
||||
) -> Vec<String> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
|| !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
|
||||
|| n.appearance.items.iter().all(|i| label(i.paint()).is_empty())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns or gradients an image's shaped fills and strokes paint (their effects can
|
||||
// transform the paint, so they are matched by label).
|
||||
// The names an image's shaped fills and strokes paint (their effects can transform the paint,
|
||||
// so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_))
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
|
||||
let mut out: Vec<String> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Some(name) = label(item.paint()) else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(&name));
|
||||
if paints && !out.contains(&name) {
|
||||
out.push(name);
|
||||
if !item.visible() || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
for name in label(item.paint()) {
|
||||
if shaped.as_ref().is_none_or(|s| s.contains(&name)) && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`pattern_label`] or [`gradient_label`] as the names [`own_paints`] takes.
|
||||
fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<String> {
|
||||
move |p| label(p).into_iter().collect()
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -370,7 +417,13 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut patterns = BTreeSet::new();
|
||||
let mut symbols = BTreeSet::new();
|
||||
// `spot_objects`, `spot_rows` and `spot` hold the `spotObjects` entries, the rows of the objects filled or stroked with a spot
|
||||
// color, in walk order, and the spot colors they use. `spot_swatches` names the document's spot colors once, for every paint.
|
||||
let spot_swatches = spot_swatches(d);
|
||||
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() };
|
||||
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
|
||||
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
|
||||
@@ -446,17 +499,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(k) = k {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
if let Paint::Solid { swatch: Some(name), .. } = item.paint()
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
{
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The patterns and the gradients this object's fills and strokes paint, each once.
|
||||
let painted_runs = painted_runs(d, n);
|
||||
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
|
||||
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
|
||||
// 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.
|
||||
@@ -464,19 +511,38 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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
|
||||
[(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)]
|
||||
{
|
||||
if let Some(name) = label(paint)
|
||||
&& !used.contains(&name)
|
||||
{
|
||||
used.push(name);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Pattern Objects and Gradient Objects list.
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
|
||||
if !used_spots.is_empty() {
|
||||
let name = n.display_name();
|
||||
spot.extend(used_spots.iter().cloned());
|
||||
spot_rows.push((name.clone(), used_spots.join(", ")));
|
||||
spot_objects.push(json!({ "id": n.id.0, "name": name, "spotColors": used_spots }));
|
||||
*counts.entry("spots").or_default() += 1;
|
||||
}
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
patterns.extend(used_patterns.iter().cloned());
|
||||
@@ -529,6 +595,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"images": images,
|
||||
"symbols": symbols,
|
||||
"spotColors": spot,
|
||||
"spotColorNames": spot,
|
||||
"spotObjects": spot_objects,
|
||||
"swatches": d.swatches_iter().count(),
|
||||
"graphicStyles": d.graphic_styles.len(),
|
||||
"graphicStyleNames": styles,
|
||||
@@ -544,7 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -997,6 +1065,169 @@ mod tests {
|
||||
assert!(!text.contains("Spare"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Spot Color Objects lists each object filled or stroked with a spot color once,
|
||||
/// with the spot colors it uses, as a solid color or in a gradient's stops, one in a group and a
|
||||
/// type object whose characters use one included. A spot swatch no art uses adds no row; a
|
||||
/// process color that looks the same, Registration and a tint of 0 are not spot colors; paint
|
||||
/// that draws nothing is left out by the rules Pattern Objects follows; and Objects counts the
|
||||
/// listed objects. With Selection Only it lists the objects in the selection, each once, and the
|
||||
/// report writes the same rows.
|
||||
#[test]
|
||||
fn info_lists_the_spot_color_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
// An empty document lists none.
|
||||
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["spotObjects"].clone(), i["spotColorNames"].clone(), i["spotColors"].clone()), (json!([]), json!([]), json!([])));
|
||||
assert!(i["objects"]["spots"].is_null() && i["sections"][0]["rows"] == json!([]), "{i}");
|
||||
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nSPOT COLOR OBJECTS\nNone\n"), "{text}");
|
||||
let ink = |c: f64| json!({"model": "cmyk", "c": c, "m": 0.5, "y": 0.0, "k": 0.0});
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": ink(1.0), "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": ink(0.2), "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spare", "color": ink(0.4), "spot": true})).unwrap();
|
||||
// A global process color of the same color as Ink.
|
||||
s.execute("swatch.new", &json!({"name": "Look", "color": ink(1.0), "global": true})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let ramp = |a: &str, b: &str| json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000", "swatch": a}, {"offset": 1, "color": "#fff", "swatch": b}]});
|
||||
let (a, b, c, f, g, h) =
|
||||
(square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0), square(&mut s, 80.0), square(&mut s, 100.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Gold", "tint": 40})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [b], "swatch": "Look"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Ink", "tint": 50})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [c], "swatch": "Ink", "tint": 0})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("Gold", "Look")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [g], "gradient": ramp("Look", "Look")})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [h], "swatch": "[Registration]"})).unwrap();
|
||||
for id in [&c, &g, &h] {
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
|
||||
// A type object whose characters are filled with a spot color.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ink"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [t], "none": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden spot fill and a spot stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 120.0), square(&mut s, 140.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// Type with no characters, or of only spaces and a line break, paints nothing, and neither
|
||||
// does a guide made from a path with a spot color.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ink"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ink"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ink"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own spot fill, or an image's spot fill without an
|
||||
// effect that gives it a shape.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["spotObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "spotColors": ["Ink", "Gold"]},
|
||||
{"id": b, "name": "<Rectangle>", "spotColors": ["Ink"]},
|
||||
{"id": f, "name": "<Rectangle>", "spotColors": ["Gold"]},
|
||||
{"id": t, "name": "Type", "spotColors": ["Ink"]},
|
||||
])
|
||||
);
|
||||
assert_eq!((i["spotColorNames"].clone(), i["spotColors"].clone()), (json!(["Gold", "Ink"]), json!(["Gold", "Ink"])));
|
||||
// Objects counts the objects that Spot Color Objects lists.
|
||||
assert_eq!(i["objects"]["spots"].as_u64(), Some(4), "{}", i["objects"]);
|
||||
let objects = s.execute("document.info", &json!({"category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert!(objects.as_array().unwrap().contains(&json!(["Spot Color Objects", "4"])), "{objects}");
|
||||
s.execute("select.set", &json!({"ids": [c, g, h, d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["spots"].is_null() && i["spotObjects"] == json!([]) && i["spotColors"] == json!([]), "{i}");
|
||||
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("spotColors"), Some("Spot Color Objects")));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Both", "Ink, Gold"], ["<Rectangle>", "Ink"], ["<Rectangle>", "Gold"], ["Type", "Ink"]]));
|
||||
// A selection that holds the group and the object inside it lists that object once.
|
||||
for ids in [json!([group, b]), json!([b, group])] {
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Ink"]]), "{ids}");
|
||||
assert_eq!((i["objects"]["spots"].as_u64(), i["spotColorNames"].clone()), (Some(1), json!(["Ink"])), "{ids}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["spotColors"].clone()), (json!([["Type", "Ink"]]), json!(["Ink"])));
|
||||
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nSPOT COLOR OBJECTS\nBoth: Ink, Gold\n<Rectangle>: Ink\n<Rectangle>: Gold\nType: Ink\n"), "{text}");
|
||||
assert!(!text.contains("Spare") && !text.contains("Look"), "{text}");
|
||||
}
|
||||
|
||||
/// Spot Color Objects lists a grayscale image colorized with a spot color, and leaves out a
|
||||
/// gradient whose stops are all at an opacity of 0, which draws nothing.
|
||||
#[test]
|
||||
fn spot_color_objects_take_colorized_images_and_skip_clear_gradients() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
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();
|
||||
assert!(s.doc().unwrap().doc.node(image).unwrap().extras().colorize.is_some());
|
||||
let clear = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let stops =
|
||||
json!([{"offset": 0, "color": "#000", "swatch": "Ink", "opacity": 0}, {"offset": 1, "color": "#fff", "swatch": "Ink", "opacity": 0}]);
|
||||
s.execute("paint.setFill", &json!({"ids": [clear], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let name = s.doc().unwrap().doc.node(image).unwrap().display_name();
|
||||
assert_eq!(i["spotObjects"], json!([{"id": image.0, "name": name, "spotColors": ["Ink"]}]), "{i}");
|
||||
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -476,11 +476,14 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
|
||||
} else {
|
||||
// A gradient that repeats or reflects expands as its stops repeated over the box.
|
||||
let (g, runs) = padded_on(g, bounds);
|
||||
let g = &*g;
|
||||
let frame = Frame::new(g, bounds);
|
||||
match to {
|
||||
GradientTo::Mesh => vec![Node::new(d.alloc_id(), NodeKind::Mesh(frame.mesh(&g.gradient)))],
|
||||
GradientTo::Objects(n) => frame
|
||||
.pieces(&g.gradient, n as usize)
|
||||
.pieces(&g.gradient, n as usize, runs)
|
||||
.into_iter()
|
||||
.map(|(shape, (color, opacity))| {
|
||||
let fill = FillLayer { opacity, overprint: f.overprint, ..FillLayer::new(Paint::solid(color)) };
|
||||
@@ -1234,8 +1237,64 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
|
||||
(super::paint::stored_color(store_in, c), a)
|
||||
});
|
||||
}
|
||||
let (geom, spread) = (g.resolve(bounds), g.gradient.spreader());
|
||||
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
|
||||
}
|
||||
|
||||
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
|
||||
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
|
||||
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
|
||||
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
|
||||
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
|
||||
/// there to 1.
|
||||
fn padded_on(g: &GradientPaint, bounds: Rect) -> (std::borrow::Cow<'_, GradientPaint>, Option<(f64, usize)>) {
|
||||
use std::borrow::Cow;
|
||||
if !g.gradient.is_spread() {
|
||||
return (Cow::Borrowed(g), None);
|
||||
}
|
||||
let geom = g.resolve(bounds);
|
||||
Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32))
|
||||
match g.gradient.padded_over(&geom, bounds) {
|
||||
Some(p) => {
|
||||
let runs = Some((p.first, p.runs));
|
||||
(Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)
|
||||
}
|
||||
None => {
|
||||
let runs = Some((0.0, g.gradient.repeat_count() as usize));
|
||||
(Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edges (gradient parameters, from `lo` to `hi`) of about `n` bands [`Frame::pieces`] cuts:
|
||||
/// evenly spaced, or for stops repeated in `runs` ([`padded_on`]: where the first run starts and
|
||||
/// how many runs lie evenly from there to 1) the same whole number of bands in each run between
|
||||
/// `lo` and `hi` (at least one, about `n` in all), so every run starts on an edge and no band
|
||||
/// holds two runs' colors.
|
||||
fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64> {
|
||||
let n = n.max(1);
|
||||
let even = || {
|
||||
let step = (hi - lo) / n as f64;
|
||||
(0..=n).map(|k| lo + k as f64 * step).collect()
|
||||
};
|
||||
let Some((first, count)) = runs.filter(|&(first, count)| count > 0 && (0.0..1.0).contains(&first)) else { return even() };
|
||||
let run = (1.0 - first) / count as f64;
|
||||
let (from, to) = (lo.max(first), hi.min(1.0));
|
||||
let shown = (to - from) / run;
|
||||
if !(shown > 0.0 && shown.is_finite()) {
|
||||
return even();
|
||||
}
|
||||
let step = run / (n as f64 / shown).round().max(1.0);
|
||||
// Both whole numbers of steps from `first`, at most `n` plus the runs shown, plus one.
|
||||
let (k0, k1) = (((from - first) / step).ceil(), ((to - first) / step).floor());
|
||||
let mut edges = vec![lo];
|
||||
for k in (k0 as usize)..(k1 as usize).saturating_add(1) {
|
||||
let t = first + k as f64 * step;
|
||||
if t > edges.last().copied().unwrap_or(lo) + 1e-12 && t < hi - 1e-12 {
|
||||
edges.push(t);
|
||||
}
|
||||
}
|
||||
edges.push(hi);
|
||||
edges
|
||||
}
|
||||
|
||||
/// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every
|
||||
@@ -1404,10 +1463,17 @@ impl Frame {
|
||||
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
|
||||
/// center from each band's start to the seam, for a diamond one, nested squares (largest
|
||||
/// first). Each paints over the ones below except its band, so no seam shows between bands.
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up. Stops repeated
|
||||
/// in `runs` ([`padded_on`]) get the same whole number of bands in each run ([`band_edges`]).
|
||||
fn pieces(&self, g: &Gradient, n: usize, runs: Option<(f64, usize)>) -> Vec<(PathData, (Color, f32))> {
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
let color = |e: &[f64], k: usize| {
|
||||
let (a, b) = (e.get(k).copied().unwrap_or(0.0), e.get(k + 1).copied().unwrap_or(1.0));
|
||||
g.sample_keep_model(((a + b) / 2.0) as f32)
|
||||
};
|
||||
if let Some((geom, b, _)) = &self.conic {
|
||||
// Evenly spaced around the turn, as the wedges are.
|
||||
let n = band_edges(0.0, 1.0, n, runs).len().saturating_sub(1);
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
@@ -1419,51 +1485,52 @@ impl Frame {
|
||||
return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))];
|
||||
};
|
||||
// Nested squares about the center, largest first, as a radial gradient's ellipses.
|
||||
let step = reach / n as f64;
|
||||
let edges = band_edges(0.0, *reach, n, runs);
|
||||
let square = |t: f64| -> SubPath {
|
||||
let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect();
|
||||
SubPath::polyline(&pts, true)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..edges.len().saturating_sub(1))
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = PathData::single(square((k + 1) as f64 * step));
|
||||
let mut shape = PathData::single(square(edges.get(k + 1).copied().unwrap_or(*reach)));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = square(k as f64 * step);
|
||||
let mut hole = square(edges.get(k).copied().unwrap_or(0.0));
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let edges = band_edges(self.t0, self.t1, n, runs);
|
||||
let bands = edges.len().saturating_sub(1);
|
||||
let edge = |k: usize| edges.get(k).copied().unwrap_or(self.t1);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
let m = Affine::new([self.along.x * t, self.along.y * t, self.across.x * t, self.across.y * t, c.x, c.y]);
|
||||
shapes::ellipse(Rect::new(-1.0, -1.0, 1.0, 1.0)).transformed(m)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..bands)
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = ellipse((k + 1) as f64 * step);
|
||||
let mut shape = ellipse(edge(k + 1));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = ellipse(k as f64 * step).subpaths.remove(0);
|
||||
let mut hole = ellipse(edge(k)).subpaths.remove(0);
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, color(k))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
(0..n)
|
||||
(0..bands)
|
||||
.map(|k| {
|
||||
let a = self.t0 + k as f64 * step;
|
||||
let b = if opaque { self.t1 } else { a + step };
|
||||
let a = edge(k);
|
||||
let b = if opaque { self.t1 } else { edge(k + 1) };
|
||||
let pts = [self.at(a, self.s0), self.at(b, self.s0), self.at(b, self.s1), self.at(a, self.s1)];
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(k))
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(&edges, k))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -92,9 +92,9 @@ pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, leave_out_unreadable_save_paths,
|
||||
reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates,
|
||||
template_filters, templates_dialog_folder, templates_folder,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, documents_dialog_folder, export_folder,
|
||||
leave_out_unreadable_save_paths, reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan,
|
||||
save_with, stamp_save_dates, template_filters, templates_dialog_folder, templates_folder,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
|
||||
@@ -123,7 +123,10 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
pub use access::{write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
pub(crate) use access::{
|
||||
|
||||
@@ -112,6 +112,31 @@ pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write)
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
/// writers keep their existing errors; an automation-root refusal is never reclassified.
|
||||
pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
write_save_file_with(path, &mut |w| w.write_all(bytes))
|
||||
}
|
||||
|
||||
/// [`write_save_file`] for a streamed save.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
let reason = format!("{path}: {error}");
|
||||
if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) }
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write_file_with(path, fill)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn create_dir(path: &str) -> Result<()> {
|
||||
may_write(path)?;
|
||||
|
||||
@@ -825,6 +825,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// A TIFF with more strips or tiles than the decoder can count
|
||||
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
|
||||
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
|
||||
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`exif_orientation`]) turns or flips it is
|
||||
/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG
|
||||
/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -863,7 +866,16 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
|
||||
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
|
||||
let turned = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff") && exif_orientation(bytes).is_some();
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten();
|
||||
let turned = orientation.is_some();
|
||||
// The resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
|
||||
let shown_ppi = ppi.map(|(x, y)| if quarter { (y, x) } else { (x, y) });
|
||||
if let Some(orientation) = orientation.filter(|_| matches!(f.id, "jpg" | "tiff"))
|
||||
&& let Some((tiff, size)) = vectorcraft_doc::cmyk::turned_cmyk(bytes, orientation, shown_ppi)
|
||||
{
|
||||
return stored(tiff, "image/tiff", size, shown_ppi);
|
||||
}
|
||||
let kept = match f.id {
|
||||
_ if turned => None,
|
||||
"png" | "jpg" | "gif" | "webp" => Some(bytes.to_vec()),
|
||||
@@ -879,36 +891,39 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
|
||||
};
|
||||
let mut img = match (f.id == "tiff").then(extra_samples).flatten() {
|
||||
Some(img) => img,
|
||||
Some(img) => image::DynamicImage::ImageRgba8(img),
|
||||
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
|
||||
Some(read) => read.map_err(err)?,
|
||||
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
|
||||
None => {
|
||||
use image::ImageDecoder as _;
|
||||
let mut decoder = reader.into_decoder().map_err(err)?;
|
||||
let decoder = reader.into_decoder().map_err(err)?;
|
||||
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
|
||||
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
|
||||
let mut img = image::DynamicImage::from_decoder(decoder).map_err(err)?;
|
||||
img.apply_orientation(orientation);
|
||||
img.to_rgba8()
|
||||
image::DynamicImage::from_decoder(decoder).map_err(err)?
|
||||
}
|
||||
},
|
||||
};
|
||||
img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms));
|
||||
let mut img = img.into_rgba8();
|
||||
if f.id == "tga" {
|
||||
super::tgaread::fix_alpha(bytes, &mut img);
|
||||
}
|
||||
as_png(img, None, ppi)
|
||||
as_png(img, None, shown_ppi)
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none.
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image
|
||||
/// ([`vectorcraft_doc::cmyk::tiff_orientation`]).
|
||||
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
let mut decoder = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
|
||||
decoder.orientation().ok().filter(|o| *o != image::metadata::Orientation::NoTransforms)
|
||||
use image::metadata::Orientation;
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
|
||||
|
||||
@@ -157,6 +157,11 @@ fn documents_folder() -> Option<std::path::PathBuf> {
|
||||
Some(home.join("Documents"))
|
||||
}
|
||||
|
||||
/// A Save As after a refused Save starts in Documents, else home, never the refused folder.
|
||||
pub fn documents_dialog_folder() -> Option<String> {
|
||||
documents_folder().filter(|p| p.is_dir()).map(|p| p.to_string_lossy().into_owned()).or_else(home_folder)
|
||||
}
|
||||
|
||||
/// `XDG_DOCUMENTS_DIR` in a `user-dirs.dirs` file's `text`, `$HOME` being `home`. None when it isn't
|
||||
/// set, is relative, or is the home folder itself (the spec's way of turning it off).
|
||||
fn xdg_documents(text: &str, home: &std::path::Path) -> Option<std::path::PathBuf> {
|
||||
@@ -1043,7 +1048,7 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value>
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let mut out = job.write_streamed(&mut super::write_file_with)?;
|
||||
let mut out = job.write_streamed(&mut super::write_save_file_with)?;
|
||||
job.complete(s, uid);
|
||||
leave_out_unreadable_save_paths(&mut out, str_param(p, "path"));
|
||||
Ok(out)
|
||||
@@ -1170,7 +1175,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -653,6 +653,11 @@ pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => e,
|
||||
})?;
|
||||
remember(s, &p);
|
||||
// A prepared export is written later, maybe on another thread: it names the folder as this
|
||||
// request may see it.
|
||||
if let (Some(folder), Some(Some(export))) = (hidden, s.screens_hand_off.as_mut()) {
|
||||
export.hidden = Some((folder.to_string(), super::access::shown_path(folder).into_owned()));
|
||||
}
|
||||
if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) {
|
||||
leave_out_unreadable_folder(&mut r, folder);
|
||||
}
|
||||
@@ -663,10 +668,14 @@ pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// give: `folder` as the path the error is about names it by its own name
|
||||
/// ([`super::access::shown_path`]), and the rest of the message stays.
|
||||
fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError {
|
||||
let name = super::access::shown_path(folder);
|
||||
leave_out_folder_named(e, folder, &super::access::shown_path(folder))
|
||||
}
|
||||
|
||||
/// [`leave_out_folder_from_error`] with `folder` named `name`.
|
||||
fn leave_out_folder_named(e: EngineError, folder: &str, name: &str) -> EngineError {
|
||||
match e {
|
||||
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)),
|
||||
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) },
|
||||
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, name)),
|
||||
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, name) },
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
@@ -699,9 +708,14 @@ fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String
|
||||
/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`),
|
||||
/// as the reply of an export to a ZIP names them.
|
||||
fn leave_out_unreadable_folder(r: &mut Value, folder: &str) {
|
||||
if super::access::shown(folder) {
|
||||
return;
|
||||
if !super::access::shown(folder) {
|
||||
leave_out_folder(r, folder);
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply `r` of an export into `folder` with the ZIP's `path` left out and `files` named
|
||||
/// relative to `folder` ([`leave_out_unreadable_folder`]).
|
||||
fn leave_out_folder(r: &mut Value, folder: &str) {
|
||||
let Some(o) = r.as_object_mut() else { return };
|
||||
o.remove("path");
|
||||
let inside = format!("{folder}/");
|
||||
@@ -1074,7 +1088,7 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items };
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items, hidden: None };
|
||||
match &mut s.screens_hand_off {
|
||||
Some(slot) => {
|
||||
*slot = Some(export);
|
||||
@@ -1095,9 +1109,27 @@ pub struct ScreenExport {
|
||||
rows: Vec<Row>,
|
||||
naming: Naming,
|
||||
items: Vec<Item>,
|
||||
/// The export folder and the name the request that prepared the export may see it by, when the
|
||||
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
|
||||
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
|
||||
hidden: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The folder `document.exportForScreens` (`id`) with `params` writes into, the client's
|
||||
/// `folder` or else the one its `exportPreset` keeps, with the name the request being served may
|
||||
/// see it by when the reply leaves it out: a preset's folder outside the read roots, named by
|
||||
/// its own name ([`super::access::shown_path`]). `assets.export` takes no preset, so for it the
|
||||
/// folder is the client's. → `None` without a folder (the files come back in the reply) or for
|
||||
/// an unknown preset, which the export itself refuses.
|
||||
pub fn screen_export_folder(&self, id: &str, params: &Value) -> Option<(String, Option<String>)> {
|
||||
let given = params.get("folder").is_some();
|
||||
let p = if given || id == ASSETS { params.clone() } else { with_preset(self, params).ok()? };
|
||||
let folder = str_param(&p, "folder").filter(|f| !f.is_empty())?.to_string();
|
||||
let hidden = (!given && !super::access::shown(&folder)).then(|| super::access::shown_path(&folder).into_owned());
|
||||
Some((folder, hidden))
|
||||
}
|
||||
|
||||
/// Run `assets.export` when `id` names it, else `document.exportForScreens`, with `params` as
|
||||
/// a command (checked and journaled as any other; Export for Screens remembers its settings)
|
||||
/// that encodes and writes nothing → the export it prepared, which [`ScreenExport::write`]
|
||||
@@ -1123,10 +1155,19 @@ impl ScreenExport {
|
||||
/// return → the reply of `document.exportForScreens`. It reports one progress step per file
|
||||
/// ([`vectorcraft_doc::cancel::progress`]), and a cancel stops it before it encodes or writes
|
||||
/// another file.
|
||||
pub fn write(self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
pub fn write(mut self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let cmd = self.cmd;
|
||||
let hidden = self.hidden.take();
|
||||
// A refusal names `assets.export` when that command prepared the export, as its reply does.
|
||||
encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) })
|
||||
let r = encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) });
|
||||
match hidden {
|
||||
Some((folder, name)) => {
|
||||
let mut r = r.map_err(|e| leave_out_folder_named(e, &folder, &name))?;
|
||||
leave_out_folder(&mut r, &folder);
|
||||
Ok(r)
|
||||
}
|
||||
None => r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -907,6 +907,254 @@ fn a_photo_places_the_way_its_exif_orientation_says() {
|
||||
assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top");
|
||||
}
|
||||
|
||||
/// Where the first stored pixel shows once EXIF (or TIFF) `orientation` turns the image, as
|
||||
/// (right, bottom): orientations 1 and 5 keep it at the top left, 2 and 6 put it at the top right,
|
||||
/// 3 and 7 at the bottom right, 4 and 8 at the bottom left. Values outside 1 to 8 leave it.
|
||||
fn first_pixel_at(orientation: u16) -> (bool, bool) {
|
||||
match orientation {
|
||||
2 | 6 => (true, false),
|
||||
3 | 7 => (true, true),
|
||||
4 | 8 => (false, true),
|
||||
_ => (false, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// A little-endian EXIF block (a TIFF header and directory, as a PNG `eXIf` chunk or a WebP
|
||||
/// `EXIF` chunk holds it) with an Orientation of `orientation` and an XResolution and YResolution
|
||||
/// of `x` and `y` pixels per inch.
|
||||
fn exif_block(orientation: u16, (x, y): (u32, u32)) -> Vec<u8> {
|
||||
let entry = |tag: u16, kind: u16, value: u32| [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &1u32.to_le_bytes(), &value.to_le_bytes()].concat();
|
||||
// Orientation, XResolution, YResolution, ResolutionUnit inches; the two rationals follow.
|
||||
[
|
||||
b"II".as_slice(),
|
||||
&[0x2a, 0, 8, 0, 0, 0],
|
||||
&4u16.to_le_bytes(),
|
||||
&entry(0x0112, 3, u32::from(orientation)),
|
||||
&entry(0x011a, 5, 62),
|
||||
&entry(0x011b, 5, 70),
|
||||
&entry(0x0128, 3, 2),
|
||||
&[0, 0, 0, 0],
|
||||
&[x.to_le_bytes(), 1u32.to_le_bytes(), y.to_le_bytes(), 1u32.to_le_bytes()].concat(),
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
|
||||
/// A photo turned a quarter by its EXIF orientation keeps its physical size: the resolution's
|
||||
/// axes swap with the pixels', in what Place reports and in the stored image. Every orientation
|
||||
/// puts the first stored pixel in its corner once, and the stored image, read again, is not turned
|
||||
/// a second time. Values outside 1 to 8 leave the photo as stored.
|
||||
#[test]
|
||||
fn a_quarter_turn_swaps_the_resolution_axes() {
|
||||
// 48 × 32: the top-left 16 × 16 (one whole JPEG MCU) red, the rest white.
|
||||
let rgb = image::RgbImage::from_fn(48, 32, |x, y| if x < 16 && y < 16 { image::Rgb([220, 0, 0]) } else { image::Rgb([255, 255, 255]) });
|
||||
let mut jpg = Vec::new();
|
||||
image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap();
|
||||
for orientation in [0u16, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
|
||||
let exif = [b"Exif\0\0".as_slice(), &exif_block(orientation, (300, 150))].concat();
|
||||
// Without a JFIF density the resolution comes from the EXIF block.
|
||||
let mut turned = jpg[..2].to_vec();
|
||||
turned.extend([0xff, 0xe1]);
|
||||
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
turned.extend(&exif);
|
||||
turned.extend(&jpg[2..]);
|
||||
let what = format!("orientation {orientation}");
|
||||
assert_eq!(super::ppi::resolution(&turned), Some((300.0, 150.0)), "{what}: as stored");
|
||||
let quarter = (5..=8).contains(&orientation);
|
||||
let (size, ppi) = if quarter { ((32, 48), (150.0, 300.0)) } else { ((48, 32), (300.0, 150.0)) };
|
||||
let img = raster_image(&turned).unwrap();
|
||||
assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}");
|
||||
assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image");
|
||||
let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8();
|
||||
let red = |x: u32, y: u32| px.get_pixel(x, y)[1] < 80;
|
||||
let (w, h) = size;
|
||||
let corners = [(false, false), (true, false), (true, true), (false, true)];
|
||||
let reds: Vec<_> =
|
||||
corners.into_iter().filter(|&(right, bottom)| red(if right { w - 4 } else { 4 }, if bottom { h - 4 } else { 4 })).collect();
|
||||
assert_eq!(reds, [first_pixel_at(orientation)], "{what}: the first stored pixel's corner");
|
||||
let again = raster_image(&img.blob.bytes).unwrap();
|
||||
assert_eq!(((again.width, again.height), again.ppi), (size, Some(ppi)), "{what}: read again, it isn't turned again");
|
||||
}
|
||||
}
|
||||
|
||||
/// `tiff` (little-endian) with an Orientation tag (274) of `value`, a SHORT or, when `long`, a
|
||||
/// LONG, and, when `y_ppi` is given, a YResolution (283, which `tiff` must have) of that many
|
||||
/// pixels per inch: its first directory copied to the end of the file with the tag added in order,
|
||||
/// and the header pointing there, so that every other offset in the file still holds.
|
||||
fn tiff_oriented(tiff: &[u8], value: u16, long: bool, y_ppi: Option<u32>) -> Vec<u8> {
|
||||
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
|
||||
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
|
||||
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
|
||||
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 274).unwrap_or(n);
|
||||
let (kind, v) = if long { (4u16, u32::from(value).to_le_bytes()) } else { (3, [value.to_le_bytes(), [0, 0]].concat().try_into().unwrap()) };
|
||||
entries.insert(i, [&274u16.to_le_bytes()[..], &kind.to_le_bytes(), &1u32.to_le_bytes(), &v].concat());
|
||||
let mut out = tiff.to_vec();
|
||||
if out.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
if let Some(y) = y_ppi {
|
||||
let rational = u32::try_from(out.len()).unwrap();
|
||||
out.extend([y.to_le_bytes(), 1u32.to_le_bytes()].concat());
|
||||
let e = entries.iter_mut().find(|e| u16::from_le_bytes([e[0], e[1]]) == 283).unwrap();
|
||||
e[8..12].copy_from_slice(&rational.to_le_bytes());
|
||||
}
|
||||
let ifd = u32::try_from(out.len()).unwrap();
|
||||
out[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
|
||||
out.extend(entries.concat());
|
||||
out.extend([0; 4]);
|
||||
out
|
||||
}
|
||||
|
||||
/// TIFFs the image decoder can't read, grayscale with an alpha channel and 1-bit ones compressed
|
||||
/// with CCITT Group 3, turn and flip as their Orientation tag says, as the others do (#4284),
|
||||
/// whether the tag is a SHORT or a LONG. A quarter turn swaps the resolution's axes.
|
||||
#[test]
|
||||
fn tiffs_read_without_the_image_decoder_follow_their_orientation() {
|
||||
// 3 × 2 at 150 × 300 ppi, the first pixel black and the rest white, opaque.
|
||||
let gray = hand_tiff(1, 8, &[2], false, &[vec![0, 255, 255, 255, 255, 255], vec![255; 6]]);
|
||||
let rows: Vec<Vec<bool>> = (0..2).map(|y| (0..3).map(|x| x == 0 && y == 0).collect()).collect();
|
||||
let g = vectorcraft_testkit::tiff::Group3 {
|
||||
rows: &rows,
|
||||
compression: 2,
|
||||
t4_options: 0,
|
||||
photometric: 0,
|
||||
fill_order: 1,
|
||||
rows_per_strip: 2,
|
||||
tile: None,
|
||||
rtc: false,
|
||||
};
|
||||
let fax = vectorcraft_testkit::tiff::group3(&g);
|
||||
// The Group 3 file declares no resolution.
|
||||
for (kind, file, y_ppi) in [("Group 3", fax, None), ("gray with alpha", gray, Some(300))] {
|
||||
assert!(image::load_from_memory(&file).is_err(), "{kind}: the image decoder reads it now");
|
||||
for (orientation, long) in (1..=8).flat_map(|o| [(o, false), (o, true)]) {
|
||||
let what = format!("{kind}, orientation {orientation}, LONG {long}");
|
||||
let img = raster_image(&tiff_oriented(&file, orientation, long, y_ppi)).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let quarter = orientation >= 5;
|
||||
let size = if quarter { (2, 3) } else { (3, 2) };
|
||||
let ppi = y_ppi.map(|y| if quarter { (f64::from(y), 150.0) } else { (150.0, f64::from(y)) });
|
||||
assert_eq!(((img.width, img.height), img.ppi), (size, ppi), "{what}");
|
||||
assert_eq!(super::ppi::resolution(&img.blob.bytes), ppi, "{what}: the stored image");
|
||||
let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8();
|
||||
let (right, bottom) = first_pixel_at(orientation);
|
||||
let (x, y) = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 });
|
||||
let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect();
|
||||
assert_eq!(black, [(x, y)], "{what}: the first stored pixel's corner");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK TIFF that its Orientation tag turns or flips keeps its inks, turned, whether it stores
|
||||
/// them together or one plane per ink, at 8 or 16 bits; a quarter turn swaps the resolution's axes.
|
||||
/// Read again, the stored image is not turned a second time.
|
||||
#[test]
|
||||
fn cmyk_tiffs_turned_by_their_orientation_keep_their_inks() {
|
||||
// 3 × 2 at 150 × 300 ppi: the first pixel full cyan, the others 30% black.
|
||||
let first: [u8; 4] = [255, 0, 0, 0];
|
||||
let other: [u8; 4] = [0, 0, 0, 77];
|
||||
let channel = |i: usize| -> Vec<u16> { (0..6).map(|p| u16::from(if p == 0 { first[i] } else { other[i] })).collect() };
|
||||
for (bits, planar) in [(8, false), (8, true), (16, false), (16, true)] {
|
||||
let channels: Vec<Vec<u16>> = (0..4).map(|i| channel(i).iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect();
|
||||
let file = hand_tiff(5, bits, &[], planar, &channels);
|
||||
for orientation in 1..=8 {
|
||||
let what = format!("{bits} bits, planar {planar}, orientation {orientation}");
|
||||
let img = raster_image(&tiff_oriented(&file, orientation, false, Some(300))).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let quarter = orientation >= 5;
|
||||
let size = if quarter { (2, 3) } else { (3, 2) };
|
||||
let ppi = if quarter { (300.0, 150.0) } else { (150.0, 300.0) };
|
||||
assert_eq!(((img.width, img.height), img.ppi, img.blob.mime.as_str()), (size, Some(ppi), "image/tiff"), "{what}");
|
||||
assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image");
|
||||
let inks = img.blob.cmyk().unwrap_or_else(|| panic!("{what}: the inks are lost"));
|
||||
assert_eq!((inks.width, inks.height), size, "{what}: the inks' size");
|
||||
let (right, bottom) = first_pixel_at(orientation);
|
||||
let at = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 });
|
||||
for (i, px) in inks.data.chunks(4).enumerate() {
|
||||
let (x, y) = (u32::try_from(i).unwrap() % size.0, u32::try_from(i).unwrap() / size.0);
|
||||
assert_eq!(px, if (x, y) == at { first } else { other }, "{what}: the inks of pixel ({x}, {y})");
|
||||
}
|
||||
let again = raster_image(&img.blob.bytes).unwrap();
|
||||
assert_eq!(((again.width, again.height), again.blob.cmyk()), (size, Some(inks)), "{what}: read again, it isn't turned again");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK JPEG that its EXIF orientation turns or flips keeps its inks, turned, stored as a CMYK
|
||||
/// TIFF; a quarter turn swaps the resolution's axes. Orientation 1 keeps the JPEG as it is, and
|
||||
/// the stored image, read again, is not turned a second time.
|
||||
#[test]
|
||||
fn cmyk_jpegs_turned_by_their_orientation_keep_their_inks() {
|
||||
use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions};
|
||||
// 48 × 32: the top-left 16 × 16 (one whole JPEG MCU) full cyan, the rest 30% black.
|
||||
let inks: Vec<u8> =
|
||||
(0..32u32).flat_map(|y| (0..48u32).flat_map(move |x| if x < 16 && y < 16 { [255, 0, 0, 0] } else { [0, 0, 0, 77] })).collect();
|
||||
let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() };
|
||||
let jpg = jpeg::encode(&inks, 48, 32, 100, None, &o).unwrap();
|
||||
for orientation in 1..=8u16 {
|
||||
let exif = [b"Exif\0\0".as_slice(), &exif_block(orientation, (300, 150))].concat();
|
||||
let mut file = jpg[..2].to_vec();
|
||||
file.extend([0xff, 0xe1]);
|
||||
file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
file.extend(&exif);
|
||||
file.extend(&jpg[2..]);
|
||||
let what = format!("orientation {orientation}");
|
||||
let quarter = orientation >= 5;
|
||||
let (size, ppi) = if quarter { ((32, 48), (150.0, 300.0)) } else { ((48, 32), (300.0, 150.0)) };
|
||||
let mime = if orientation == 1 { "image/jpeg" } else { "image/tiff" };
|
||||
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert_eq!(((img.width, img.height), img.ppi, img.blob.mime.as_str()), (size, Some(ppi), mime), "{what}");
|
||||
assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image");
|
||||
let inks = img.blob.cmyk().unwrap_or_else(|| panic!("{what}: the inks are lost"));
|
||||
assert_eq!((inks.width, inks.height), size, "{what}: the inks' size");
|
||||
let (w, h) = size;
|
||||
let at = |x: u32, y: u32| inks.data[usize::try_from((y * w + x) * 4).unwrap()..][..4].to_vec();
|
||||
let cyan = |p: &[u8]| p[0] > 200 && p[3] < 40;
|
||||
let corners = [(false, false), (true, false), (true, true), (false, true)];
|
||||
let cyans: Vec<_> =
|
||||
corners.into_iter().filter(|&(right, bottom)| cyan(&at(if right { w - 4 } else { 4 }, if bottom { h - 4 } else { 4 }))).collect();
|
||||
assert_eq!(cyans, [first_pixel_at(orientation)], "{what}: the first stored pixel's corner");
|
||||
let black = at(w / 2, h / 2);
|
||||
assert!(black[0] < 40 && (60..=95).contains(&black[3]), "{what}: the other inks, {black:?}");
|
||||
let again = raster_image(&img.blob.bytes).unwrap();
|
||||
assert_eq!(((again.width, again.height), again.blob.cmyk()), (size, Some(inks)), "{what}: read again, it isn't turned again");
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG (its `eXIf` chunk and `pHYs` resolution), a WebP (its `EXIF` chunk) and an RGB TIFF read
|
||||
/// by the image decoder, turned a quarter by their orientation, swap their resolution's axes; a
|
||||
/// half turn keeps them.
|
||||
#[test]
|
||||
fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() {
|
||||
use image::ImageEncoder as _;
|
||||
let rgb = image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(if x == 0 && y == 0 { [0, 0, 0] } else { [255, 255, 255] }));
|
||||
for orientation in [3u16, 6, 8] {
|
||||
let mut png = Vec::new();
|
||||
let mut enc = image::codecs::png::PngEncoder::new(&mut png);
|
||||
enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap();
|
||||
enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap();
|
||||
let png = super::ppi::with_png_resolution(&png, (150.0, 300.0));
|
||||
let mut webp = Vec::new();
|
||||
let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut webp);
|
||||
enc.set_exif_metadata(exif_block(orientation, (150, 300))).unwrap();
|
||||
enc.write_image(rgb.as_raw(), 3, 2, image::ExtendedColorType::Rgb8).unwrap();
|
||||
let channel = |c: usize| -> Vec<u16> { rgb.pixels().map(|p| u16::from(p[c])).collect() };
|
||||
let tiff = tiff_oriented(&hand_tiff(2, 8, &[], false, &[channel(0), channel(1), channel(2)]), orientation, false, Some(300));
|
||||
for (kind, file) in [("PNG", png), ("WebP", webp), ("TIFF", tiff)] {
|
||||
let what = format!("{kind}, orientation {orientation}");
|
||||
assert_eq!(super::ppi::resolution(&file), Some((150.0, 300.0)), "{what}: as stored");
|
||||
let quarter = orientation >= 5;
|
||||
let (size, ppi) = if quarter { ((2, 3), (300.0, 150.0)) } else { ((3, 2), (150.0, 300.0)) };
|
||||
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
assert_eq!(((img.width, img.height), img.ppi), (size, Some(ppi)), "{what}");
|
||||
assert_eq!(super::ppi::resolution(&img.blob.bytes), Some(ppi), "{what}: the stored image");
|
||||
let px = image::load_from_memory(&img.blob.bytes).unwrap().to_luma8();
|
||||
let (right, bottom) = first_pixel_at(orientation);
|
||||
let at = (if right { size.0 - 1 } else { 0 }, if bottom { size.1 - 1 } else { 0 });
|
||||
let black: Vec<_> = px.enumerate_pixels().filter(|p| p.2[0] < 128).map(|p| (p.0, p.1)).collect();
|
||||
assert_eq!(black, [at], "{what}: the first stored pixel's corner");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With `importer` named, a file up to the importer's limit is read whole and a larger one is an
|
||||
/// error, whatever its content.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Save errors retain their type without changing the other filesystem writers (#6146).
|
||||
|
||||
use std::io::{self, ErrorKind};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::{SaveMode, access, save_plan, save_with, write_file_with, write_save_file_with};
|
||||
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 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();
|
||||
let ordinary = write_file_with(&path, &mut |_| Err(io::Error::new(kind, "injected"))).unwrap_err();
|
||||
let reason = format!("{path}: injected");
|
||||
assert!(matches!(&ordinary, EngineError::Other(_)));
|
||||
assert_eq!(ordinary.to_string(), reason);
|
||||
if matches!(kind, ErrorKind::PermissionDenied | ErrorKind::ReadOnlyFilesystem) {
|
||||
assert!(matches!(&typed, EngineError::ReadOnlyLocation(_)));
|
||||
assert_eq!(typed.to_string(), format!("{READ_ONLY_LOCATION}: {reason}"));
|
||||
} else {
|
||||
assert!(matches!(&typed, EngineError::Other(_)));
|
||||
assert_eq!(typed.to_string(), reason);
|
||||
}
|
||||
assert!(!std::path::Path::new(&path).exists());
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_failed_save_keeps_document_and_options() {
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", &json!({"width": 40, "height": 40})).unwrap();
|
||||
session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
|
||||
let st = session.doc_mut().unwrap();
|
||||
st.path = Some("Poster.svg".into());
|
||||
st.format = "svg";
|
||||
st.save_options = json!({"decimals": 3}).as_object().unwrap().clone();
|
||||
let before = serde_json::to_value(&*st.doc).unwrap();
|
||||
let options = st.save_options.clone();
|
||||
let plan = save_plan(&session, SaveMode::Save, &json!({"modified": null})).unwrap();
|
||||
let e = save_with(&mut session, plan, |path, _| Err(access::save_write_error(path, io::Error::from(ErrorKind::PermissionDenied)))).unwrap_err();
|
||||
assert!(matches!(e, EngineError::ReadOnlyLocation(_)));
|
||||
let st = session.doc().unwrap();
|
||||
assert_eq!(st.path.as_deref(), Some("Poster.svg"));
|
||||
assert_eq!(st.format, "svg");
|
||||
assert_eq!(st.save_options, options);
|
||||
assert!(st.is_dirty());
|
||||
assert_eq!(serde_json::to_value(&*st.doc).unwrap(), before);
|
||||
}
|
||||
@@ -730,11 +730,86 @@ fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": parent});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap();
|
||||
let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string();
|
||||
let root = inside.display().to_string();
|
||||
let root = crate::cmd::findfiles::plain(inside.canonicalize().unwrap()).display().to_string();
|
||||
let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned();
|
||||
assert!(e.contains(&format!("root {root}: {name}")), "{e}");
|
||||
}
|
||||
|
||||
/// A prepared export into the folder an export preset keeps, prepared for a client whose read roots
|
||||
/// don't hold that folder and written later outside that client's scope (as on the background
|
||||
/// thread): its reply leaves out the ZIP's path and names the files relative to the folder, and a
|
||||
/// refused write names the folder by its name. A folder inside the read roots, and one the client
|
||||
/// gives, stay whole.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_prepared_export_into_a_presets_folder_outside_the_read_root_leaves_it_out() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("prepared-roots");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap();
|
||||
let prepare = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| {
|
||||
confine(roots.as_ref(), || s.prepare_screen_export("document.exportForScreens", &p)).unwrap()
|
||||
};
|
||||
|
||||
let (r, files) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept"})));
|
||||
assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}");
|
||||
assert!(files.contains_key(&format!("{folder}/1x/Artboard-1.png")), "the files are written into the folder");
|
||||
let (r, _) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true})));
|
||||
assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}");
|
||||
assert!(!r.to_string().contains(&folder), "{r}");
|
||||
// A refused write names the folder by its name.
|
||||
let refused = prepare(&mut s, &write_only, json!({"exportPreset": "Kept"}));
|
||||
let e = refused.write(&mut |path, _| Err(crate::EngineError::Other(format!("{path}: access denied")))).unwrap_err().to_string();
|
||||
assert!(e.contains("kept-out/1x/Artboard-1.png: access denied") && !e.contains(&folder), "{e}");
|
||||
// Inside the read roots, or given by the client: whole.
|
||||
let (r, _) = write_prepared(prepare(&mut s, &both, json!({"exportPreset": "Kept"})));
|
||||
assert_eq!(r["files"], json!([format!("{folder}/1x/Artboard-1.png")]), "{r}");
|
||||
let (r, _) = write_prepared(prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true})));
|
||||
assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}");
|
||||
let given = prepare(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder}));
|
||||
let e = given.write(&mut |path, _| Err(crate::EngineError::Other(format!("{path}: access denied")))).unwrap_err().to_string();
|
||||
assert!(e.contains(&folder), "{e}");
|
||||
}
|
||||
|
||||
/// [`Session::screen_export_folder`]: the client's folder, else the one the export preset keeps,
|
||||
/// with its own name when the request's read roots don't hold it; none without a folder, for an
|
||||
/// unknown preset or for `assets.export`, which takes no preset.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_export_folder_is_the_clients_else_the_presets() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("export-folder");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
let ask = |id: &str, p: Value| confine(confined.as_ref(), || s.screen_export_folder(id, &p));
|
||||
|
||||
let screens = "document.exportForScreens";
|
||||
assert_eq!(ask(screens, json!({"exportPreset": "Kept"})), Some((folder.clone(), Some("kept-out".to_string()))));
|
||||
assert_eq!(ask(screens, json!({"exportPreset": "Kept", "folder": "/x/y"})), Some(("/x/y".to_string(), None)));
|
||||
assert_eq!(ask(screens, json!({"exportPreset": "Kept", "folder": ""})), None);
|
||||
assert_eq!(ask(screens, json!({"exportPreset": "Nope"})), None);
|
||||
assert_eq!(ask(screens, json!({})), None);
|
||||
assert_eq!(ask("assets.export", json!({"exportPreset": "Kept"})), None);
|
||||
assert_eq!(s.screen_export_folder(screens, &json!({"exportPreset": "Kept"})), Some((folder, None)), "unconfined: whole");
|
||||
}
|
||||
|
||||
/// The export settings the document keeps and the saved presets, read by a client whose read roots
|
||||
/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and
|
||||
/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest.
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
//! and they lie the same way relative to each other: the group as a whole is moved or scaled.
|
||||
//! With Appearance on, each of those objects must have the same fill and stroke too; with Size,
|
||||
//! the groups the same width and height.
|
||||
//! - Selecting one of the repeated objects with the Selection tool highlights the similar objects
|
||||
//! at once, before Global Edit starts. Here they are the objects Start Global Edit would take
|
||||
//! with the current Global Edit Options ([`similar`]).
|
||||
//! - While Global Edit is on, an edit made to one of the found objects is made to all of them,
|
||||
//! each in proportion to its own size: halving the height of a 100 pt object halves a 20 pt
|
||||
//! match to 10 pt. Stop Global Edit (or Escape) ends it.
|
||||
@@ -780,18 +783,55 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
|
||||
|
||||
/// The outlines of the members of the active document's Global Edit that are not selected, hold
|
||||
/// no selected object and sit inside no selected object, in their layer's colour: the canvas
|
||||
/// highlights them while Global Edit is on.
|
||||
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
|
||||
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
|
||||
/// ([`similar`]).
|
||||
pub fn highlights(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let Some(ge) = &st.global_edit else { return vec![] };
|
||||
let Some(ge) = &st.global_edit else { return similar(s) };
|
||||
if let Some((rev, out)) = &*ge.outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = outlines(st, &ge.members);
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
pub fn similar(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
return vec![];
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
&& opts == o
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
};
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// The outlines of `members` that are not selected, hold no selected object and sit inside no
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let out: Vec<_> = ge
|
||||
.members
|
||||
members
|
||||
.iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
|
||||
@@ -804,9 +844,7 @@ pub fn highlights(s: &Session) -> Outlines {
|
||||
};
|
||||
Some((path, st.doc.layer_color(*id)))
|
||||
})
|
||||
.collect();
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The Gradient panel and the Gradient tool: in-place gradient edits and the gradient vector.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_color::gradient::MAX_REPEATS;
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
|
||||
use vectorcraft_doc::appearance::stroke_paint_bounds;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, StrokeGradientMode};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
@@ -23,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), 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 (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",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -129,6 +130,36 @@ fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `spread` param of `p`, if given: what the gradient paints past the ends of its stops.
|
||||
fn spread_param(p: &Value) -> Parsed<Option<GradientSpread>> {
|
||||
match p.get("spread") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_str().and_then(GradientSpread::parse).map(Some).ok_or_else(|| "`spread` must be pad, repeat or reflect".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `repeats` param of `p`, if given: how many times the stops run along the vector with
|
||||
/// Repeat and Reflect, a whole number from 1 to [`MAX_REPEATS`].
|
||||
fn repeats_param(p: &Value) -> Parsed<Option<u32>> {
|
||||
match p.get("repeats") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_REPEATS)).contains(n))
|
||||
.map(|n| Some(n as u32))
|
||||
.ok_or_else(|| format!("`repeats` must be a whole number from 1 to {MAX_REPEATS}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// An error when `p` gives a spread other than pad for a gradient of `kind` that has no ends to
|
||||
/// spread past (freeform).
|
||||
fn spread_for(kind: GradientKind, p: &Value) -> Parsed<()> {
|
||||
match spread_param(p)? {
|
||||
Some(s) if !s.is_pad() && kind == GradientKind::Freeform => Err("`spread` applies to linear, radial, conic and diamond gradients".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` (params holding `stops`) with each stop that names a `swatch` resolved through `d`
|
||||
/// ([`swatch_solid`]): a global or spot colour or a tint swatch gives the stop its colour, link and
|
||||
/// tint, a process colour just its colour. A stop linked to a swatch that no longer exists keeps
|
||||
@@ -271,6 +302,9 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
Some(v) => v.as_bool().ok_or("`dither` must be true or false")?,
|
||||
};
|
||||
gp.gradient.method = method_param(g)?.unwrap_or_default();
|
||||
spread_for(kind, g)?;
|
||||
gp.gradient.spread = spread_param(g)?.unwrap_or_default();
|
||||
gp.gradient.repeats = repeats_param(g)?.unwrap_or(1);
|
||||
gp.angle = f64_or(g, "angle", 0.0);
|
||||
gp.swatch = str_param(g, "swatch").map(str::to_string);
|
||||
let geom = GeomEdit::parse(g)?;
|
||||
@@ -422,6 +456,13 @@ fn apply_gradient_edit_in_model(
|
||||
if let Some(m) = method_param(p)? {
|
||||
gp.gradient.method = m;
|
||||
}
|
||||
spread_for(gp.gradient.kind, p)?;
|
||||
if let Some(sp) = spread_param(p)? {
|
||||
gp.gradient.spread = sp;
|
||||
}
|
||||
if let Some(n) = repeats_param(p)? {
|
||||
gp.gradient.repeats = n;
|
||||
}
|
||||
// Angle and aspect edits keep the focal point in its place in the extent ellipse.
|
||||
let before = gp.geom;
|
||||
if let Some(a) = p.get("angle").and_then(Value::as_f64) {
|
||||
@@ -516,6 +557,18 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(p),
|
||||
};
|
||||
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
|
||||
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
|
||||
let for_default = match for_default {
|
||||
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
|
||||
let mut q = q.into_owned();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("spread");
|
||||
}
|
||||
std::borrow::Cow::Owned(q)
|
||||
}
|
||||
q => q,
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! The built-in presets are the gradient swatches of the built-in swatch libraries
|
||||
//! ([`vectorcraft_color::libraries`]: the app's own computed palettes), each listed under its
|
||||
//! library's name. Saved presets are kept with the preferences ([`crate::Prefs::gradient_presets`]),
|
||||
//! so every document has them. A preset is the colour ramp (type, stops, method, dither), not a
|
||||
//! so every document has them. A preset is the color ramp (type, stops, method, dither, spread), not a
|
||||
//! placement: applying one edits the gradient in place, as `paint.editGradient` does.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique",
|
||||
"{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?, spread?, repeats?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops and method, and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method and dither (stops linked to a swatch keep their colour, unlinked) → {name}",
|
||||
"{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method, dither, spread and repeats (stops linked to a swatch keep their colour, unlinked) → {name}",
|
||||
can_save,
|
||||
save
|
||||
),
|
||||
@@ -90,12 +90,13 @@ fn builtin_presets() -> impl Iterator<Item = GradientPresetEntry> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Do `a` and `b` have the same colour ramp (type, method, dither and stops), swatch links aside?
|
||||
/// Do `a` and `b` have the same color ramp (type, method, dither, spread as it paints and stops),
|
||||
/// swatch links aside?
|
||||
fn same_ramp(a: &Gradient, b: &Gradient) -> bool {
|
||||
let stop = |x: &vectorcraft_color::GradientStop, y: &vectorcraft_color::GradientStop| {
|
||||
(x.offset, x.color, x.opacity, x.midpoint) == (y.offset, y.color, y.opacity, y.midpoint)
|
||||
};
|
||||
(a.kind, a.method, a.dither) == (b.kind, b.method, b.dither)
|
||||
(a.kind, a.method, a.dither, a.painted_spread()) == (b.kind, b.method, b.dither, b.painted_spread())
|
||||
&& a.stops.len() == b.stops.len()
|
||||
&& a.stops.iter().zip(&b.stops).all(|(x, y)| stop(x, y))
|
||||
}
|
||||
@@ -215,6 +216,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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()));
|
||||
// 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()));
|
||||
o.insert("repeats".into(), json!(g.repeat_count()));
|
||||
}
|
||||
// Dither is a fill's (paint.editGradient refuses it on a stroke).
|
||||
if !stroke {
|
||||
o.insert("dither".into(), json!(g.dither));
|
||||
|
||||
@@ -436,7 +436,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
|
||||
continue;
|
||||
};
|
||||
let preview = d.images.get(&key).map(|b| b.bytes.clone());
|
||||
// A file read as it is keeps its own type; one turned upright (EXIF orientation) is the PNG it became.
|
||||
// A file read as it is keeps its own type; one turned upright by its orientation is the PNG, or CMYK TIFF, it became.
|
||||
let mime = match fileio::format_for_name(g.link.name()) {
|
||||
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
|
||||
_ => img.blob.mime.clone(),
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
//! from the tool's options (Objects on Path Tool Options). `object.objectsOnPath.options` sets the
|
||||
//! group's Pivot, Rotate and Space (the distance between the objects along the path, and where the
|
||||
//! first one attaches), and `object.objectsOnPath.expand` makes it a plain group.
|
||||
//! `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.
|
||||
//!
|
||||
//! 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,
|
||||
@@ -19,7 +23,7 @@
|
||||
//! 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).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -28,7 +32,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, check_numbers, checked_id, checked_ids_param, cmd, has_selection};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, check_numbers, checked_id, checked_ids_param, cmd, has_doc, has_selection};
|
||||
|
||||
/// The id of the Objects on Path tool.
|
||||
pub const TOOL: &str = "objectsOnPath";
|
||||
@@ -53,6 +57,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_objects_on_path,
|
||||
options
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.selectMember",
|
||||
"Select Object on Path",
|
||||
[],
|
||||
None,
|
||||
"{member: id of an object of an Objects on Path group} select the group alone with that object chosen, as a click on the object's Select/Move widget does; any other selection change clears the choice → {group, member}",
|
||||
has_doc,
|
||||
select_member
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.moveMember",
|
||||
"Move Object on Path",
|
||||
[],
|
||||
None,
|
||||
"{member: id of an object of an Objects on Path group, target: id of another object of the same group, group?: the group's id (when given, it must be the group of both); neither object nor the group may be hidden or locked} move the object to the target's place along the path; the objects between them each move one place toward where it was, except hidden and locked objects, which keep their places. Only the order along the path changes: Space, the start, Pivot, Rotate and the order in the Layers panel stay. A target that is the object itself changes nothing → {group, member, index}",
|
||||
has_doc,
|
||||
move_member
|
||||
),
|
||||
cmd!(
|
||||
"object.objectsOnPath.expand",
|
||||
"Expand",
|
||||
@@ -296,6 +318,71 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": groups.iter().map(|g| g.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
// ---------- Select/Move ----------
|
||||
|
||||
/// The Objects on Path group whose object `key` of `p` names, checked: an object listed in the
|
||||
/// group's record (not its path), in a group that is not hidden or locked.
|
||||
fn member_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<(NodeId, NodeId)> {
|
||||
let v = p.get(key).filter(|v| !v.is_null()).ok_or_else(|| bad(cmd, format!("missing `{key}`")))?;
|
||||
let id = checked_id(s, v, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let not_on_path = || bad(cmd, format!("`{key}` must name an object attached to the path of an Objects on Path group"));
|
||||
let g =
|
||||
d.ancestry(id).unwrap_or_default().into_iter().rev().nth(1).filter(|g| d.node(*g).is_some_and(is_objects_on_path)).ok_or_else(not_on_path)?;
|
||||
let listed = d.node(g).and_then(|n| n.extras().objects_on_path.as_deref()).is_some_and(|rec| rec.members.iter().any(|m| m.id == id));
|
||||
if !listed {
|
||||
return Err(not_on_path());
|
||||
}
|
||||
if !d.is_editable(g) {
|
||||
return Err(bad(cmd, "the Objects on Path group is hidden or locked"));
|
||||
}
|
||||
if !d.is_editable(id) {
|
||||
return Err(bad(cmd, format!("`{key}` names an object that is hidden or locked")));
|
||||
}
|
||||
Ok((g, id))
|
||||
}
|
||||
|
||||
fn select_member(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (g, member) = member_param(s, p, "member", "object.objectsOnPath.selectMember")?;
|
||||
s.select(|_, sel| sel.set_on_path_member(g, member))?;
|
||||
Ok(json!({ "group": g.0, "member": member.0 }))
|
||||
}
|
||||
|
||||
fn move_member(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.objectsOnPath.moveMember";
|
||||
let (g, member) = member_param(s, p, "member", C)?;
|
||||
let (target_group, target) = member_param(s, p, "target", C)?;
|
||||
if target_group != g {
|
||||
return Err(bad(C, "`target` must be an object of the same Objects on Path group as `member`"));
|
||||
}
|
||||
if let Some(v) = p.get("group").filter(|v| !v.is_null())
|
||||
&& checked_id(s, v, C)? != g
|
||||
{
|
||||
return Err(bad(C, "`group` must be the Objects on Path group of `member` and `target`"));
|
||||
}
|
||||
let at = |s: &Session| -> Result<usize> {
|
||||
let rec = s.doc()?.doc.node(g).and_then(|n| n.extras().objects_on_path.as_deref().cloned()).ok_or(EngineError::NoNode(g))?;
|
||||
rec.members.iter().position(|m| m.id == member).ok_or(EngineError::NoNode(member))
|
||||
};
|
||||
// Onto its own place: nothing changes, and no undo step is recorded.
|
||||
if target == member {
|
||||
return Ok(json!({ "group": g.0, "member": member.0, "index": at(s)? }));
|
||||
}
|
||||
// Hidden and locked objects between them keep their places.
|
||||
let index = s.edit("Move Object on Path", |d, _| {
|
||||
let mut rec = d.node(g).and_then(|n| n.extras().objects_on_path.as_deref().cloned()).ok_or(EngineError::NoNode(g))?;
|
||||
let fixed: HashSet<NodeId> = {
|
||||
let editable = d.editable();
|
||||
rec.members.iter().map(|m| m.id).filter(|&id| !editable(id)).collect()
|
||||
};
|
||||
let index = rec.move_member(member, target, |id| fixed.contains(&id)).ok_or(EngineError::NoNode(member))?;
|
||||
let n = d.node_mut(g).ok_or(EngineError::NoNode(g))?;
|
||||
n.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
Ok(index)
|
||||
})?;
|
||||
Ok(json!({ "group": g.0, "member": member.0, "index": index }))
|
||||
}
|
||||
|
||||
// ---------- Expand ----------
|
||||
|
||||
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -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), 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); 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 (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); 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)
|
||||
),
|
||||
|
||||
@@ -26,6 +26,7 @@ pub struct BuiltinPatternLibrary {
|
||||
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[
|
||||
BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns },
|
||||
BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures },
|
||||
BuiltinPatternLibrary { id: "optical-effects", name: "Optical Effects", make: optical_effects },
|
||||
];
|
||||
|
||||
/// The library category of the built-in pattern libraries.
|
||||
@@ -256,6 +257,162 @@ fn grit_textures(d: &mut Document) {
|
||||
});
|
||||
}
|
||||
|
||||
/// `n` + 1 points of the curve `(t, f(t))` for `t` from `t0` to `t1`, evenly spaced.
|
||||
fn curve(t0: f64, t1: f64, n: u32, f: impl Fn(f64) -> f64) -> Vec<(f64, f64)> {
|
||||
(0..=n)
|
||||
.map(|i| {
|
||||
let t = t0 + (t1 - t0) * f64::from(i) / f64::from(n);
|
||||
(t, f(t))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The closed band between two curves drawn from the same side to the same side: `upper` forward,
|
||||
/// then `lower` back.
|
||||
fn band(upper: &[(f64, f64)], lower: &[(f64, f64)]) -> PathData {
|
||||
let points: Vec<(f64, f64)> = upper.iter().chain(lower.iter().rev()).copied().collect();
|
||||
polygon(&points)
|
||||
}
|
||||
|
||||
/// 72 corners of the circle of radius `r` about (`cx`, `cy`), turning the other way with `reverse`.
|
||||
fn circle(cx: f64, cy: f64, r: f64, reverse: bool) -> SubPath {
|
||||
const CORNERS: u32 = 72;
|
||||
let turn = if reverse { -std::f64::consts::TAU } else { std::f64::consts::TAU };
|
||||
let points: Vec<Point> = (0..CORNERS)
|
||||
.map(|i| {
|
||||
let a = turn * f64::from(i) / f64::from(CORNERS);
|
||||
Point::new(cx + r * a.cos(), cy + r * a.sin())
|
||||
})
|
||||
.collect();
|
||||
SubPath::polyline(&points, true)
|
||||
}
|
||||
|
||||
/// The ring from radius `inner` to `outer` about (`cx`, `cy`): the outer circle and the inner one
|
||||
/// turning the other way, so the middle stays clear under either fill rule. An `inner` of 0 gives
|
||||
/// a disk.
|
||||
fn ring(cx: f64, cy: f64, inner: f64, outer: f64) -> PathData {
|
||||
let mut subpaths = vec![circle(cx, cy, outer, false)];
|
||||
if inner > 0.0 {
|
||||
subpaths.push(circle(cx, cy, inner, true));
|
||||
}
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// A lens `2 × l` long and `2 × h` high about (`cx`, `cy`), lying along x: two half sine waves that
|
||||
/// meet at its tips, turning the other way with `reverse`.
|
||||
fn lens(cx: f64, cy: f64, l: f64, h: f64, reverse: bool) -> SubPath {
|
||||
const STEPS: u32 = 32;
|
||||
let at = |i: u32, side: f64| {
|
||||
let t = f64::from(i) / f64::from(STEPS);
|
||||
Point::new(cx - l + 2.0 * l * t, cy + side * h * (std::f64::consts::PI * t).sin())
|
||||
};
|
||||
let mut points: Vec<Point> = (0..=STEPS).map(|i| at(i, -1.0)).chain((1..STEPS).rev().map(|i| at(i, 1.0))).collect();
|
||||
if reverse {
|
||||
points.reverse();
|
||||
}
|
||||
SubPath::polyline(&points, true)
|
||||
}
|
||||
|
||||
/// Optical Effects: black waves, rings, warped checks, pinched stripes, chevrons and lenses on a
|
||||
/// clear background. Each tile is one period of its design, so a band that leaves one edge comes
|
||||
/// back at the same place on the opposite edge. Art that reaches past an edge is kept whole: the
|
||||
/// tiling draws the part outside the tile on the next tile.
|
||||
fn optical_effects(d: &mut Document) {
|
||||
use std::f64::consts::TAU;
|
||||
// Three bands 5 pt wide, 12 pt apart, each one sine wave across the tile.
|
||||
let bands = (0..3u32)
|
||||
.map(|k| {
|
||||
let mid = move |x: f64| 6.0 + 12.0 * f64::from(k) + 3.0 * (TAU * x / 36.0).sin();
|
||||
band(&curve(0.0, 36.0, 48, |x| mid(x) - 2.5), &curve(0.0, 36.0, 48, |x| mid(x) + 2.5))
|
||||
})
|
||||
.collect();
|
||||
add(d, "Sine Bands", 36.0, 36.0, TileType::Grid, bands);
|
||||
// Nine thin waves 4 pt apart, two waves across the tile, each a ninth of a wave on from the one
|
||||
// above it, so the ninth leads into the first wave of the next tile down.
|
||||
let lines = (0..9u32)
|
||||
.map(|k| {
|
||||
let (y, phase) = (2.0 + 4.0 * f64::from(k), TAU * f64::from(k) / 9.0);
|
||||
let mid = move |x: f64| y + 2.5 * (TAU * x / 18.0 + phase).sin();
|
||||
band(&curve(0.0, 36.0, 72, |x| mid(x) - 0.6), &curve(0.0, 36.0, 72, |x| mid(x) + 0.6))
|
||||
})
|
||||
.collect();
|
||||
add(d, "Ripple Lines", 36.0, 36.0, TileType::Grid, lines);
|
||||
// Thin rings 3 pt apart about the center and rings 3.3 pt apart about a point 4 pt to its
|
||||
// right. The two sets cross, and the outer rings reach into the next tile across.
|
||||
let rings = (1..=7u32)
|
||||
.map(|k| (24.0, 3.0 * f64::from(k)))
|
||||
.chain((1..=7u32).map(|k| (28.0, 3.3 * f64::from(k))))
|
||||
.map(|(cx, r)| ring(cx, 24.0, r - 0.6, r + 0.6))
|
||||
.collect();
|
||||
add(d, "Interference Rings", 48.0, 48.0, TileType::Grid, rings);
|
||||
// Rings 2 pt and 1 pt wide by turns about the tile's corner and about its center, the center's
|
||||
// starting with the narrower one. The corner's rings are the same rings at all four corners.
|
||||
let mut rings = vec![];
|
||||
for (c, first) in [(0.0, 0), (20.0, 1)] {
|
||||
let mut r = 0.0;
|
||||
for k in 0..5 {
|
||||
let width = if (k + first) % 2 == 0 { 2.0 } else { 1.0 };
|
||||
rings.push(ring(c, c, r, r + width));
|
||||
r += width + 1.2;
|
||||
}
|
||||
}
|
||||
add(d, "Offset Rings", 40.0, 40.0, TileType::Grid, rings);
|
||||
// An 8 × 8 checkerboard of 4 pt cells whose columns are bent by a sine wave down the tile and
|
||||
// whose rows by one across it, each edge drawn through five points.
|
||||
let warp = |x: f64, y: f64| (x + 2.0 * (TAU * y / 32.0).sin(), y + 2.0 * (TAU * x / 32.0).sin());
|
||||
let cells = (0..8u32)
|
||||
.flat_map(|row| (0..8u32).map(move |col| (col, row)))
|
||||
.filter(|(col, row)| (col + row) % 2 == 0)
|
||||
.map(|(col, row)| {
|
||||
let (x, y) = (4.0 * f64::from(col), 4.0 * f64::from(row));
|
||||
let corners = [(x, y), (x + 4.0, y), (x + 4.0, y + 4.0), (x, y + 4.0), (x, y)];
|
||||
let points: Vec<(f64, f64)> = corners
|
||||
.windows(2)
|
||||
.flat_map(|e| {
|
||||
let (a, b) = (e[0], e[1]);
|
||||
(0..4u32).map(move |i| {
|
||||
let t = f64::from(i) / 4.0;
|
||||
warp(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
polygon(&points)
|
||||
})
|
||||
.collect();
|
||||
add(d, "Warped Checks", 32.0, 32.0, TileType::Grid, cells);
|
||||
// Six upright stripes 6 pt apart that widen from 0.8 pt to 5.6 pt and narrow again down the tile,
|
||||
// each a sixth of a wave on from the one to its left.
|
||||
let stripes = (0..6u32)
|
||||
.map(|k| {
|
||||
let (x, phase) = (3.0 + 6.0 * f64::from(k), TAU * f64::from(k) / 6.0);
|
||||
let half = move |y: f64| 1.6 + 1.2 * (TAU * y / 36.0 + phase).cos();
|
||||
let side = |s: f64| -> Vec<(f64, f64)> { curve(0.0, 36.0, 48, |y| x + s * half(y)).into_iter().map(|(y, at)| (at, y)).collect() };
|
||||
band(&side(-1.0), &side(1.0))
|
||||
})
|
||||
.collect();
|
||||
add(d, "Pinched Stripes", 36.0, 36.0, TileType::Grid, stripes);
|
||||
// Four zigzag bands 8 pt apart, two zigzags across the tile; the bend and the width of the bands
|
||||
// rise and fall from band to band.
|
||||
let chevrons = [(0.0, 3.0, 4.0), (8.0, 4.5, 2.5), (16.0, 3.0, 1.0), (24.0, 1.5, 2.5)]
|
||||
.into_iter()
|
||||
.map(|(y, bend, width)| {
|
||||
let upper: Vec<(f64, f64)> = (0..=4u32).map(|i| (8.0 * f64::from(i), if i % 2 == 1 { y + bend } else { y })).collect();
|
||||
let lower: Vec<(f64, f64)> = upper.iter().map(|&(x, y)| (x, y + width)).collect();
|
||||
band(&upper, &lower)
|
||||
})
|
||||
.collect();
|
||||
add(d, "Chevron Pulse", 32.0, 32.0, TileType::Grid, chevrons);
|
||||
// Five nested lens outlines 1.5 pt wide about the center, 14 pt to 78 pt long. The longer ones
|
||||
// reach across the side edges and cross the next tiles' lenses.
|
||||
let lenses = (0..5u32)
|
||||
.map(|k| {
|
||||
let (l, h) = (7.0 + 8.0 * f64::from(k), 4.0 + 4.0 * f64::from(k));
|
||||
PathData::new(vec![lens(24.0, 24.0, l, h, false), lens(24.0, 24.0, l - 1.5, h - 1.5, true)])
|
||||
})
|
||||
.collect();
|
||||
add(d, "Radiating Lenses", 48.0, 48.0, TileType::Grid, lenses);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -326,4 +483,101 @@ mod tests {
|
||||
}
|
||||
assert!(crossing > 0, "no mark reaches past an edge");
|
||||
}
|
||||
|
||||
const OPTICAL: [&str; 8] =
|
||||
["Sine Bands", "Ripple Lines", "Interference Rings", "Offset Rings", "Warped Checks", "Pinched Stripes", "Chevron Pulse", "Radiating Lenses"];
|
||||
|
||||
fn optical_doc() -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
optical_effects(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
/// The paths of pattern `p`'s art, each with its fill rule.
|
||||
fn paths(p: &PatternDef) -> Vec<(&PathData, vectorcraft_geom::FillRule)> {
|
||||
p.art
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { path, rule, .. } => (path, *rule),
|
||||
_ => panic!("{}: art that is not a path", p.name),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optical_effects_is_a_pattern_library_of_eight_bounded_tiles() {
|
||||
let b = PATTERN_LIBRARIES.iter().find(|b| b.id == "optical-effects").expect("Optical Effects is listed");
|
||||
assert_eq!(b.name, "Optical Effects");
|
||||
let names: Vec<String> = library_doc(b.id).unwrap().patterns.iter().map(|p| p.name.clone()).collect();
|
||||
assert_eq!(names, OPTICAL);
|
||||
// Made twice, the art is the same.
|
||||
let (a, again) = (optical_doc(), optical_doc());
|
||||
assert_eq!(a.patterns, again.patterns);
|
||||
for p in &a.patterns {
|
||||
let (w, h) = (p.width(), p.height());
|
||||
assert!((32.0..=48.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name);
|
||||
assert_eq!(p.tile_type, TileType::Grid, "{}", p.name);
|
||||
let paths = paths(p);
|
||||
let segments: usize = paths.iter().flat_map(|(path, _)| &path.subpaths).map(SubPath::segment_count).sum();
|
||||
assert!(!paths.is_empty() && paths.len() <= 600 && segments <= 20_000, "{}: {} paths, {segments} segments", p.name, paths.len());
|
||||
for (path, _) in &paths {
|
||||
let b = path.bounds().unwrap_or_else(|| panic!("{}: an empty path", p.name));
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name);
|
||||
assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Just either side of a tile's right and bottom edges, the tiling paints the same points: a band
|
||||
/// cut off at an edge, or one that comes back at another height or width, paints one side only.
|
||||
/// No path is another moved by a whole tile, which the tiling would draw twice in one place.
|
||||
#[test]
|
||||
fn optical_tiles_join_without_a_seam() {
|
||||
const SAMPLES: u32 = 400;
|
||||
const STEP: f64 = 1e-4;
|
||||
for p in &optical_doc().patterns {
|
||||
let (w, h) = (p.width(), p.height());
|
||||
let shapes: Vec<(BezPathFill, Rect)> =
|
||||
paths(p).into_iter().map(|(path, rule)| ((path.to_bezpath(), rule), path.bounds().unwrap_or(Rect::ZERO))).collect();
|
||||
let paints = |q: Point| {
|
||||
let near = Rect::new(q.x - STEP, q.y - STEP, q.x + STEP, q.y + STEP);
|
||||
p.offsets_covering(near).into_iter().any(|o| {
|
||||
let at = q - o;
|
||||
shapes.iter().any(|((bp, rule), b)| {
|
||||
let inside = b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1;
|
||||
let turns = if inside { kurbo::Shape::winding(bp, at) } else { 0 };
|
||||
match rule {
|
||||
vectorcraft_geom::FillRule::EvenOdd => turns % 2 != 0,
|
||||
vectorcraft_geom::FillRule::NonZero => turns != 0,
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
let (mut differ, mut painted) = (0, 0);
|
||||
for i in 0..SAMPLES {
|
||||
let t = (f64::from(i) + 0.37) / f64::from(SAMPLES);
|
||||
let (right, bottom) = (Point::new(w, t * h), Point::new(t * w, h));
|
||||
let (dx, dy) = (kurbo::Vec2::new(STEP, 0.0), kurbo::Vec2::new(0.0, STEP));
|
||||
for (a, b) in [(right - dx, right + dx), (bottom - dy, bottom + dy)] {
|
||||
let (pa, pb) = (paints(a), paints(b));
|
||||
differ += usize::from(pa != pb);
|
||||
painted += usize::from(pa);
|
||||
}
|
||||
}
|
||||
assert!(differ <= 2, "{}: {differ} of {} points across the edges differ", p.name, 2 * SAMPLES);
|
||||
assert!(painted > 0, "{}: nothing crosses an edge", p.name);
|
||||
let bounds: Vec<Rect> = shapes.iter().map(|(_, b)| *b).collect();
|
||||
let same = |a: &Rect, b: Rect| {
|
||||
(a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9
|
||||
};
|
||||
for b in &bounds {
|
||||
for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] {
|
||||
let moved = *b + kurbo::Vec2::new(dx, dy);
|
||||
assert!(!bounds.iter().any(|o| same(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type BezPathFill = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
|
||||
}
|
||||
@@ -62,13 +62,28 @@ fn err(e: vectorcraft_plugins::Error) -> EngineError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Under automation read roots, a reply names a file or folder outside them by its name alone.
|
||||
fn shown_file(path: &str) -> String {
|
||||
super::fileio::shown_path(path).into_owned()
|
||||
}
|
||||
|
||||
/// A plug-in turned off for the next launch, or the one a launch stopped at, as a reply shows it: a
|
||||
/// file outside the automation read roots is named by its file name.
|
||||
fn shown_item(item: &safe_mode::Item) -> Value {
|
||||
let mut v = item.to_json();
|
||||
if let Some(file) = item.file.as_deref() {
|
||||
v["file"] = json!(shown_file(file));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// JSON description of an installed plug-in.
|
||||
pub fn describe(p: &Plugin) -> Value {
|
||||
let m = p.manifest();
|
||||
let mut v = json!({
|
||||
"id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description,
|
||||
"params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()),
|
||||
"size": p.size(), "source": p.source(),
|
||||
"size": p.size(), "source": p.source().map(shown_file),
|
||||
"permissions": permissions::names(&m.permissions()), "hash": p.hash(), "api": m.api,
|
||||
});
|
||||
match m.kind {
|
||||
@@ -932,9 +947,46 @@ fn describe_installed(p: &Plugin) -> Value {
|
||||
v
|
||||
}
|
||||
|
||||
/// The folder load `report` as a reply shows it: under automation read roots, a folder outside them
|
||||
/// is `null` and a failed file outside them is named by its file name, in the errors too.
|
||||
fn shown_report(mut report: Value) -> Value {
|
||||
let mut hidden: Vec<(String, String)> = vec![];
|
||||
if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) {
|
||||
for row in failed {
|
||||
let Some(file) = row.get("file").and_then(Value::as_str).map(str::to_string) else { continue };
|
||||
let shown = shown_file(&file);
|
||||
if shown != file {
|
||||
row["file"] = json!(shown);
|
||||
hidden.push((file, shown));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(folder) = report.get("folder").and_then(Value::as_str).map(str::to_string) {
|
||||
let shown = shown_file(&folder);
|
||||
if shown != folder {
|
||||
report["folder"] = Value::Null;
|
||||
hidden.push((folder, shown));
|
||||
}
|
||||
}
|
||||
// A failed file's path holds its folder's: the longer paths are put back first.
|
||||
hidden.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
|
||||
let unnamed = |text: &str| hidden.iter().fold(text.to_string(), |t, (path, name)| t.replace(path.as_str(), name));
|
||||
if let Some(e) = report.get("error").and_then(Value::as_str).map(unnamed) {
|
||||
report["error"] = json!(e);
|
||||
}
|
||||
if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) {
|
||||
for row in failed {
|
||||
if let Some(e) = row.get("error").and_then(Value::as_str).map(unnamed) {
|
||||
row["error"] = json!(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| r.clone());
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect();
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
|
||||
Ok(
|
||||
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
|
||||
)
|
||||
@@ -946,11 +998,33 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"active": safe_mode::active(),
|
||||
"source": safe_mode::source().map(safe_mode::Source::name),
|
||||
"disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>(),
|
||||
"pendingItem": safe_mode::previous().map(|i| i.to_json()),
|
||||
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
|
||||
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name
|
||||
/// by its file name (outside the automation read roots) is found by that name, when no other listed
|
||||
/// file has it.
|
||||
fn listed_file(file: String) -> String {
|
||||
let mut listed: Vec<String> = safe_mode::disabled()
|
||||
.into_iter()
|
||||
.chain(safe_mode::previous())
|
||||
.filter_map(|i| i.file)
|
||||
.chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string)))
|
||||
.collect();
|
||||
listed.sort();
|
||||
listed.dedup();
|
||||
if listed.contains(&file) {
|
||||
return file;
|
||||
}
|
||||
let mut named = listed.into_iter().filter(|f| shown_file(f) == file);
|
||||
match (named.next(), named.next()) {
|
||||
(Some(f), None) => f,
|
||||
_ => file,
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.setEnabled`: turns a plug-in on or off for the next launch, by `id` or by `file` (a
|
||||
/// plug-in that stopped a launch while loading may be known by its file alone). It neither loads
|
||||
/// nor unloads anything now, and uninstalls nothing.
|
||||
@@ -972,7 +1046,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None };
|
||||
(registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored)
|
||||
}
|
||||
(None, Some(file)) => (safe_mode::Item::file(file), None),
|
||||
(None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None),
|
||||
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
|
||||
};
|
||||
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
|
||||
@@ -986,7 +1060,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Without a plug-in folder (a session confined to automation roots), or when the list there
|
||||
// can't take the change, the change stays in this process and goes with the next change that saves.
|
||||
let saved = !changed || s.store_disabled_plugins();
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>()}))
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1055,7 +1129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -1127,7 +1201,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Safe Mode",
|
||||
[],
|
||||
None,
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
always,
|
||||
safe_mode_state
|
||||
),
|
||||
@@ -1136,7 +1210,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Enable on Re-launch",
|
||||
[],
|
||||
None,
|
||||
"{id | file: a plug-in as plugin.safeMode's disabled lists it, enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
|
||||
"{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
|
||||
always,
|
||||
set_enabled
|
||||
),
|
||||
|
||||
@@ -102,7 +102,53 @@ const FILE_WORDS: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Param keys that name a file or a folder.
|
||||
const FILE_KEYS: &[&str] = &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url"];
|
||||
const FILE_KEYS: &[&str] =
|
||||
&["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"];
|
||||
|
||||
/// The keys in [`FILE_KEYS`] that name a folder.
|
||||
const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"];
|
||||
|
||||
/// What a param key that names a place on disk names there.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Location {
|
||||
/// A file (or a list of files).
|
||||
File,
|
||||
/// A folder (or a list of folders).
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// What `key` names on disk when a command takes it ([`FILE_KEYS`]), or `None` when it never
|
||||
/// names a file or a folder.
|
||||
pub fn key_location(key: &str) -> Option<Location> {
|
||||
if FOLDER_KEYS.contains(&key) {
|
||||
Some(Location::Folder)
|
||||
} else if FILE_KEYS.contains(&key) {
|
||||
Some(Location::File)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`]
|
||||
/// names it for `spec` (it names part of the document there).
|
||||
pub fn location_in(spec: &CommandSpec, key: &str) -> Option<Location> {
|
||||
if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) }
|
||||
}
|
||||
|
||||
/// The param keys of `spec` that name a file or a folder, with what they name: the keys in
|
||||
/// [`FILE_KEYS`] that its params description names ([`super::params::doc_keys`]), with those of the
|
||||
/// commands its `…` entries name ([`super::params::takes_key`]), and its schema's params, less those
|
||||
/// [`NOT_FILES`] names for it. Sorted, each key once.
|
||||
pub fn location_keys(spec: &CommandSpec) -> Vec<(&'static str, Location)> {
|
||||
let described = super::params::doc_keys(spec.params).map(|p| p.keys).unwrap_or_default();
|
||||
let in_schema = spec.schema.map(|s| s.params.iter().map(|p| p.name)).into_iter().flatten();
|
||||
let taken = FILE_KEYS.iter().copied().filter(|k| super::params::takes_key(spec.params, k));
|
||||
let mut keys: Vec<(&'static str, Location)> =
|
||||
described.into_iter().chain(in_schema).chain(taken).filter_map(|k| Some((k, location_in(spec, k)?))).collect();
|
||||
keys.sort_unstable_by_key(|(k, _)| *k);
|
||||
keys.dedup();
|
||||
keys
|
||||
}
|
||||
|
||||
/// Commands and the param key in [`FILE_KEYS`] that, in them, names part of the document (a path of
|
||||
/// its art, a setting, an attribute it stores or a result field), not a file.
|
||||
@@ -119,6 +165,8 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[
|
||||
("attributes.set", "url"),
|
||||
("svgInteractivity.info", "files"),
|
||||
("addon.cleanup.rejoin", "paths"),
|
||||
("object.slice.options", "url"),
|
||||
("document.exportForScreens", "folders"),
|
||||
];
|
||||
|
||||
/// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`],
|
||||
@@ -466,7 +514,8 @@ mod tests {
|
||||
}
|
||||
for (id, key) in NOT_FILES {
|
||||
let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") };
|
||||
assert!(names_key(spec.params, key), "{id} has no `{key}` param");
|
||||
let described = crate::cmd::params::doc_keys(spec.params).is_ok_and(|p| p.keys.contains(key));
|
||||
assert!(names_key(spec.params, key) || described, "{id} has no `{key}` param");
|
||||
}
|
||||
let leaks: Vec<&str> = specs
|
||||
.iter()
|
||||
@@ -565,6 +614,40 @@ mod tests {
|
||||
read.unwrap();
|
||||
}
|
||||
|
||||
/// [`location_keys`] names every key in [`FILE_KEYS`] that a command's params description or
|
||||
/// schema names, in every way a description writes one (`path | name`, `folder? (…)`), less
|
||||
/// those [`NOT_FILES`] names for it; folder keys name folders. No command a plug-in may call
|
||||
/// has one.
|
||||
#[test]
|
||||
fn location_keys_come_from_the_command_catalog() {
|
||||
let find = |id: &str| crate::cmd::find_command(id).unwrap_or_else(|| panic!("no command {id}"));
|
||||
let keys = |id: &str| location_keys(find(id));
|
||||
assert!(keys("document.open").contains(&("path", Location::File)), "{:?}", keys("document.open"));
|
||||
assert!(keys("document.compare").contains(&("diffPath", Location::File)), "{:?}", keys("document.compare"));
|
||||
assert!(keys("addon.document.saveTimestampedCopy").contains(&("folder", Location::Folder)));
|
||||
let relink = keys("links.relink");
|
||||
for k in [("path", Location::File), ("paths", Location::File), ("folder", Location::Folder)] {
|
||||
assert!(relink.contains(&k), "{relink:?}");
|
||||
}
|
||||
assert!(keys("action.batch").contains(&("destinationFolder", Location::Folder)));
|
||||
for (id, key) in NOT_FILES {
|
||||
assert!(!keys(id).iter().any(|(k, _)| k == key), "{id} `{key}` names a file");
|
||||
}
|
||||
for spec in crate::cmd::command_specs() {
|
||||
let found = location_keys(spec);
|
||||
let described = crate::cmd::params::doc_keys(spec.params).map(|p| p.keys).unwrap_or_default();
|
||||
let in_schema = spec.schema.map(|s| s.params.iter().map(|p| p.name).collect::<Vec<_>>()).unwrap_or_default();
|
||||
for k in described.into_iter().chain(in_schema).filter(|k| FILE_KEYS.contains(k) && !NOT_FILES.contains(&(spec.id, *k))) {
|
||||
assert!(found.iter().any(|(f, _)| *f == k), "{}: `{k}` is missing from {found:?}", spec.id);
|
||||
}
|
||||
assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id);
|
||||
assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id);
|
||||
}
|
||||
assert_eq!(key_location("url"), Some(Location::File));
|
||||
assert_eq!(key_location("sourceFolder"), Some(Location::Folder));
|
||||
assert_eq!(key_location("pathData"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_are_found_as_whole_keys() {
|
||||
assert!(names_key("{path: a .wasm file}", "path"));
|
||||
|
||||
@@ -307,7 +307,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.nudge",
|
||||
"object.objectsOnPath.attach",
|
||||
"object.objectsOnPath.expand",
|
||||
"object.objectsOnPath.moveMember",
|
||||
"object.objectsOnPath.options",
|
||||
"object.objectsOnPath.selectMember",
|
||||
"object.path.addAnchorPoints",
|
||||
"object.path.cleanUp",
|
||||
"object.path.divideObjectsBelow",
|
||||
|
||||
@@ -97,6 +97,10 @@ pub trait RecoveryStore: Send + Sync {
|
||||
fn remove(&self, name: &str) -> std::result::Result<(), String>;
|
||||
/// Where the entries are, as the user knows it (a folder, "browser storage").
|
||||
fn location(&self) -> String;
|
||||
/// Is [`RecoveryStore::location`] a folder on this computer (default: no)?
|
||||
fn in_folder(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// The areas in the store (default: those with entries).
|
||||
fn areas(&self) -> std::result::Result<Vec<String>, String> {
|
||||
let names = self.list()?;
|
||||
@@ -477,6 +481,9 @@ impl RecoveryStore for FolderStore {
|
||||
fn location(&self) -> String {
|
||||
self.0.to_string_lossy().into_owned()
|
||||
}
|
||||
fn in_folder(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn areas(&self) -> std::result::Result<Vec<String>, String> {
|
||||
Self::names(&self.0, true)
|
||||
}
|
||||
@@ -938,6 +945,21 @@ fn sweep(store: &dyn RecoveryStore, area: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's file `path` as a reply names it: under automation read roots, only inside them.
|
||||
fn shown_path(path: Option<String>) -> Option<String> {
|
||||
path.filter(|p| crate::file_access::check_read(p).is_ok())
|
||||
}
|
||||
|
||||
/// Where `store` keeps its copies, as a reply names it: a recovery folder outside the automation
|
||||
/// read roots is `null`.
|
||||
fn shown_location(store: &dyn RecoveryStore) -> Value {
|
||||
let location = store.location();
|
||||
if store.in_folder() && crate::file_access::check_read(&location).is_err() {
|
||||
return Value::Null;
|
||||
}
|
||||
json!(location)
|
||||
}
|
||||
|
||||
fn read_meta(store: &dyn RecoveryStore, file: &str) -> Meta {
|
||||
store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
|
||||
}
|
||||
@@ -1235,7 +1257,7 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
forget_clean(s);
|
||||
heartbeat(s);
|
||||
Ok(json!({ "saved": saved, "skipped": skipped, "location": store.location() }))
|
||||
Ok(json!({ "saved": saved, "skipped": skipped, "location": shown_location(store.as_ref()) }))
|
||||
}
|
||||
|
||||
/// Who an area of the store belongs to.
|
||||
@@ -1361,7 +1383,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let meta = read_meta(store.as_ref(), f);
|
||||
let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title };
|
||||
rows.push(json!({
|
||||
"file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved,
|
||||
"file": f, "title": title, "path": shown_path(meta.path), "format": meta.format, "saved": meta.saved,
|
||||
"open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running,
|
||||
}));
|
||||
}
|
||||
@@ -1370,7 +1392,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
tidy(store.as_ref(), &area, hold);
|
||||
}
|
||||
}
|
||||
Ok(json!({ "copies": rows, "location": store.location() }))
|
||||
Ok(json!({ "copies": rows, "location": shown_location(store.as_ref()) }))
|
||||
}
|
||||
|
||||
/// A gone app's area to act on: its name, the copies to act on, and its lock.
|
||||
@@ -1483,7 +1505,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
|
||||
// The copy stays until the document is saved or closed.
|
||||
st.recovery = Some(RecoveryCopy { file: mine.clone(), doc: st.doc.clone() });
|
||||
let title = st.title();
|
||||
Ok(super::fileio::merge(json!({ "index": index, "title": title, "file": mine, "path": meta.path, "warnings": warnings }), links.to_json()))
|
||||
Ok(super::fileio::merge(
|
||||
json!({ "index": index, "title": title, "file": mine, "path": shown_path(meta.path), "warnings": warnings }),
|
||||
links.to_json(),
|
||||
))
|
||||
}
|
||||
|
||||
fn restore(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1527,7 +1552,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Recovery Data",
|
||||
[],
|
||||
None,
|
||||
"{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web)",
|
||||
"{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web; null under automation read roots when the folder is outside them)",
|
||||
has_store,
|
||||
save
|
||||
),
|
||||
@@ -1536,7 +1561,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recovery Data",
|
||||
[],
|
||||
None,
|
||||
"{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash",
|
||||
"{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash; under automation read roots, path is null when the document's file is outside them, and location when the recovery folder is",
|
||||
has_store,
|
||||
list
|
||||
),
|
||||
@@ -1545,7 +1570,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Restore Recovered Documents",
|
||||
[],
|
||||
None,
|
||||
"{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}. The copy moves to this app's area and stays until the document is saved or closed",
|
||||
"{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}; under automation read roots, path is null when the original file is outside them. The copy moves to this app's area and stays until the document is saved or closed",
|
||||
has_store,
|
||||
restore
|
||||
),
|
||||
|
||||
@@ -233,6 +233,43 @@ impl Session {
|
||||
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// The last run's report ([`Session::script_report`]) as a reply shows it: under automation read
|
||||
/// roots, a file the run wrote outside them (`written`) and the file a failed run stopped in
|
||||
/// (`file`, also in the run's error line in `console`) are named by their file name. What the
|
||||
/// script wrote itself (`log`, its output lines) stays as written.
|
||||
pub fn shown_script_report(&self) -> Option<Value> {
|
||||
let mut report = self.script_report()?.clone();
|
||||
if let Some(written) = report.get_mut("written").and_then(Value::as_array_mut) {
|
||||
for path in written.iter_mut() {
|
||||
if let Some(name) = path.as_str().and_then(hidden_name) {
|
||||
*path = json!(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(file) = report.get("file").and_then(Value::as_str).map(str::to_string)
|
||||
&& let Some(name) = hidden_name(&file)
|
||||
{
|
||||
// The run's error lines come after every line the script wrote. They are written again
|
||||
// from the report with the file's name, which also covers a line the console cut inside
|
||||
// the path. A console that dropped its oldest lines may hold only the last of them.
|
||||
let before = script::error_lines(&report);
|
||||
report["file"] = json!(name);
|
||||
if let Some(message) = report.get("message").and_then(Value::as_str) {
|
||||
report["message"] = json!(message.replace(&file, &name));
|
||||
}
|
||||
let after = script::error_lines(&report);
|
||||
if let Some(lines) = report.pointer_mut("/console/lines").and_then(Value::as_array_mut) {
|
||||
let kept = (1..=before.len().min(lines.len()))
|
||||
.rev()
|
||||
.find(|&n| lines.iter().rev().take(n).map(Value::as_str).eq(before.iter().rev().take(n).map(|l| Some(l.as_str()))))
|
||||
.unwrap_or(0);
|
||||
lines.truncate(lines.len() - kept);
|
||||
lines.extend(after.iter().skip(after.len().saturating_sub(kept)).map(|l| json!(l)));
|
||||
}
|
||||
}
|
||||
Some(report)
|
||||
}
|
||||
|
||||
/// The text of the script at `path`, which a listing of the Scripts folder gave
|
||||
/// ([`script::folder::read`]), checked as `script.run` checks a file's.
|
||||
pub fn installed_script(&self, path: &str) -> Result<String> {
|
||||
@@ -248,6 +285,13 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name a reply names `path` by when the file is outside the automation read roots; `None`
|
||||
/// when a reply may name it whole.
|
||||
fn hidden_name(path: &str) -> Option<String> {
|
||||
let shown = super::fileio::shown_path(path);
|
||||
(shown != path).then(|| shown.into_owned())
|
||||
}
|
||||
|
||||
fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(root) = s.scripts_dir() else {
|
||||
return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}));
|
||||
|
||||
@@ -184,7 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Not Aligned to Pixel Grid",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups but not into compound paths → {count}",
|
||||
"{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups, clip groups, blends, envelopes, repeats and Intertwine groups but not into compound paths → {count}",
|
||||
has_doc,
|
||||
not_pixel_aligned
|
||||
),
|
||||
|
||||
@@ -393,11 +393,12 @@ fn float_key(v: f32) -> Option<u32> {
|
||||
/// keys.
|
||||
type StopKey<'a> = (u32, ColorKey, u32, u32, Option<&'a str>, u32, Option<[u32; 4]>);
|
||||
|
||||
/// A gradient's kind, method, dither and stops, as keys.
|
||||
type GradientKey<'a> = (u8, u8, bool, Vec<StopKey<'a>>);
|
||||
/// A gradient's kind, method, dither, spread and count as it paints them, and stops, as keys.
|
||||
type GradientKey<'a> = (u8, u8, bool, (vectorcraft_color::GradientSpread, u32), Vec<StopKey<'a>>);
|
||||
|
||||
/// A key that is equal for two gradients exactly when the gradients are equal (`==`); `None` when
|
||||
/// any of its numbers is NaN, so the gradient equals no gradient.
|
||||
/// A key that is equal for two gradients exactly when the gradients are equal (`==`), apart from
|
||||
/// a count that a gradient which pads does not use ([`Gradient::painted_spread`]); `None` when any
|
||||
/// of its numbers is NaN, so the gradient equals no gradient.
|
||||
fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
let kind = match g.kind {
|
||||
GradientKind::Linear => 0,
|
||||
@@ -410,7 +411,7 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
GradientMethod::Classic => 0,
|
||||
GradientMethod::Perceptual => 1,
|
||||
};
|
||||
Some((kind, method, g.dither, g.stops.iter().map(stop_key).collect::<Option<_>>()?))
|
||||
Some((kind, method, g.dither, g.painted_spread(), g.stops.iter().map(stop_key).collect::<Option<_>>()?))
|
||||
}
|
||||
|
||||
/// A stop's key for [`gradient_key`]; `None` when any of its numbers is NaN.
|
||||
|
||||
@@ -1365,6 +1365,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod area_tests;
|
||||
mod block;
|
||||
pub(crate) use block::needed_room;
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
|
||||
|
||||
@@ -89,6 +89,39 @@ fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collection
|
||||
out
|
||||
}
|
||||
|
||||
/// The room along its lines that a frame of `t`'s text needs for Block to keep the widest line as
|
||||
/// typed at its present size: that line's width plus its paragraph's indents, as [`block_fit`]
|
||||
/// measures them, and a margin of under half a size step so that the line is not made a step
|
||||
/// smaller; with the widest line's first byte and its paragraph's index. A line whose negative
|
||||
/// indents take more than its width needs its own width. None when no line has a width.
|
||||
pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> {
|
||||
let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?;
|
||||
let text = t.plain_text();
|
||||
let lines = typed_lines(&text);
|
||||
let widths = line_widths(vectorcraft_text::FontDb::global(), t);
|
||||
let sizes = first_sizes(&t.runs, &lines);
|
||||
lines
|
||||
.iter()
|
||||
.zip(&sizes)
|
||||
.filter_map(|(l, size)| {
|
||||
let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?;
|
||||
let size = size * points;
|
||||
if l.content == l.start || !(size.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let para = t.para_at(l.para);
|
||||
let first = if l.para_start { para.first_line_indent } else { 0.0 };
|
||||
let indents = para.laid_out_left_indent() + para.right_indent + first;
|
||||
// Negative indents that take more than the line's width leave the line no room at its
|
||||
// size; the frame is then as wide as the line itself, and Block makes it larger.
|
||||
let room = if width + indents > 1e-9 { width + indents } else { width };
|
||||
// A tenth of a point more size widens the line by 0.1 * width / size.
|
||||
Some((room + 0.04 * width / size, l.start, l.para))
|
||||
})
|
||||
.filter(|r| r.0.is_finite() && r.0 > 1e-9)
|
||||
.reduce(|a, b| if b.0 > a.0 { b } else { a })
|
||||
}
|
||||
|
||||
/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing
|
||||
/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down
|
||||
/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its
|
||||
@@ -152,7 +185,7 @@ pub(crate) fn block_fit(t: &mut TextObject) -> bool {
|
||||
let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?;
|
||||
let para = t.para_at(l.para);
|
||||
let first = if l.para_start { para.first_line_indent } else { 0.0 };
|
||||
let avail = cell - para.left_indent - para.right_indent - first;
|
||||
let avail = cell - para.laid_out_left_indent() - para.right_indent - first;
|
||||
let size = size * points;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
|
||||
@@ -188,13 +188,25 @@ fn bad_params_and_other_type_are_refused() {
|
||||
assert!(!text(&s, id).dynamic_text);
|
||||
let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [point]})).unwrap();
|
||||
// Off leaves point type as it is, with no undo step, and a gap needs it turned on.
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["ids"], json!([point]));
|
||||
let e = s.execute("type.dynamicText", &json!({"on": false, "wordGap": 200})).unwrap_err().to_string();
|
||||
assert!(e.contains("need area type"), "{e}");
|
||||
assert_eq!(undo_len(&s), n);
|
||||
assert!(matches!(text(&s, point).kind, TextKind::Point));
|
||||
let shape = s.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [shape]})).unwrap();
|
||||
let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("select type on a path or area type"), "{e}");
|
||||
// With point type selected too, only the area type changes.
|
||||
// With point type selected too, both turn on, the point type as area type with Block on.
|
||||
s.execute("select.set", &json!({"ids": [id, point]})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([id]));
|
||||
assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text);
|
||||
assert_eq!(r["ids"], json!([id, point]));
|
||||
assert!(text(&s, id).dynamic_text && text(&s, point).dynamic_text);
|
||||
assert!(matches!(text(&s, point).kind, TextKind::Area { .. }));
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
// A gap with only type on a path selected is an error, and nothing changes.
|
||||
let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap();
|
||||
let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -438,6 +450,228 @@ fn threaded_frames_are_refused_and_threading_turns_block_off() {
|
||||
assert!(matches!(text(&s, a).kind, TextKind::Area { .. }));
|
||||
}
|
||||
|
||||
/// 12 pt point type at (300, 100) with `extra` params for `text.create`, selected.
|
||||
fn point(s: &mut Session, text: &str, extra: Value) -> u64 {
|
||||
let mut p = json!({"x": 300, "y": 100, "size": 12, "text": text});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Where the first glyph of the laid-out line starting at byte `start` is in the document.
|
||||
fn line_start(t: &TextObject, start: usize) -> vectorcraft_geom::Point {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let l = lay.lines.iter().find(|l| l.start == start).expect("a line starts there");
|
||||
t.xf * lay.glyphs[l.glyph_start].origin
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_becomes_area_type_with_block_at_its_widest_line() {
|
||||
for justify in ["left", "center", "right"] {
|
||||
let mut s = session();
|
||||
let id = point(&mut s, "Short\nA much longer line", json!({}));
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "justify": justify})).unwrap();
|
||||
let before = line_start(&text(&s, id), 6);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!((r["on"].clone(), r["ids"].clone()), (json!(true), json!([id])));
|
||||
assert_eq!((r["wordGap"].clone(), r["lineGap"].clone()), (json!(100.0), json!(0.0)), "the reply gives the new frame's gaps");
|
||||
assert_eq!(undo_len(&s), n + 1, "{justify}: one undo step");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Dynamic Text");
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }), "{justify}");
|
||||
assert_eq!(t.area.fit, AreaFit::None);
|
||||
assert_block(&t);
|
||||
assert_eq!(size_at(&t, 6), 12.0, "{justify}: the widest line keeps its size");
|
||||
assert!(size_at(&t, 0) > 24.0, "{justify}: the short line grows to the frame's width: {}", size_at(&t, 0));
|
||||
// Across, the widest line stays where it was; the short line above it grew, so it moved down.
|
||||
let after = line_start(&t, 6);
|
||||
assert!((after.x - before.x).abs() < 0.05, "{justify}: the widest line stays where it was across: {before:?} → {after:?}");
|
||||
assert!(after.y > before.y + 12.0, "{justify}");
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "{justify}: the frame holds every line");
|
||||
// Edits fit it again as area type; undo brings the point type back as it was.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let back = text(&s, id);
|
||||
assert!(matches!(back.kind, TextKind::Point) && !back.dynamic_text && size_at(&back, 0) == 12.0, "{justify}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_with_gaps_indents_and_vertical_type_turns_into_block() {
|
||||
let mut s = session();
|
||||
// The gaps apply to the frame point type becomes.
|
||||
let id = point(&mut s, "one\ntwo words here", json!({}));
|
||||
let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 4})).unwrap();
|
||||
assert_eq!((r["wordGap"].clone(), r["lineGap"].clone()), (json!(300.0), json!(4.0)));
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && (t.area.word_gap, t.area.line_gap) == (300.0, 4.0));
|
||||
assert_block(&t);
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Indents: the frame takes them in, so the widest line keeps its size.
|
||||
let id = point(&mut s, "Tiny\nThe widest line of all", json!({"y": 300}));
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "leftIndent": 20, "firstLineIndent": 10})).unwrap();
|
||||
let before = line_start(&text(&s, id), 5);
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_block(&t);
|
||||
assert_eq!(size_at(&t, 5), 12.0);
|
||||
assert!((line_start(&t, 5).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 5));
|
||||
// A nested list item: the frame takes in the level's indent too.
|
||||
let id = point(&mut s, "Tiny\nThe widest item of all", json!({"y": 200}));
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet", "listLevel": 3})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(size_at(&t, 5), 12.0, "nested list");
|
||||
assert!(size_at(&t, 0) > 12.0);
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Mixed alignments: the widest line keeps its size and its place.
|
||||
let id = point(&mut s, "Left\nThe widest line, right aligned", json!({"y": 400}));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) {
|
||||
let right = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Right, ..t.para.clone() };
|
||||
t.set_paragraph_styles(vec![t.para.clone(), right]);
|
||||
}
|
||||
let before = line_start(&text(&s, id), 5);
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(size_at(&t, 5), 12.0, "mixed alignments");
|
||||
assert!((line_start(&t, 5).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 5));
|
||||
// A right-to-left list, whose indents the layout mirrors.
|
||||
let id = point(&mut s, "קצר\nשורה ארוכה בהרבה מהראשונה", json!({"y": 450}));
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet", "rightIndent": 9})).unwrap();
|
||||
let widest = "קצר\n".len();
|
||||
let before = line_start(&text(&s, id), widest);
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(size_at(&t, widest), 12.0, "right-to-left list");
|
||||
assert!((line_start(&t, widest).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, widest));
|
||||
// Point type that was area type with its own options: the new frame takes the defaults but the
|
||||
// gaps.
|
||||
let id = point(&mut s, "Was\nonce a frame of two columns", json!({"y": 500}));
|
||||
s.execute("type.convertToAreaType", &json!({"ids": [id]})).unwrap();
|
||||
s.execute(
|
||||
"text.areaOptions",
|
||||
&json!({"columns": 2, "gutter": 12, "inset": 6, "verticalAlign": "bottom", "firstBaselineMin": 40, "wordGap": 150}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("type.convertToPointType", &json!({"ids": [id]})).unwrap();
|
||||
let before = line_start(&text(&s, id), 4);
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
let defaults = vectorcraft_doc::AreaOptions { word_gap: 150.0, ..Default::default() };
|
||||
assert_eq!(t.area, defaults);
|
||||
assert_eq!(size_at(&t, 4), 12.0, "options from an earlier frame");
|
||||
assert!((line_start(&t, 4).x - before.x).abs() < 0.05, "{before:?} → {:?}", line_start(&t, 4));
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Vertical type: the frame is as tall as the longest column and grows to the left.
|
||||
let id = point(&mut s, "縦書き\nもっと長い縦書きの行", json!({"x": 600, "y": 40, "vertical": true}));
|
||||
let before = line_start(&text(&s, id), "縦書き\n".len());
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.vertical && t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
|
||||
assert_block(&t);
|
||||
assert_eq!(size_at(&t, "縦書き\n".len()), 12.0);
|
||||
let after = line_start(&t, "縦書き\n".len());
|
||||
assert!((after.y - before.y).abs() < 0.05, "the longest column stays where it was down the page: {before:?} → {after:?}");
|
||||
assert!(after.x < before.x - 12.0, "the short column before it grew, so it moved left: {before:?} → {after:?}");
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_with_negative_indents_wider_than_its_line_turns_into_block() {
|
||||
// Block makes the line larger; it keeps its start, center or end by its alignment.
|
||||
let ends = |t: &TextObject| {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let l = &lay.lines[0];
|
||||
((t.xf * vectorcraft_geom::Point::new(l.x0, l.baseline)).x, (t.xf * vectorcraft_geom::Point::new(l.x1 - l.trailing, l.baseline)).x)
|
||||
};
|
||||
for justify in ["left", "center", "right"] {
|
||||
let mut s = session();
|
||||
let id = point(&mut s, "Short", json!({}));
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "justify": justify})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "leftIndent": -200})).unwrap();
|
||||
let (b0, b1) = ends(&text(&s, id));
|
||||
let n = undo_len(&s);
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1, "{justify}");
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }), "{justify}: the frame is as wide as the line");
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "{justify}");
|
||||
assert!(size_at(&t, 0) > 12.0, "{justify}: Block makes the line larger");
|
||||
let (a0, a1) = ends(&t);
|
||||
let kept = match justify {
|
||||
"left" => (a0, b0),
|
||||
"center" => ((a0 + a1) / 2.0, (b0 + b1) / 2.0),
|
||||
_ => (a1, b1),
|
||||
};
|
||||
assert!((kept.0 - kept.1).abs() < 0.05, "{justify}: the line keeps its aligned point: {b0},{b1} → {a0},{a1}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_under_a_text_wrap_object_turns_into_block_that_holds_every_line() {
|
||||
let mut s = session();
|
||||
let id = point(&mut s, "One\nTwo\nThree\nA much longer line than the rest", json!({}));
|
||||
// A wrap object above the type, across the top of the frame it becomes.
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 250, "y": 80, "width": 400, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
|
||||
assert!(!t.wrap.is_empty(), "the new area type takes the wrap object");
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame holds every line around the wrap");
|
||||
// A wrap object deeper than any size Block sets, across the whole frame: the lines go below it.
|
||||
let id = point(&mut s, "Below", json!({"x": 1000, "y": 100}));
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 900, "y": 80, "width": 400, "height": 9000})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && !t.wrap.is_empty());
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame reaches past a deep wrap object");
|
||||
// An inverted wrap object far below the type holds the lines inside it: the frame reaches it.
|
||||
let id = point(&mut s, "Inside", json!({"x": 1600, "y": 100}));
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 1550, "y": 9000, "width": 400, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("object.textWrap.make", &json!({})).unwrap();
|
||||
s.execute("object.textWrap.options", &json!({"invert": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && !t.wrap.is_empty());
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "the frame reaches a distant inverted wrap object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_with_nothing_to_fit_is_left_as_it_is() {
|
||||
let mut s = session();
|
||||
for blank in ["", " ", "\n\n"] {
|
||||
let id = point(&mut s, blank, json!({}));
|
||||
let before = text(&s, id);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["on"], json!(true));
|
||||
assert_eq!(undo_len(&s), n, "{blank:?}: no undo step");
|
||||
assert_eq!(text(&s, id), before, "{blank:?}");
|
||||
// A gap needs type it can apply to.
|
||||
let e = s.execute("type.dynamicText", &json!({"wordGap": 200})).unwrap_err().to_string();
|
||||
assert!(e.contains("need area type"), "{blank:?}: {e}");
|
||||
}
|
||||
// A line far shorter than the widest one stops at the size limit, and the frame still holds it.
|
||||
let id = point(&mut s, &format!(".\n{}", "w".repeat(400)), json!({"size": 6}));
|
||||
s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!(size_at(&t, 0), 1296.0);
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
let mut s = session();
|
||||
@@ -451,4 +685,16 @@ fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
// pass and the caches), plus the reply's own.
|
||||
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4;
|
||||
assert!(used <= bound, "{used} layouts");
|
||||
// Long point type: measured, fitted in its frame and fitted again at its depth, with the
|
||||
// layouts that place and measure the frame.
|
||||
let id = point(&mut s, &story, json!({}));
|
||||
let before = vectorcraft_text::test_fonts::layouts_on_this_thread();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before;
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
|
||||
assert_block(&t);
|
||||
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8;
|
||||
assert!(used <= bound, "point type: {used} layouts");
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, No
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::object::choice;
|
||||
use super::typecmd::{area_text, block_gaps, refresh_bounds};
|
||||
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
|
||||
switch_or, targets, text_param,
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Dynamic Text",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
has_dynamic_type,
|
||||
dynamic_text
|
||||
),
|
||||
@@ -346,13 +346,7 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A little slack on the right so the text doesn't rewrap.
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5 + trailing;
|
||||
// Slack goes where the alignment leaves room, so the text doesn't move or rewrap.
|
||||
let (sl, sr) = match t.para_at(0).justify {
|
||||
Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5),
|
||||
Justify::Right | Justify::JustifyRight => (slack, 0.0),
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => (slack, 0.0),
|
||||
_ => (0.0, slack),
|
||||
};
|
||||
let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack);
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
@@ -362,6 +356,107 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// How `slack` added to point type's lines in a frame is shared before and after them: where the
|
||||
/// alignment leaves room, so the text doesn't move or rewrap.
|
||||
fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) {
|
||||
match justify {
|
||||
Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5),
|
||||
Justify::Right | Justify::JustifyRight => (slack, 0.0),
|
||||
Justify::Auto if rtl => (slack, 0.0),
|
||||
_ => (0.0, slack),
|
||||
}
|
||||
}
|
||||
|
||||
/// Point type `t` turned into area type with Dynamic Text's Block on, with the default Area Type
|
||||
/// Options but its gaps: the frame takes the room along the lines that keeps the widest line as
|
||||
/// typed at its size ([`needed_room`]), placed so that line stays where it is by its own
|
||||
/// alignment, and after the fit it takes the depth that holds every line, so nothing overflows.
|
||||
/// Lines run in line space (for vertical type, down the page), and the frame is mapped to the
|
||||
/// type's own space by the layout's `line_xf`. `wrap` is the Text Wrap shapes the new area type
|
||||
/// takes, in the type's own space, which the fit and the depth follow. When negative indents take
|
||||
/// more than the widest line's width, the frame is as wide as that line and placed so that the
|
||||
/// line keeps its aligned point. None when no line has a
|
||||
/// width (empty text, or only spaces and breaks), which Block leaves at its size.
|
||||
fn point_to_block(t: &TextObject, wrap: &[vectorcraft_doc::WrapShape]) -> Option<TextObject> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Options point type kept from a frame it had before (columns, inset, alignment, first
|
||||
// baseline) do not carry over to the new frame.
|
||||
let mut t = t.clone();
|
||||
let (word_gap, line_gap) = (t.area.word_gap, t.area.line_gap);
|
||||
t.area = vectorcraft_doc::AreaOptions { word_gap, line_gap, ..Default::default() };
|
||||
t.wrap = wrap.to_vec();
|
||||
let t = &t;
|
||||
// The room is measured as Block sets the lines in a frame, with the word gap.
|
||||
let as_block = TextObject { dynamic_text: true, kind: TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)) }, ..t.clone() };
|
||||
let (room, widest, para_index) = needed_room(&as_block)?;
|
||||
let lay = vectorcraft_text::layout(db, t);
|
||||
let first = lay.lines.first()?;
|
||||
let line = lay.lines.iter().find(|l| l.start == widest)?;
|
||||
// Across, the widest line as it is aligned, with its paragraph's indents, which the frame holds.
|
||||
let para = t.para_at(para_index);
|
||||
let starts = widest == 0 || t.plain_text().as_bytes().get(widest - 1) == Some(&b'\n');
|
||||
let start_indent = para.laid_out_left_indent() + if starts { para.first_line_indent } else { 0.0 };
|
||||
// A horizontal right-to-left list paragraph has its indents mirrored, as the layout sets them.
|
||||
let mirror = line.rtl && !t.vertical && para.list.is_some();
|
||||
let (left, right) = if mirror { (para.right_indent, start_indent) } else { (start_indent, para.right_indent) };
|
||||
let (lo, hi) = (line.x0 - left, line.x1 - line.trailing + right);
|
||||
let top = lay.lines.iter().map(|l| l.baseline - l.ascent).fold(first.baseline - first.ascent, f64::min);
|
||||
let bottom = lay.lines.iter().map(|l| l.baseline + l.descent).fold(top, f64::max);
|
||||
if ![lo, hi, top, bottom, room].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
// Negative indents can take more than the line's width (hi below lo); the frame is then wider
|
||||
// than the line with its indents, and the same split of the difference keeps the line's
|
||||
// aligned point (its start, center or end) where it was when Block makes the line fill it.
|
||||
let (sl, _) = slack_sides(para.justify, line.rtl, room - (hi - lo));
|
||||
let frame = |depth: f64| lay.line_xf.transform_rect_bbox(Rect::new(lo - sl, top, lo - sl + room, top + depth.max(1.0)));
|
||||
let start = frame(bottom - top);
|
||||
let mut out = t.clone();
|
||||
out.kind = TextKind::Area { frame: shapes::rectangle(start) };
|
||||
out.dynamic_text = true;
|
||||
refresh_bounds(&mut out);
|
||||
// The lines fitted in one cell from the frame's top deep enough for all of them (every line at
|
||||
// the largest size Block sets), around any wrap shapes, give the depth the frame takes.
|
||||
let mut probe = out.clone();
|
||||
let points = t.style_scale().map_or(1.0, |s| s.points).max(1e-12);
|
||||
let deep = (bottom - top) + (lay.lines.len() as f64 + 1.0) * 3.0 * (1296.0 + out.area.line_gap.abs()) / points;
|
||||
// Wrap shapes push lines on past them (an inverted one holds them inside it), so the cell also
|
||||
// reaches as far again as the farthest one reaches past the frame's top.
|
||||
let inv = lay.line_xf.inverse();
|
||||
let deep = deep
|
||||
+ wrap
|
||||
.iter()
|
||||
.filter_map(|w| w.path.bounds().map(|r| inv.transform_rect_bbox(r)).map(|r| (r.y1 - top).max(0.0) + 2.0 * w.wrap.offset.abs()))
|
||||
.filter(|d| d.is_finite())
|
||||
.fold(0.0, f64::max);
|
||||
probe.kind = TextKind::Area { frame: shapes::rectangle(frame(deep)) };
|
||||
if !wrap.is_empty() {
|
||||
refresh_bounds(&mut probe);
|
||||
}
|
||||
let laid = vectorcraft_text::layout(db, &probe);
|
||||
if laid.overflow {
|
||||
return Some(out);
|
||||
}
|
||||
let mut grown = start;
|
||||
for l in &laid.lines {
|
||||
for y in [l.baseline - l.ascent, l.baseline + l.descent] {
|
||||
grown = grown.union_pt(laid.line_xf * vectorcraft_geom::Point::new(l.x0, y));
|
||||
}
|
||||
}
|
||||
// Only the depth grows (for vertical type, the columns run on to the left), with a hundredth
|
||||
// of a point to spare.
|
||||
if t.vertical {
|
||||
(grown.y0, grown.y1, grown.x0) = (start.y0, start.y1, grown.x0 - 0.01);
|
||||
} else {
|
||||
(grown.x0, grown.x1, grown.y1) = (start.x0, start.x1, grown.y1 + 0.01);
|
||||
}
|
||||
if grown.is_finite() && grown != start {
|
||||
out.kind = TextKind::Area { frame: shapes::rectangle(grown) };
|
||||
refresh_bounds(&mut out);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// (run, byte within the run) for a byte offset into the plain text.
|
||||
fn locate(runs: &[TextRun], byte: usize) -> Option<(usize, usize)> {
|
||||
let mut off = 0;
|
||||
@@ -698,14 +793,23 @@ fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> {
|
||||
path_text(n).or_else(|| area_text(n))
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it
|
||||
/// in a thread.
|
||||
/// Type `type.dynamicText` takes: type on a path, area type, and point type, which it turns into
|
||||
/// area type with Block on.
|
||||
fn dynamic_target(n: Option<&Node>) -> Option<&TextObject> {
|
||||
match n.map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::Point) => Some(t),
|
||||
_ => dynamic_type(n),
|
||||
}
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path, area type or point type,
|
||||
/// none of it in a thread.
|
||||
fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let d = &st.doc;
|
||||
let selected: Vec<NodeId> = st.selection.objects.to_vec();
|
||||
let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect();
|
||||
let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_target(d.node(*id)).is_some()).collect();
|
||||
if types.is_empty() {
|
||||
return Err("select type on a path or area type".into());
|
||||
}
|
||||
@@ -731,32 +835,46 @@ fn threaded_ids(d: &Document, ids: &[NodeId]) -> String {
|
||||
|
||||
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on
|
||||
/// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in
|
||||
/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn
|
||||
/// at ([`bake_dynamic_text`]).
|
||||
/// one undo step, and none when nothing changes. Turning it on also turns the selected point type
|
||||
/// into area type with Block on ([`point_to_block`]). Turning it off keeps the sizes the text was
|
||||
/// drawn at ([`bake_dynamic_text`]).
|
||||
fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.dynamicText";
|
||||
let (word_gap, line_gap) = block_gaps(p, C)?;
|
||||
let (ids, on, planned) = {
|
||||
let (ids, on, planned, converted) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect();
|
||||
let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_target(d.node(*i)).is_some()).collect();
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?;
|
||||
if let Some(why) = threaded_refusal(d, &ids) {
|
||||
return Err(bad(C, why));
|
||||
}
|
||||
let gap_given = word_gap.is_some() || line_gap.is_some();
|
||||
if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) {
|
||||
let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
// Point type with a line to fit, which turning it on makes area type.
|
||||
let converts = |id: &NodeId| on && dynamic_target(d.node(*id)).is_some_and(|t| matches!(t.kind, TextKind::Point) && needed_room(t).is_some());
|
||||
if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some() || converts(id)) {
|
||||
return Err(bad(C, "wordGap and lineGap need area type in the selection"));
|
||||
}
|
||||
let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
// Each object as the command leaves it, and only those it changes.
|
||||
let mut planned: Vec<(NodeId, TextObject)> = vec![];
|
||||
// The point type that becomes area type, with the gaps applied, by id.
|
||||
let mut converted: Vec<(NodeId, TextObject)> = vec![];
|
||||
for id in &ids {
|
||||
let Some(t) = dynamic_type(d.node(*id)) else { continue };
|
||||
let Some(t) = dynamic_target(d.node(*id)) else { continue };
|
||||
let mut after = t.clone();
|
||||
if matches!(t.kind, TextKind::Area { .. }) {
|
||||
if matches!(t.kind, TextKind::Area { .. } | TextKind::Point) {
|
||||
after.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
|
||||
after.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
|
||||
}
|
||||
if matches!(t.kind, TextKind::Point) {
|
||||
// Point type has no Dynamic Text of its own: on, it becomes area type with Block
|
||||
// on; off, or with no line to fit, it stays as it is.
|
||||
if let Some(block) = on.then(|| point_to_block(&after, &[])).flatten() {
|
||||
planned.push((*id, block));
|
||||
converted.push((*id, after));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (on, t.dynamic_text) {
|
||||
(true, true) => refresh_bounds(&mut after),
|
||||
(true, false) => {
|
||||
@@ -776,7 +894,7 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
planned.push((*id, after));
|
||||
}
|
||||
}
|
||||
(ids, on, planned)
|
||||
(ids, on, planned, converted)
|
||||
};
|
||||
if !planned.is_empty() {
|
||||
s.edit("Dynamic Text", |d, _| {
|
||||
@@ -785,6 +903,19 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
**t = after.clone();
|
||||
}
|
||||
}
|
||||
if converted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// The new area type takes the Text Wrap shapes above it; one that has any is fitted
|
||||
// again around them, with the depth that holds every line.
|
||||
for id in vectorcraft_doc::text::resolve_wrap(None, d) {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
|
||||
let block = converted.iter().find(|(c, _)| *c == id).and_then(|(_, src)| point_to_block(src, &t.wrap));
|
||||
match block {
|
||||
Some(block) => **t = block,
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Free Distort",
|
||||
[],
|
||||
None,
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), ids?} projective warp of anchors and handles",
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays",
|
||||
has_doc,
|
||||
distort
|
||||
),
|
||||
@@ -104,7 +104,8 @@ impl Projective {
|
||||
}
|
||||
|
||||
/// Warp `n`'s anchors and handles; gradients (pinned first if unplaced) follow the warp's affine
|
||||
/// approximation at their centre.
|
||||
/// approximation at their center. The art of a linked opacity mask is warped with the object it
|
||||
/// masks; an unlinked one stays where it is.
|
||||
fn warp_node(n: &mut Node, pr: &Projective) {
|
||||
n.pin_gradients();
|
||||
match &mut n.kind {
|
||||
@@ -131,6 +132,9 @@ fn warp_node(n: &mut Node, pr: &Projective) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) {
|
||||
warp_node(Arc::make_mut(&mut m.art), pr);
|
||||
}
|
||||
n.appearance.warp_gradients(&|p| pr.affine_near(p));
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,9 @@ pub struct DocState {
|
||||
/// Select › Start Global Edit: the objects edited together until Stop Global Edit or Escape
|
||||
/// ([`cmd::globaledit`]). Editing state: not saved, not undoable.
|
||||
pub global_edit: Option<cmd::globaledit::GlobalEdit>,
|
||||
/// The objects Start Global Edit would take, highlighted before it starts
|
||||
/// ([`cmd::globaledit::similar`]), as of a revision. Not saved, not undoable.
|
||||
pub(crate) similar_outlines: cmd::globaledit::SimilarCache,
|
||||
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
|
||||
pub(crate) symbol_edit_return: cmd::symboledit::Return,
|
||||
pub interaction: Option<Interaction>,
|
||||
@@ -302,6 +305,7 @@ impl DocState {
|
||||
variables_highlight: None,
|
||||
isolation: None,
|
||||
global_edit: None,
|
||||
similar_outlines: Default::default(),
|
||||
symbol_edit_return: Default::default(),
|
||||
interaction: None,
|
||||
undo_group: None,
|
||||
|
||||
@@ -3,6 +3,9 @@ use super::{NodeId, cancel};
|
||||
/// The text of [`EngineError::Busy`], which ends every error a frontend reports for it.
|
||||
pub const SCRIPT_BUSY: &str = "a script is running: stop it or wait for it to finish";
|
||||
|
||||
/// Stable prefix for a save refused by the filesystem: choose another destination.
|
||||
pub const READ_ONLY_LOCATION: &str = "READ_ONLY_LOCATION";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("unknown command `{0}`")]
|
||||
@@ -20,6 +23,10 @@ pub enum EngineError {
|
||||
NoNode(NodeId),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
/// The save's terminal filesystem error refuses writes here. The reason keeps the path and
|
||||
/// system message. This never means an automation-root refusal or a recovery-copy failure.
|
||||
#[error("{code}: {0}", code = READ_ONLY_LOCATION)]
|
||||
ReadOnlyLocation(String),
|
||||
/// The caller asked for the command to stop ([`cancel`]). It changed nothing.
|
||||
#[error("cancelled; nothing was changed")]
|
||||
Cancelled,
|
||||
|
||||
@@ -382,7 +382,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, Result, SCRIPT_BUSY};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
|
||||
@@ -2116,6 +2116,27 @@ fn line_to(s: &mut Session, host: &Host, entry: console::Entry, cut: bool) {
|
||||
host.console.borrow_mut().push(line, cut);
|
||||
}
|
||||
|
||||
/// The error of the failed run `report` describes, as its console lines give it; `name` is the
|
||||
/// run's name in those lines ([`console::line_name`]).
|
||||
fn error_text(name: &str, report: &Value) -> String {
|
||||
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
|
||||
let message = report["message"].as_str().unwrap_or_default();
|
||||
match report["file"].as_str() {
|
||||
Some(file) if line > 0 => format!("{name}: {file}:{line}:{column}: {message}"),
|
||||
_ if line > 0 => format!("{name}:{line}:{column}: {message}"),
|
||||
_ => format!("{name}: location unavailable: {message}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The console lines of the error of the failed run `report` describes, each as the console keeps
|
||||
/// it, cut to its limit.
|
||||
pub(crate) fn error_lines(report: &Value) -> Vec<String> {
|
||||
let name = console::line_name(report["name"].as_str().unwrap_or_default());
|
||||
let mut lines = vec![];
|
||||
each_line(&error_text(&name, report), |line, _| lines.push(line));
|
||||
lines
|
||||
}
|
||||
|
||||
/// Ends the console lines of `host`'s run: the line `$.write` left unended, then for a failed run
|
||||
/// (`report["ok"]` false) its error as `name:line:column: message`, then an end line and a report
|
||||
/// line in the session's console. Adds the run's time, host calls by kind, slowest commands,
|
||||
@@ -2130,14 +2151,7 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
|
||||
}
|
||||
}
|
||||
if report["ok"] == false {
|
||||
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
|
||||
let message = report["message"].as_str().unwrap_or_default();
|
||||
let text = match report["file"].as_str() {
|
||||
Some(file) if line > 0 => format!("{}: {file}:{line}:{column}: {message}", host.name),
|
||||
_ if line > 0 => format!("{}:{line}:{column}: {message}", host.name),
|
||||
_ => format!("{}: location unavailable: {message}", host.name),
|
||||
};
|
||||
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
|
||||
}
|
||||
let timing = clock().is_some();
|
||||
let ms = millis(host.run_nanos.get());
|
||||
|
||||
@@ -104,7 +104,10 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let list = run(&mut s, "brush.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "bristle-brushes", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams"]);
|
||||
assert_eq!(
|
||||
ids,
|
||||
["art-ribbons", "calligraphic-nibs", "bristle-brushes", "pattern-borders", "scatter-shapes", "game-trails", "energy-beams", "dry-media"]
|
||||
);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
|
||||
assert_eq!(
|
||||
@@ -124,6 +127,12 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
|
||||
);
|
||||
assert_eq!(libs[6]["count"].as_u64(), Some(4));
|
||||
let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"}));
|
||||
assert_eq!(
|
||||
dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((libs[7]["name"].as_str(), libs[7]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
|
||||
@@ -137,6 +146,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("scatter-shapes", "scatter"),
|
||||
("game-trails", "art"),
|
||||
("energy-beams", "art"),
|
||||
("dry-media", "art"),
|
||||
] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
@@ -166,6 +176,137 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// Whether `p` lies inside the polygon through `pts` (even-odd ray cast).
|
||||
fn inside(p: vectorcraft_geom::Point, pts: &[vectorcraft_geom::Point]) -> bool {
|
||||
let mut odd = false;
|
||||
for (i, a) in pts.iter().enumerate() {
|
||||
let b = pts[(i + 1) % pts.len()];
|
||||
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) * (b.x - a.x) / (b.y - a.y) {
|
||||
odd = !odd;
|
||||
}
|
||||
}
|
||||
odd
|
||||
}
|
||||
|
||||
/// Every anchor of the paths in `nodes` and their descendants.
|
||||
fn anchors(nodes: &[&vectorcraft_doc::Node]) -> Vec<vectorcraft_geom::Point> {
|
||||
let mut out = vec![];
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| out.extend(c.path_data().into_iter().flat_map(|p| p.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Dry Media: four art brushes of grainy dry marks (chalk, pencil, crayon, charcoal) with names
|
||||
/// of their own. Each one's art is a bounded set of filled vector paths 100 pt long that takes the
|
||||
/// stroke color as tints, with real even-odd gaps in the chalk and the crayon; it draws finite art
|
||||
/// on curved and short paths, is the same every time it is made, and goes into a document in one
|
||||
/// undo step, once, applied, and through a saved library unchanged.
|
||||
#[test]
|
||||
fn the_dry_media_library_holds_grainy_art_brushes_with_bounded_art() {
|
||||
use vectorcraft_brush::{ArtScale, Colorization};
|
||||
use vectorcraft_geom::FillRule;
|
||||
let mut s = session();
|
||||
let (info, lib) = cmd::brushlib::library(&s, "dry-media").unwrap();
|
||||
assert_eq!((info.name.as_str(), info.category, lib.name.as_str()), ("Dry Media", "builtIn", "Dry Media"));
|
||||
let names: Vec<String> = lib.brushes.iter().map(|b| b.name.clone()).collect();
|
||||
assert_eq!(names, ["Chalk Grain", "Graphite Pencil", "Wax Crayon", "Charcoal Dust"]);
|
||||
let mut total = 0;
|
||||
for (b, (height, gaps)) in lib.brushes.iter().zip([(8.0, true), (2.5, false), (6.0, true), (7.0, false)]) {
|
||||
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
|
||||
assert_eq!((a.colorization, a.scale, a.width), (Colorization::Tints, ArtScale::Stretch, 100.0), "{}", b.name);
|
||||
let (mut paths, mut holes) = (0, 0);
|
||||
a.art.walk(&mut |n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
paths += 1;
|
||||
assert!(path.subpaths.iter().all(|sp| sp.closed && sp.anchors.len() >= 4), "{}", b.name);
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
assert_eq!(*rule, FillRule::EvenOdd, "{}", b.name);
|
||||
// The gaps lie inside the band and apart from each other, so each one is a hole.
|
||||
let body = anchors(&[&*children[0]]);
|
||||
let boxes: Vec<vectorcraft_geom::Rect> = children[1..].iter().map(|c| c.path_data().unwrap().bounds().unwrap()).collect();
|
||||
for (i, c) in children[1..].iter().enumerate() {
|
||||
assert!(anchors(&[&**c]).iter().all(|p| inside(*p, &body)), "{}: gap {i} leaves the band", b.name);
|
||||
let r = boxes[i];
|
||||
assert!(boxes[..i].iter().all(|o| r.x0 >= o.x1 || o.x0 >= r.x1 || r.y0 >= o.y1 || o.y0 >= r.y1), "{}: gap {i} overlaps", b.name);
|
||||
}
|
||||
holes += children.len() - 1;
|
||||
}
|
||||
NodeKind::Group { .. } => {}
|
||||
other => panic!("{}: unexpected {other:?}", b.name),
|
||||
});
|
||||
let pts = anchors(&[&a.art]);
|
||||
assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
|
||||
assert!(paths <= 80 && pts.len() <= 500, "{}: {paths} paths, {} anchors", b.name, pts.len());
|
||||
assert_eq!(holes > 0, gaps, "{}: {holes} gaps", b.name);
|
||||
let r = vectorcraft_geom::Rect::from_points(pts[0], pts[0]);
|
||||
let r = pts.iter().fold(r, |r, p| r.union_pt(*p));
|
||||
assert!(r.x0 >= 0.0 && r.x0 < 0.5 && r.x1 <= 100.0 && r.x1 > 99.5, "{}: {r:?}", b.name);
|
||||
assert!((r.height() - height).abs() <= height * 0.25 && r.y0 < 0.0 && r.y1 > 0.0, "{}: {r:?}", b.name);
|
||||
total += pts.len();
|
||||
// Finite art on a curve and on a 2 pt path.
|
||||
for (line, width) in [(vec![(0.0, 0.0), (60.0, -40.0), (140.0, 40.0), (200.0, 0.0)], 1.0), (vec![(0.0, 0.0), (2.0, 0.0)], 3.0)] {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to(line[0]);
|
||||
if line.len() == 4 {
|
||||
bp.curve_to(line[1], line[2], line[3]);
|
||||
} else {
|
||||
bp.line_to(line[1]);
|
||||
}
|
||||
let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), width);
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &bp, &stroke);
|
||||
let drawn = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!drawn.is_empty() && drawn.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} on {line:?}", b.name);
|
||||
}
|
||||
}
|
||||
assert!(total <= 1200, "{total} anchors");
|
||||
// Made again, the same bytes; the checksum pins them across runs and platforms.
|
||||
let bytes = serde_json::to_string(&cmd::brushlib::dry_media().brushes).unwrap();
|
||||
assert_eq!(bytes, serde_json::to_string(&lib.brushes).unwrap());
|
||||
let fnv = bytes.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
|
||||
assert_eq!(fnv, 12_859_086_488_513_909_464, "the Dry Media art changed");
|
||||
// Names of their own: no default brush's, no other built-in library's.
|
||||
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
|
||||
let others: Vec<String> = cmd::brushlib::BUILTIN
|
||||
.iter()
|
||||
.filter(|b| b.id != "dry-media")
|
||||
.flat_map(|b| cmd::brushlib::library(&s, b.id).unwrap().1.brushes.iter().map(|x| x.name.clone()).collect::<Vec<_>>())
|
||||
.collect();
|
||||
assert!(names.iter().all(|n| !defaults.contains(&n.as_str()) && !others.contains(n)), "{names:?}");
|
||||
|
||||
// Added and applied to a path in one undo step, which undo takes back.
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60}))["id"].as_u64().unwrap();
|
||||
let stroke_brush = |s: &Session| doc(s).node(NodeId(path)).unwrap().appearance.stroke().and_then(|st| st.brush.clone());
|
||||
let before = (undo_len(&s), brushes(&s));
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Dry Media", "name": "Wax Crayon", "apply": true, "ids": [path]}));
|
||||
assert_eq!((strs(&r["added"]), r["applied"].clone()), (vec!["Wax Crayon"], json!([path])));
|
||||
assert_eq!((undo_len(&s), stroke_brush(&s).as_deref()), (before.0 + 1, Some("Wax Crayon")));
|
||||
assert_eq!(&brush(&s, "Wax Crayon"), lib.brush("Wax Crayon").unwrap());
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((brushes(&s), stroke_brush(&s)), (before.1.clone(), None));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
// The rest in one more step; then nothing new to add.
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "dry-media"}));
|
||||
assert_eq!((strs(&r["added"]), strs(&r["existing"])), (vec!["Chalk Grain", "Graphite Pencil", "Charcoal Dust"], vec!["Wax Crayon"]));
|
||||
assert_eq!(undo_len(&s), before.0 + 2);
|
||||
assert_eq!(
|
||||
brushes(&s),
|
||||
[before.1.clone(), vec!["Wax Crayon".into(), "Chalk Grain".into(), "Graphite Pencil".into(), "Charcoal Dust".into()]].concat()
|
||||
);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "dry-media"}));
|
||||
assert_eq!((strs(&r["added"]).len(), undo_len(&s)), (0, before.0 + 2));
|
||||
// Saved as a library and loaded back: the same brushes, in the document's order.
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({ "names": names, "name": "Dry" }));
|
||||
let b64 = saved["dataBase64"].as_str().unwrap().to_string();
|
||||
let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Dry.vectorcraft"}));
|
||||
let (_, reopened) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(reopened.len(), lib.len());
|
||||
for b in &lib.brushes {
|
||||
assert_eq!(reopened.brush(&b.name), Some(b), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one brush per tip shape, every value inside the range the brush keeps (a value
|
||||
/// outside would be clamped without notice), names no other library or default brush uses; added
|
||||
/// in one step, not twice, and saved as a library they reopen unchanged.
|
||||
|
||||
@@ -88,19 +88,17 @@ fn dynamic_text_refuses_bad_params_and_other_type() {
|
||||
assert!(err(s.execute("type.dynamicText", &json!({"on": 1}))).contains("on"));
|
||||
assert_eq!(undo_len(&s), before);
|
||||
assert!(!text(&s, id).dynamic_text);
|
||||
// Point type alone: refused (area type takes Block, `typecmd::block_tests`).
|
||||
let point = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [point]})).unwrap();
|
||||
assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path or area type"));
|
||||
let empty = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [empty]})).unwrap();
|
||||
assert!(s.execute("type.dynamicText", &json!({})).is_err());
|
||||
// With point type selected too, only the type on a path changes.
|
||||
// With point type selected too, both change in one undo step: the point type becomes area
|
||||
// type with Block on (`typecmd::block_tests`).
|
||||
let before = undo_len(&s);
|
||||
s.execute("select.set", &json!({"ids": [point, id.0]})).unwrap();
|
||||
let r = s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(r["ids"], json!([id.0]));
|
||||
assert!(!text(&s, NodeId(point)).dynamic_text);
|
||||
assert_eq!(r["ids"], json!([point, id.0]));
|
||||
assert!(text(&s, NodeId(point)).dynamic_text && text(&s, id).dynamic_text);
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -631,6 +631,32 @@ fn an_opacity_mask_on_type_bends_as_other_art() {
|
||||
assert_eq!(kept, 1, "the type's stroke stays a stroke");
|
||||
}
|
||||
|
||||
/// An envelope bends the art of a linked opacity mask on its contents with them; an unlinked mask
|
||||
/// stays where it is.
|
||||
#[test]
|
||||
fn an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one() {
|
||||
for linked in [true, false] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s);
|
||||
let m = rect(&mut s);
|
||||
sel(&mut s, &[a, m]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
if !linked {
|
||||
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
|
||||
}
|
||||
let before = node(&s, a).extras().mask.as_ref().unwrap().art.path_data().cloned();
|
||||
sel(&mut s, &[a]);
|
||||
let e = arch(&mut s, 60.0, json!({}));
|
||||
let mut found = vec![];
|
||||
for n in &evaluated(&s, e) {
|
||||
n.walk(&mut |c| found.extend(c.extras().mask.as_ref().map(|k| (c.path_data().cloned(), k.art.path_data().cloned()))));
|
||||
}
|
||||
let [(bent, mask)] = found.as_slice() else { panic!("one masked object: {found:?}") };
|
||||
assert!(bent != &before, "the contents bend");
|
||||
assert_eq!(mask, if linked { bent } else { &before }, "linked: {linked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand turns an envelope of stroked type into its bent glyph outlines with the stroke on them,
|
||||
/// at its own weight, as it draws (#6644).
|
||||
#[test]
|
||||
|
||||
@@ -92,7 +92,50 @@ fn start_global_edit_takes_the_objects_of_the_same_shape_at_any_place_and_size()
|
||||
assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2);
|
||||
let r = s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
assert_eq!(r["active"], false, "the second run is Stop Global Edit");
|
||||
assert!(s.doc().unwrap().global_edit.is_none() && crate::cmd::globaledit::highlights(&s).is_empty());
|
||||
assert!(s.doc().unwrap().global_edit.is_none());
|
||||
assert_eq!(crate::cmd::globaledit::highlights(&s).len(), 2, "with the square still selected, the objects it would take are highlighted again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts() {
|
||||
use crate::cmd::globaledit::highlights;
|
||||
let mut s = session();
|
||||
let [a, b, _, wide, _] = squares(&mut s);
|
||||
assert!(highlights(&s).is_empty(), "nothing selected");
|
||||
sel(&mut s, &[a]);
|
||||
assert_eq!(members(&s), None, "Global Edit has not started");
|
||||
assert_eq!(highlights(&s).len(), 2, "the copy and the smaller square");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(highlights(&s).len(), 1, "the options narrow them: the copy only");
|
||||
s.execute("select.globalEditOptions", &json!({"size": false})).unwrap();
|
||||
assert_eq!(highlights(&s).len(), 2);
|
||||
sel(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
sel(&mut s, &[a]);
|
||||
assert_eq!(highlights(&s).len(), 1, "a deleted copy is no longer highlighted");
|
||||
sel(&mut s, &[wide]);
|
||||
assert!(highlights(&s).is_empty(), "the rectangle has no similar object");
|
||||
sel(&mut s, &[a, wide]);
|
||||
assert!(highlights(&s).is_empty(), "two objects selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
|
||||
let mut s = session();
|
||||
let [a, b, ..] = squares(&mut s);
|
||||
let outline = node(&s, b).stroke_path().unwrap();
|
||||
let shown = |s: &mut Session| {
|
||||
s.overlays(ViewInfo::default())
|
||||
.iter()
|
||||
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
|
||||
};
|
||||
sel(&mut s, &[a]);
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
assert!(shown(&mut s), "the copy is highlighted with the Selection tool");
|
||||
s.select_tool("directSelection", ViewInfo::default()).unwrap();
|
||||
assert!(!shown(&mut s), "not with another tool before Global Edit starts");
|
||||
s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
assert!(shown(&mut s), "while Global Edit is on, with any tool");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -506,6 +549,7 @@ fn leaving_out_all_but_one_ends_global_edit_and_the_first_object_stays() {
|
||||
let r = s.execute("select.globalEditExclude", &json!({"id": b.0})).unwrap();
|
||||
assert_eq!(r, json!({"active": false, "count": 0, "ids": []}));
|
||||
assert_eq!(members(&s), None, "one object left: Global Edit ends");
|
||||
sel(&mut s, &[wide]);
|
||||
assert!(crate::cmd::globaledit::highlights(&s).is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -881,3 +881,134 @@ fn making_a_gradient_diamond_is_one_undo_step() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id), before);
|
||||
}
|
||||
|
||||
/// `paint.setFill` and `paint.editGradient` take a spread and a count for each kind of gradient
|
||||
/// that has ends; the params give them back, the native format keeps them, and a change is one
|
||||
/// undo step while an edit that changes nothing records none.
|
||||
#[test]
|
||||
fn a_gradient_takes_a_spread_and_a_count() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
for kind in ["linear", "radial", "conic", "diamond"] {
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "spread": "Reflect", "repeats": 4}})).unwrap();
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Reflect, 4), "{kind}");
|
||||
let params = vectorcraft_tools::params::gradient_params(&g);
|
||||
assert_eq!((params["spread"].as_str(), params["repeats"].as_u64()), (Some("reflect"), Some(4)), "{kind}");
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.spread, GradientSpread::Pad, "a new gradient pads");
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient, g.gradient, "{kind}");
|
||||
}
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step");
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 2));
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "nothing changed: no step");
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.repeats, 2, "Pad keeps the count for later");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id), g);
|
||||
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!("the gradient is lost") };
|
||||
assert_eq!((saved.gradient.spread, saved.gradient.repeats), (GradientSpread::Repeat, 2));
|
||||
// The params of a gradient that pads give back the count it keeps.
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
assert_eq!((fill_gradient(&s, id).gradient.spread, fill_gradient(&s, id).gradient.repeats), (GradientSpread::Pad, 2), "{params}");
|
||||
}
|
||||
|
||||
/// A spread or count a gradient can't take is an error, from every command that sets one, and the
|
||||
/// gradient stays as it was: an unknown spread, a count that is not a whole number from 1 to 100,
|
||||
/// and a spread other than pad on a freeform gradient.
|
||||
#[test]
|
||||
fn a_bad_spread_or_count_is_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "spread": "repeat", "repeats": 3}})).unwrap();
|
||||
let before = fill_gradient(&s, id);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!({"spread": "mirror"}), json!({"spread": 1}), json!({"spread": true})] {
|
||||
let e = s.execute("paint.editGradient", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` must be pad, repeat or reflect"), "{bad}: {e}");
|
||||
}
|
||||
for n in [json!(0), json!(-2), json!(1.5), json!(101), json!(1e9), json!("3"), json!(f64::MAX)] {
|
||||
let e = s.execute("paint.editGradient", &json!({ "repeats": n })).unwrap_err().to_string();
|
||||
assert!(e.contains("`repeats` must be a whole number from 1 to 100"), "{n}: {e}");
|
||||
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "repeats": n}})).unwrap_err().to_string();
|
||||
assert!(e.contains("`repeats`"), "{n}: {e}");
|
||||
}
|
||||
let freeform = json!({"kind": "freeform", "spread": "reflect"});
|
||||
let e = s.execute("paint.editGradient", &freeform).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` applies to linear, radial, conic and diamond gradients"), "{e}");
|
||||
let e = s.execute("paint.setFill", &json!({ "gradient": freeform })).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` applies to"), "{e}");
|
||||
assert_eq!(fill_gradient(&s, id), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// Pad on a freeform gradient is allowed (it has nothing to spread), and 100 is the most.
|
||||
s.execute("paint.editGradient", &json!({"repeats": 100})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": "freeform", "spread": "pad"})).unwrap();
|
||||
// A repeating gradient turned freeform: its params, which carry no spread, set it again.
|
||||
s.execute("paint.editGradient", &json!({"kind": "radial", "spread": "reflect"})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": "freeform"})).unwrap();
|
||||
let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id));
|
||||
assert!(params.get("spread").is_none(), "{params}");
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
}
|
||||
|
||||
/// A spread for a selected gradient applies while the gradient used last, the default, is a
|
||||
/// freeform one, which keeps no spread.
|
||||
#[test]
|
||||
fn a_spread_for_a_selected_gradient_leaves_a_freeform_default_alone() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"ids": [a.0], "spread": "repeat", "repeats": 3})).unwrap();
|
||||
let g = fill_gradient(&s, a);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 3));
|
||||
}
|
||||
|
||||
/// A preset keeps its spread and count: saved from a gradient, applied to another object.
|
||||
#[test]
|
||||
fn a_gradient_preset_keeps_its_spread() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "spread": "reflect", "repeats": 5}})).unwrap();
|
||||
s.execute("gradient.presets.save", &json!({"name": "Fan"})).unwrap();
|
||||
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("gradient.presets.apply", &json!({"name": "Fan"})).unwrap();
|
||||
let g = fill_gradient(&s, b);
|
||||
assert_eq!((g.gradient.kind, g.gradient.spread, g.gradient.repeats), (GradientKind::Conic, GradientSpread::Reflect, 5));
|
||||
assert_eq!(fill_gradient(&s, a).gradient.repeats, 5);
|
||||
}
|
||||
|
||||
/// A gradient set back to Pad keeps its count for later, and still matches a saved preset and a
|
||||
/// swatch of the same gradient; while it repeats, the spread tells them apart.
|
||||
#[test]
|
||||
fn a_padding_gradient_matches_whatever_count_it_keeps() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("paint.setFill", &json!({ "gradient": ramp })).unwrap();
|
||||
s.execute("gradient.presets.save", &json!({"name": "Plain"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "paint": {"gradient": ramp}})).unwrap();
|
||||
let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().contains(&json!("Plain"));
|
||||
assert!(!unused(&mut s));
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 5})).unwrap();
|
||||
assert_eq!(s.active_saved_gradient_preset(), None, "a repeating gradient is another ramp");
|
||||
assert!(unused(&mut s), "nothing paints the swatch's gradient");
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, a).gradient.repeats, 5);
|
||||
assert_eq!(s.active_saved_gradient_preset(), Some("Plain"));
|
||||
assert!(!unused(&mut s), "the gradient paints as the swatch does");
|
||||
}
|
||||
@@ -531,6 +531,139 @@ fn a_space_that_is_not_usable_is_refused_and_one_too_large_is_kept_to_the_path()
|
||||
assert_eq!(space(&s, g), (Some(100.0), 0.0));
|
||||
}
|
||||
|
||||
/// The ids of group `g`'s objects in their order along the path, and of its children in the
|
||||
/// Layers panel's order.
|
||||
fn orders(s: &Session, g: NodeId) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let n = s.doc().unwrap().doc.node(g).unwrap();
|
||||
let path = n.extras().objects_on_path.as_deref().unwrap().members.iter().map(|m| m.id).collect();
|
||||
(path, n.children().unwrap().iter().map(|c| c.id).collect())
|
||||
}
|
||||
|
||||
/// Three objects of different widths (20, 40 and 10 pt) attached to a 300 pt line from (50, 300),
|
||||
/// in that order, with a Space of 100 pt from 0, Pivot 4 and Rotate 0.
|
||||
fn three_on_a_line(s: &mut Session) -> (NodeId, [NodeId; 3], NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(s, 100.0, 0.0, 40.0, 20.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 20.0);
|
||||
let path = line(s, (50.0, 300.0), (350.0, 300.0));
|
||||
let g = attach(s, path, &[a, b, c], json!({}));
|
||||
s.execute("object.objectsOnPath.options", &json!({"spacing": 100})).unwrap();
|
||||
(g, [a, b, c], path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_member_takes_the_target_s_place_and_shifts_the_objects_between() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, c], path) = three_on_a_line(&mut s);
|
||||
let (_, layers) = orders(&s, g);
|
||||
let before = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": c.0})).unwrap();
|
||||
assert_eq!(v, json!({"group": g.0, "member": a.0, "index": 2}));
|
||||
assert_eq!(orders(&s, g), (vec![b, c, a], layers.clone()), "the order along the path changes, the Layers order does not");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
assert_eq!(center(&s, b), Point::new(50.0, 300.0));
|
||||
assert_eq!(center(&s, c), Point::new(150.0, 300.0));
|
||||
assert_eq!(center(&s, a), Point::new(250.0, 300.0));
|
||||
let after = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap();
|
||||
assert_eq!(
|
||||
(after.path, after.pivot, after.rotate, after.spacing, after.start),
|
||||
(path, before.pivot, before.rotate, before.spacing, before.start)
|
||||
);
|
||||
let w = bounds(&s, a);
|
||||
assert!((w.width() - 20.0).abs() < 1e-9, "the object keeps its art: {w:?}");
|
||||
// The last one back to the first place, with its group named.
|
||||
let v = s.execute("object.objectsOnPath.moveMember", &json!({"group": g.0, "member": a.0, "target": b.0})).unwrap();
|
||||
assert_eq!(v["index"], 0);
|
||||
assert_eq!(orders(&s, g).0, [a, b, c]);
|
||||
assert_eq!(center(&s, a), Point::new(50.0, 300.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [b, c, a]);
|
||||
assert_eq!(center(&s, a), Point::new(250.0, 300.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [a, b, c]);
|
||||
assert_eq!(center(&s, c), Point::new(250.0, 300.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(orders(&s, g).0, [b, c, a]);
|
||||
// Onto its own place: nothing changes and no step is recorded.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": c.0, "target": c.0})).unwrap();
|
||||
assert_eq!(v["index"], 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// The order saves and reopens.
|
||||
let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone();
|
||||
let mut o = Session::new();
|
||||
o.execute("document.open", &json!({"name": "objects.vectorcraft", "dataBase64": data})).unwrap();
|
||||
assert_eq!(orders(&o, g), (vec![b, c, a], layers));
|
||||
assert_eq!(center(&o, a), Point::new(250.0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_member_refuses_what_is_not_an_object_on_the_same_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 x = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
let other_line = line(&mut s, (50.0, 380.0), (350.0, 380.0));
|
||||
let h = attach(&mut s, other_line, &[x], json!({}));
|
||||
let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.moveMember", &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"member": path.0, "target": a.0})).contains("`member` must name an object attached"), "the path");
|
||||
assert!(err(&mut s, json!({"member": a.0, "target": path.0})).contains("`target` must name"), "the path as the target");
|
||||
assert!(err(&mut s, json!({"member": loose.0, "target": a.0})).contains("`member` must name"), "an object on no path");
|
||||
assert!(err(&mut s, json!({"member": g.0, "target": a.0})).contains("`member` must name"), "the group itself");
|
||||
assert!(err(&mut s, json!({"member": a.0, "target": x.0})).contains("same Objects on Path group"), "another group's object");
|
||||
assert!(err(&mut s, json!({"member": a.0, "target": b.0, "group": h.0})).contains("`group` must be"), "another group named");
|
||||
assert!(err(&mut s, json!({"target": b.0})).contains("missing `member`"));
|
||||
assert!(err(&mut s, json!({"member": a.0})).contains("missing `target`"));
|
||||
assert!(err(&mut s, json!({"member": 99999, "target": b.0})).contains("no such object"));
|
||||
assert!(err(&mut s, json!({"member": "a", "target": b.0})).contains("invalid object id"));
|
||||
// A locked object neither moves nor gives its place, and is not chosen.
|
||||
select(&mut s, &[c]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"member": c.0, "target": a.0})).contains("`member` names an object that is hidden or locked"));
|
||||
assert!(err(&mut s, json!({"member": a.0, "target": c.0})).contains("`target` names an object that is hidden or locked"));
|
||||
assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": c.0})).is_err());
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
// A locked object between the two keeps its place, and the others pass over it.
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let v = s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": c.0})).unwrap();
|
||||
assert_eq!(v["index"], 2);
|
||||
assert_eq!(orders(&s, g).0, [c, b, a]);
|
||||
assert_eq!(center(&s, b), Point::new(150.0, 300.0), "the locked object stays where it was");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).unwrap().locked);
|
||||
let e = err(&mut s, json!({"member": a.0, "target": b.0}));
|
||||
assert!(e.contains("hidden or locked"), "a locked group: {e}");
|
||||
assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": a.0})).is_err(), "a locked group's object is not chosen");
|
||||
assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused changed the order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_member_selects_the_group_with_the_object_chosen() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, _], path) = three_on_a_line(&mut s);
|
||||
let v = s.execute("object.objectsOnPath.selectMember", &json!({"member": b.0})).unwrap();
|
||||
assert_eq!(v, json!({"group": g.0, "member": b.0}));
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(b)));
|
||||
// Moving the chosen object keeps it chosen.
|
||||
s.execute("object.objectsOnPath.moveMember", &json!({"member": b.0, "target": a.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.on_path_member, Some(b));
|
||||
assert!(s.execute("object.objectsOnPath.selectMember", &json!({"member": path.0})).is_err());
|
||||
select(&mut s, &[g]);
|
||||
assert_eq!(s.doc().unwrap().selection.on_path_member, None, "another selection clears it");
|
||||
// Both take their objects without a selection.
|
||||
select(&mut s, &[]);
|
||||
s.execute("object.objectsOnPath.moveMember", &json!({"member": a.0, "target": b.0})).unwrap();
|
||||
assert_eq!(orders(&s, g).0[..2], [a, b]);
|
||||
s.execute("object.objectsOnPath.selectMember", &json!({"member": a.0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.on_path_member, Some(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_space_saves_and_reopens_and_goes_with_a_copy() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -464,6 +464,50 @@ fn a_turned_or_flat_diamond_expands_as_the_canvas_draws_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats or reflects expands, into objects or a mesh, as the canvas paints it:
|
||||
/// its stops repeated across the box, for each kind.
|
||||
#[test]
|
||||
fn a_spread_gradient_expands_as_the_canvas_paints_it() {
|
||||
for kind in ["linear", "radial", "conic", "diamond"] {
|
||||
for spread in ["repeat", "reflect"] {
|
||||
for to in [json!({"steps": 240}), json!({"gradient": "mesh"})] {
|
||||
let mut s = session();
|
||||
let gr = json!({"kind": kind, "spread": spread, "repeats": 3, "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]});
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", to.clone());
|
||||
let after = render(&s);
|
||||
// Where Repeat starts the stops again, the hard edge may land a pixel off.
|
||||
assert!(mean_diff(&before, &after) < 4.0, "{kind} {spread} {to}: {}", mean_diff(&before, &after));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats or reflects expands into the same whole number of objects in each run,
|
||||
/// so each run starts on an object's edge: a sharp step in the middle of each of 7 runs, expanded
|
||||
/// into about 15 objects (2 a run), lands where the canvas paints it.
|
||||
#[test]
|
||||
fn a_spread_gradient_expands_into_whole_bands_for_each_run() {
|
||||
let stops = json!([
|
||||
{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ffff00"},
|
||||
{"offset": 0.5, "color": "#004080"}, {"offset": 1, "color": "#004080"}
|
||||
]);
|
||||
for kind in ["linear", "conic"] {
|
||||
for spread in ["repeat", "reflect"] {
|
||||
let mut s = session();
|
||||
// A conic gradient turns about the box's center.
|
||||
let start = if kind == "conic" { [100, 100] } else { [30, 100] };
|
||||
let gr = json!({"kind": kind, "spread": spread, "repeats": 7, "start": start, "end": [170, 100], "stops": stops});
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({"steps": 15}));
|
||||
let after = render(&s);
|
||||
assert!(mean_diff(&before, &after) < 2.0, "{kind} {spread}: {}", mean_diff(&before, &after));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
|
||||
for gradient in [
|
||||
|
||||
@@ -515,7 +515,7 @@ fn the_document_info_report_has_every_category() {
|
||||
"OBJECTS",
|
||||
"GRAPHIC STYLES",
|
||||
"BRUSHES",
|
||||
"SPOT COLORS",
|
||||
"SPOT COLOR OBJECTS",
|
||||
"PATTERN OBJECTS",
|
||||
"GRADIENT OBJECTS",
|
||||
"SYMBOLS",
|
||||
|
||||
@@ -959,3 +959,202 @@ fn not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected() {
|
||||
assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 1);
|
||||
assert_eq!(selected_ids(&s), vec![inside]);
|
||||
}
|
||||
|
||||
/// Run Not Aligned to Pixel Grid with `before` selected, check that it makes no undo step and that
|
||||
/// its count is the number of objects it selected → the selected ids, sorted.
|
||||
fn not_aligned(s: &mut Session, before: &[u64]) -> Vec<u64> {
|
||||
s.execute("select.set", &json!({ "ids": before })).unwrap();
|
||||
let steps = undo_len(s);
|
||||
let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap();
|
||||
let ids = selected_ids(s);
|
||||
assert_eq!(r["count"], json!(ids.len()), "{r}");
|
||||
assert_eq!(undo_len(s), steps);
|
||||
ids
|
||||
}
|
||||
|
||||
fn sorted(mut ids: Vec<u64>) -> Vec<u64> {
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
/// What Select All selects, sorted.
|
||||
fn all_ids(s: &mut Session) -> Vec<u64> {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
selected_ids(s)
|
||||
}
|
||||
|
||||
fn kind(s: &Session, id: u64) -> NodeKind {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind.clone()
|
||||
}
|
||||
|
||||
/// Images, symbol instances, point type, area type and type on a path cannot take the property, so
|
||||
/// Not Aligned to Pixel Grid leaves them out though Select All selects them; the path a symbol was
|
||||
/// made from is the symbol's art, not an object of the document.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_leaves_out_images_symbol_instances_and_type() {
|
||||
let mut s = new_doc();
|
||||
let p = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0);
|
||||
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
|
||||
s.execute("file.place", &json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0].0;
|
||||
let art = path(&mut s, "M60.5 60 L80 60 L80 80 L60.5 80 Z", 1.0);
|
||||
let made = s.execute("symbol.new", &json!({"name": "Mark", "ids": [art]})).unwrap()["id"].as_u64().unwrap();
|
||||
let placed = s.execute("symbol.place", &json!({"name": "Mark", "x": 200.3, "y": 200.3})).unwrap()["id"].as_u64().unwrap();
|
||||
let point = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "point"})).unwrap()["id"].as_u64().unwrap();
|
||||
let frame = json!({"width": 80.5, "height": 40.5});
|
||||
let area = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "area", "area": frame})).unwrap()["id"].as_u64().unwrap();
|
||||
let on_path = path(&mut s, "M10.5 300 C100 250 200 350 300.5 300", 1.0);
|
||||
let on_path = s.execute("text.createInPath", &json!({"path": on_path, "mode": "onPath", "text": "on a path"})).unwrap()["id"].as_u64().unwrap();
|
||||
let in_path = path(&mut s, "M250.5 20.5 L350 20.5 L350 90 L250.5 90 Z", 1.0);
|
||||
let in_path = s.execute("text.createInPath", &json!({"path": in_path, "mode": "area", "text": "in a path"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(matches!(kind(&s, image), NodeKind::Image(_)));
|
||||
for id in [made, placed] {
|
||||
assert!(matches!(kind(&s, id), NodeKind::SymbolInstance { .. }), "{id}");
|
||||
}
|
||||
for id in [point, area, on_path, in_path] {
|
||||
assert!(matches!(kind(&s, id), NodeKind::Text(_)), "{id}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(art)).is_none());
|
||||
assert_eq!(all_ids(&mut s), sorted(vec![p, image, made, placed, point, area, on_path, in_path]));
|
||||
assert_eq!(not_aligned(&mut s, &[image, made, point]), vec![p]);
|
||||
// With the path aligned, nothing is left to select.
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [p]})).unwrap();
|
||||
assert_eq!(not_aligned(&mut s, &[placed]), Vec::<u64>::new());
|
||||
}
|
||||
|
||||
/// Paths on a template layer, in a hidden or locked sublayer or on a locked artboard are left out,
|
||||
/// as Select All leaves them out; paths in an unlocked visible sublayer are selected.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_leaves_out_template_layers_locked_sublayers_and_locked_artboards() {
|
||||
let mut s = new_doc();
|
||||
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
let main = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let free = path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0);
|
||||
let on_locked_board = path(&mut s, "M510 10 L520 10 L520 20 L510 20 Z", 1.0);
|
||||
let template = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap();
|
||||
let traced = path(&mut s, "M30 10 L40 10 L40 20 L30 20 Z", 1.0);
|
||||
s.execute("layer.setProps", &json!({"id": template, "template": true})).unwrap();
|
||||
let sub = |s: &mut Session, name: &str, d: &str| {
|
||||
let l = s.execute("layer.newSublayer", &json!({"parent": main, "name": name})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.setCurrent", &json!({"id": l})).unwrap();
|
||||
(l, path(s, d, 1.0))
|
||||
};
|
||||
let (_, in_sublayer) = sub(&mut s, "Open", "M50 10 L60 10 L60 20 L50 20 Z");
|
||||
let (hidden, in_hidden) = sub(&mut s, "Hidden", "M70 10 L80 10 L80 20 L70 20 Z");
|
||||
let (locked, in_locked) = sub(&mut s, "Locked", "M90 10 L100 10 L100 20 L90 20 Z");
|
||||
s.execute("layer.setProps", &json!({"id": hidden, "visible": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": locked, "locked": true})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let all = all_ids(&mut s);
|
||||
for id in [traced, in_hidden, in_locked, on_locked_board] {
|
||||
assert!(!all.contains(&id), "{id}");
|
||||
}
|
||||
assert_eq!(not_aligned(&mut s, &[free]), sorted(vec![free, in_sublayer]));
|
||||
// Unlocked, the artboard's path is selected again.
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": false})).unwrap();
|
||||
assert_eq!(not_aligned(&mut s, &[free]), sorted(vec![free, in_sublayer, on_locked_board]));
|
||||
}
|
||||
|
||||
/// A clipping path and the paths it clips are selected, not their clip group; a path with a drop
|
||||
/// shadow or a Gaussian Blur is selected as the path it is, and its effects are not objects.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_selects_clipping_paths_and_paths_with_effects() {
|
||||
let mut s = new_doc();
|
||||
let clipped = path(&mut s, "M10.5 10 L60 10 L60 60 L10.5 60 Z", 1.0);
|
||||
let clip = path(&mut s, "M20.5 20 L50 20 L50 50 L20.5 50 Z", 1.0);
|
||||
s.execute("select.set", &json!({"ids": [clipped, clip]})).unwrap();
|
||||
let group = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let shadowed = path(&mut s, "M100.5 10 L150 10 L150 60 L100.5 60 Z", 1.0);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [shadowed]})).unwrap();
|
||||
let blurred = path(&mut s, "M200.5 10 L250 10 L250 60 L200.5 60 Z", 1.0);
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "params": {"radius": 3}, "ids": [blurred]})).unwrap();
|
||||
assert!(matches!(kind(&s, group), NodeKind::Group { .. }));
|
||||
for id in [shadowed, blurred] {
|
||||
assert!(!s.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects.is_empty(), "{id}");
|
||||
}
|
||||
let want = sorted(vec![clipped, clip, shadowed, blurred]);
|
||||
assert_eq!(not_aligned(&mut s, &[group]), want);
|
||||
// Object › Align to Pixel Grid takes each object selected; then nothing is left to select.
|
||||
s.execute("object.setPixelAligned", &json!({"ids": want})).unwrap();
|
||||
assert_eq!(not_aligned(&mut s, &[group]), Vec::<u64>::new());
|
||||
}
|
||||
|
||||
/// The filter looks into blends, envelopes, repeats and Intertwine groups and selects the paths
|
||||
/// they are made of, not the objects that hold them; Align to Pixel Grid takes that selection, and
|
||||
/// then nothing is left to select.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_selects_the_paths_of_blends_envelopes_repeats_and_intertwines() {
|
||||
let mut s = new_doc();
|
||||
let b1 = path(&mut s, "M10.5 10 L30 10 L30 30 L10.5 30 Z", 1.0);
|
||||
let b2 = path(&mut s, "M80.5 10 L100 10 L100 30 L80.5 30 Z", 1.0);
|
||||
s.execute("select.set", &json!({"ids": [b1, b2]})).unwrap();
|
||||
let blend = s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let warped = path(&mut s, "M10.5 100 L100 100 L100 150 L10.5 150 Z", 1.0);
|
||||
let envelope = s.execute("object.envelope.makeWithWarp", &json!({"ids": [warped]})).unwrap()["id"].as_u64().unwrap();
|
||||
let tile = path(&mut s, "M200.5 10 L220 10 L220 30 L200.5 30 Z", 1.0);
|
||||
let repeat = s.execute("object.repeat.grid", &json!({"ids": [tile], "rows": 2, "cols": 2})).unwrap()["id"].as_u64().unwrap();
|
||||
let i1 = path(&mut s, "M200.5 200 L260 200 L260 230 L200.5 230 Z", 1.0);
|
||||
let i2 = path(&mut s, "M220.5 180 L240 180 L240 250 L220.5 250 Z", 1.0);
|
||||
let intertwine = s.execute("object.intertwine.make", &json!({"ids": [i1, i2]})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(matches!(kind(&s, blend), NodeKind::Blend { .. }));
|
||||
assert!(matches!(kind(&s, envelope), NodeKind::Envelope { .. }));
|
||||
assert!(matches!(kind(&s, repeat), NodeKind::Repeat(_)));
|
||||
assert!(matches!(kind(&s, intertwine), NodeKind::Intertwine { .. }));
|
||||
let want = sorted(vec![b1, b2, warped, tile, i1, i2]);
|
||||
assert_eq!(not_aligned(&mut s, &[blend, envelope]), want);
|
||||
s.execute("object.setPixelAligned", &json!({})).unwrap();
|
||||
for id in &want {
|
||||
assert!(aligned(&s, *id), "{id}");
|
||||
}
|
||||
assert_eq!(not_aligned(&mut s, &[repeat, intertwine]), Vec::<u64>::new());
|
||||
}
|
||||
|
||||
/// Gradient meshes, placed documents and ruler guides are left out; a live shape is a path and is
|
||||
/// selected.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_leaves_out_meshes_placed_documents_and_guides_but_takes_live_shapes() {
|
||||
let mut s = new_doc();
|
||||
let filled = path(&mut s, "M10.5 10 L60 10 L60 60 L10.5 60 Z", 1.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap();
|
||||
let mesh = s.execute("object.mesh.create", &json!({"ids": [filled], "rows": 2, "cols": 2})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let dir = crate::tests_links::Folder::new("pixelalign-placed");
|
||||
let file = dir.file("placed.vectorcraft");
|
||||
let mut d = vectorcraft_doc::Document::new(50.0, 50.0);
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.5, 0.5, 40.0, 40.0));
|
||||
let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(20, 20, 230));
|
||||
let look = vectorcraft_doc::Appearance::basic(paint, vectorcraft_color::Paint::None, 0.0);
|
||||
d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap();
|
||||
crate::tests_links::write(&file, &vectorcraft_format::save_file(&d));
|
||||
let placed = s.execute("file.place", &json!({"path": file, "at": [200, 200]})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let guide = path(&mut s, "M0 300.5 L400 300.5", 1.0);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let live = s.execute("shape.rectangle", &json!({"x": 100.3, "y": 20.6, "width": 30.4, "height": 9.7})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(matches!(kind(&s, mesh), NodeKind::Mesh(_)));
|
||||
assert!(matches!(kind(&s, placed), NodeKind::PlacedDocument(_)));
|
||||
assert!(matches!(kind(&s, guide), NodeKind::Path { guide: true, .. }));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(live)).unwrap().live_shape().is_some());
|
||||
let all = all_ids(&mut s);
|
||||
assert!(all.contains(&mesh) && all.contains(&placed), "{all:?}");
|
||||
assert_eq!(not_aligned(&mut s, &[mesh, placed]), vec![live]);
|
||||
}
|
||||
|
||||
/// A compound path goes by its own property, whatever the property of the paths in it (a file can
|
||||
/// hold paths with the property on inside a compound path): off, it is selected as one object and
|
||||
/// the paths in it are not; on, it is not selected, though a path in it has the property off.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() {
|
||||
let mut s = new_doc();
|
||||
let on = path(&mut s, "M10.5 10 L30 10 L30 30 L10.5 30 Z", 1.0);
|
||||
let off = path(&mut s, "M50.5 10 L70 10 L70 30 L50.5 30 Z", 1.0);
|
||||
s.execute("select.set", &json!({"ids": [on, off]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(on)).unwrap().extras_mut().pixel_aligned = true;
|
||||
assert!(aligned(&s, on) && !aligned(&s, off) && !aligned(&s, compound));
|
||||
let other = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0);
|
||||
assert_eq!(not_aligned(&mut s, &[other]), sorted(vec![compound, other]));
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [compound]})).unwrap();
|
||||
assert!(!aligned(&s, off));
|
||||
assert_eq!(not_aligned(&mut s, &[compound]), vec![other]);
|
||||
}
|
||||
@@ -505,6 +505,30 @@ fn a_painted_group_effect_links_to_the_document_s_swatches() {
|
||||
assert_eq!((img.pixel(50, 50), img.pixel(15, 15)), (GREEN, WHITE), "the group's piece, green");
|
||||
}
|
||||
|
||||
/// A painted effect on a group leaves the group's art as it is when a path in it has a linked
|
||||
/// opacity mask, which can't take the pieces as the path does: the mask still covers the path.
|
||||
#[test]
|
||||
fn a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, "#ff0000");
|
||||
let m = rect(&mut s, 10.0, "#ffffff");
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, m.0]}));
|
||||
run(&mut s, "transparency.makeOpacityMask", json!({}));
|
||||
rect(&mut s, 100.0, "#0000ff");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
let out = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#00ff00")]}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&painting("test.engine.maskedpaint", true), &out));
|
||||
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "plugin.test.engine.maskedpaint"}));
|
||||
let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, g)).unwrap();
|
||||
let mut masked = vec![];
|
||||
art.walk(&mut |c| masked.extend(c.extras().mask.as_ref().map(|k| (c.geometric_bounds(), k.art.geometric_bounds()))));
|
||||
assert!(!masked.is_empty(), "the masked path");
|
||||
for (path, mask) in masked {
|
||||
assert_eq!(path, mask, "the mask covers the path");
|
||||
}
|
||||
}
|
||||
|
||||
/// The output of a painted effect that returns one green square linked to swatch `Leaf`.
|
||||
fn leaf_square() -> String {
|
||||
let mut leaf = solid("#00ff00");
|
||||
@@ -1433,6 +1457,92 @@ fn plugins_folder_set_again_after_clearing_installs_its_plugins() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Under automation read roots, `plugin.list` names the plug-in folder last loaded, its failed
|
||||
/// files and a plug-in's source file only inside them: a folder outside is `null`, and a file
|
||||
/// outside is named by its file name.
|
||||
#[test]
|
||||
fn plugin_list_leaves_out_paths_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let base = crate::tests_links::Folder::new("plugin-list-read-root");
|
||||
let (inside, outside) = (base.0.join("in"), base.0.join("out"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let id = "test.engine.listroots";
|
||||
let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#);
|
||||
std::fs::write(outside.join("hidden.wasm"), wat::parse_str(src).unwrap()).unwrap();
|
||||
std::fs::write(outside.join("broken.wasm"), b"\0asm?").unwrap();
|
||||
let folder = outside.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "plugin.reload", json!({"path": folder}));
|
||||
assert_eq!(r["loaded"], json!([id]), "{r}");
|
||||
let broken = outside.join("broken.wasm").to_string_lossy().to_string();
|
||||
let source = outside.join("hidden.wasm").to_string_lossy().to_string();
|
||||
let entry = |list: &Value| list["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).cloned().unwrap();
|
||||
|
||||
// The person sees the paths.
|
||||
let person = run(&mut s, "plugin.list", json!({}));
|
||||
assert_eq!((&person["folder"]["folder"], &person["folder"]["failed"][0]["file"]), (&json!(folder), &json!(broken)), "{person}");
|
||||
assert_eq!(entry(&person)["source"], json!(source));
|
||||
|
||||
// The client sees their names.
|
||||
let roots = AutomationRoots::new(&[&inside], &[]).unwrap();
|
||||
let listed = confine(roots.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap();
|
||||
let report = &listed["folder"];
|
||||
assert_eq!((&report["folder"], &report["loaded"], &report["failed"][0]["file"]), (&Value::Null, &json!([id]), &json!("broken.wasm")), "{listed}");
|
||||
assert_eq!(entry(&listed)["source"], "hidden.wasm");
|
||||
let info = confine(roots.as_ref(), || s.execute("plugin.info", &json!({"id": id}))).unwrap();
|
||||
assert_eq!(info["source"], "hidden.wasm");
|
||||
let outside_text = json!(folder).to_string();
|
||||
for reply in [&listed, &info] {
|
||||
assert!(!reply.to_string().contains(outside_text.trim_matches('"')), "no path outside the root: {reply}");
|
||||
}
|
||||
|
||||
// A read root holding the folder shows it whole.
|
||||
let wider = AutomationRoots::new(&[&outside], &[]).unwrap();
|
||||
let listed = confine(wider.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap();
|
||||
assert_eq!(listed["folder"]["folder"], json!(folder), "{listed}");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Under automation read roots, a plug-in turned off for the next launch is listed with a file
|
||||
/// outside them named by its file name, and `plugin.setEnabled` turns it on by that name.
|
||||
#[test]
|
||||
fn disabled_plugins_name_files_outside_the_read_root_by_their_names() {
|
||||
if !in_own_process("disabled_plugins_name_files_outside_the_read_root_by_their_names") {
|
||||
return;
|
||||
}
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
let base = crate::tests_links::Folder::new("plugin-disabled-read-root");
|
||||
let (inside, outside) = (base.0.join("in"), base.0.join("out"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let id = "test.engine.disabledroots";
|
||||
let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#);
|
||||
let file = outside.join("off.wasm");
|
||||
std::fs::write(&file, wat::parse_str(src).unwrap()).unwrap();
|
||||
let file = file.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
run(&mut s, "plugin.install", json!({"path": file}));
|
||||
let roots = AutomationRoots::new(&[&inside], &[]).unwrap();
|
||||
// The client turns it off by the source plugin.list shows.
|
||||
let listed = confine(roots.as_ref(), || s.execute("plugin.list", &json!({}))).unwrap();
|
||||
let source = listed["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap()["source"].clone();
|
||||
assert_eq!(source, "off.wasm", "{listed}");
|
||||
confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": source, "enabled": false}))).unwrap();
|
||||
assert_eq!(run(&mut s, "plugin.safeMode", json!({}))["disabled"][0]["file"], json!(file), "the person sees the path");
|
||||
|
||||
let outside_text = json!(outside.to_string_lossy()).to_string();
|
||||
for cmd in ["plugin.list", "plugin.safeMode"] {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &json!({}))).unwrap();
|
||||
assert_eq!(r["disabled"][0]["file"], "off.wasm", "{cmd}: {r}");
|
||||
assert!(!r.to_string().contains(outside_text.trim_matches('"')), "{cmd}: no path outside the root: {r}");
|
||||
}
|
||||
let r = confine(roots.as_ref(), || s.execute("plugin.setEnabled", &json!({"file": "off.wasm", "enabled": true}))).unwrap();
|
||||
assert_eq!((&r["changed"], &r["disabled"]), (&json!(true), &json!([])), "{r}");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// #2541: a plug-in installed in a session with a plug-in store is installed again in the next
|
||||
/// session that attaches the store, and Remove Plug-in takes it out of the store.
|
||||
#[test]
|
||||
|
||||
@@ -1545,6 +1545,71 @@ impl RecoveryStore for DiesAfterDocument {
|
||||
}
|
||||
}
|
||||
|
||||
/// Under automation read roots, `file.recovery.save`, `file.recovery.list` and
|
||||
/// `file.recovery.restore` name a document's file and the recovery folder only inside them.
|
||||
#[test]
|
||||
fn recovery_replies_leave_out_paths_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
use serde_json::Value;
|
||||
let base = crate::tests_links::Folder::new("recovery-read-root");
|
||||
let (inside, outside) = (base.0.join("in"), base.0.join("out"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let store: Arc<dyn RecoveryStore> = Arc::new(FolderStore::new(outside.join("recovery")));
|
||||
let location = outside.join("recovery").to_string_lossy().to_string();
|
||||
let kept = inside.join("kept.vectorcraft").to_string_lossy().to_string();
|
||||
let hidden = outside.join("hidden.vectorcraft").to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.recovery.set_store(store.clone());
|
||||
for path in [&kept, &hidden] {
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("file.saveAs", &json!({"path": path})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
}
|
||||
let roots = AutomationRoots::new(&[&inside], &[]).unwrap();
|
||||
let saved = confine(roots.as_ref(), || s.execute("file.recovery.save", &json!({}))).unwrap();
|
||||
assert_eq!(saved["location"], Value::Null, "{saved}");
|
||||
s.execute("shape.ellipse", &json!({"x": 80, "y": 20, "width": 20, "height": 20})).unwrap();
|
||||
assert_eq!(s.execute("file.recovery.save", &json!({})).unwrap()["location"], json!(location), "the person sees the folder");
|
||||
|
||||
let sorted = |v: &Value, key: &str| -> Vec<String> {
|
||||
let mut out: Vec<String> = v[key].as_array().unwrap().iter().map(|c| c["path"].to_string()).collect();
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
let both = |first: Value| {
|
||||
let mut out = vec![first.to_string(), json!(kept).to_string()];
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
assert_eq!(sorted(&s.execute("file.recovery.list", &json!({})).unwrap(), "copies"), both(json!(hidden)));
|
||||
let listed = confine(roots.as_ref(), || s.execute("file.recovery.list", &json!({}))).unwrap();
|
||||
assert_eq!((sorted(&listed, "copies"), &listed["location"]), (both(Value::Null), &Value::Null), "{listed}");
|
||||
let outside_text = json!(outside.to_string_lossy()).to_string();
|
||||
assert!(!listed.to_string().contains(outside_text.trim_matches('"')), "no path outside the root: {listed}");
|
||||
// A relative recovery folder is checked as the file system reads it; a store that is no folder
|
||||
// keeps its name.
|
||||
let mut relative = Session::new();
|
||||
relative.recovery.set_store(Arc::new(FolderStore::new("vc-recovery-relative-folder")));
|
||||
let l = confine(roots.as_ref(), || relative.execute("file.recovery.list", &json!({}))).unwrap();
|
||||
assert_eq!(l["location"], Value::Null, "{l}");
|
||||
let (mut memory, _) = session();
|
||||
let l = confine(roots.as_ref(), || memory.execute("file.recovery.list", &json!({}))).unwrap();
|
||||
assert_eq!(l["location"], "memory", "{l}");
|
||||
|
||||
// After a crash, the copies restored.
|
||||
drop(s);
|
||||
let mut s = Session::new();
|
||||
s.recovery.set_store(store.clone());
|
||||
let r = confine(roots.as_ref(), || s.execute("file.recovery.restore", &json!({}))).unwrap();
|
||||
assert_eq!(sorted(&r, "restored"), both(Value::Null), "{r}");
|
||||
let mut opened: Vec<Option<String>> = s.documents().iter().map(|d| d.path.clone()).collect();
|
||||
opened.sort();
|
||||
let mut files = vec![Some(hidden), Some(kept)];
|
||||
files.sort();
|
||||
assert_eq!(opened, files, "the documents keep their files");
|
||||
}
|
||||
|
||||
/// A crash between writing a copy's document and its details restores the new document with
|
||||
/// every image, the one placed since the last copy too (and the first copy likewise).
|
||||
#[test]
|
||||
|
||||
@@ -265,3 +265,31 @@ fn the_slowest_commands_are_the_longest_in_all_then_by_id() {
|
||||
assert_eq!(ids, ["b.two", "a.one", "c.three", "f", "e"]);
|
||||
assert_eq!((slow[0].calls, slow[0].total_ms, slow[0].max_ms), (3, 9, 4));
|
||||
}
|
||||
|
||||
/// Under automation read roots, the error lines of a failed run name the included file it stopped
|
||||
/// in by its file name also when the console cut a line inside the file's path.
|
||||
#[test]
|
||||
fn a_cut_error_line_leaves_out_an_included_files_folder_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
let base = crate::tests_links::Folder::new("script-report-cut-line");
|
||||
let inside = base.0.join("in");
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
// A path longer than a console line, as the report of a failed run names it.
|
||||
let file = base.0.join("out").join("d".repeat(MAX_LINE_BYTES)).join("bad.jsxinc").to_string_lossy().to_string();
|
||||
let mut report = json!({"ok": false, "name": "t.js", "file": file, "line": 2, "column": 7, "message": format!("Error: stopped\nin {file}")});
|
||||
let error = script::error_lines(&report);
|
||||
assert!(error.len() == 2 && error.iter().all(|l| l.len() <= MAX_LINE_BYTES && l.ends_with(CUT_MARK)), "both lines are cut: {error:?}");
|
||||
let written: Vec<String> = std::iter::once("written by the script".to_string()).chain(error).collect();
|
||||
report["console"] = json!({"lines": written, "droppedLines": 0, "truncatedLines": 2});
|
||||
let mut s = Session::new();
|
||||
s.script_report = Some(report.clone());
|
||||
|
||||
let roots = AutomationRoots::new(&[&inside], &[]).unwrap();
|
||||
let shown = confine(roots.as_ref(), || s.shown_script_report()).unwrap();
|
||||
assert_eq!((&shown["file"], &shown["message"]), (&json!("bad.jsxinc"), &json!("Error: stopped\nin bad.jsxinc")), "{shown}");
|
||||
assert_eq!(shown["console"]["lines"], json!(["written by the script", "t.js: bad.jsxinc:2:7: Error: stopped", "in bad.jsxinc"]), "{shown}");
|
||||
let outside = json!(base.0.join("out").to_string_lossy()).to_string();
|
||||
assert!(!shown.to_string().contains(outside.trim_matches('"')), "no path outside the root: {shown}");
|
||||
// The person sees the report as it is.
|
||||
assert_eq!(s.shown_script_report(), Some(report));
|
||||
}
|
||||
@@ -230,7 +230,7 @@ fn script_file_link_escape_refused() {
|
||||
/// not matter, and outside it where case matters, whether or not the file is there.
|
||||
#[test]
|
||||
fn script_file_case_variant_folder() {
|
||||
let base = folder("case");
|
||||
let base = crate::cmd::findfiles::plain(folder("case").canonicalize().unwrap());
|
||||
write(&base.join("main/own.txt"), b"own");
|
||||
let upper = base.join("MAIN");
|
||||
let source = |name: &str| {
|
||||
|
||||
@@ -844,7 +844,7 @@ fn a_grit_texture_adds_once_undoes_and_saves() {
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let ids: Vec<&str> =
|
||||
list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["geometric-patterns", "grit-textures"]);
|
||||
assert_eq!(ids, ["geometric-patterns", "grit-textures", "optical-effects"]);
|
||||
let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"}));
|
||||
let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]);
|
||||
@@ -869,6 +869,49 @@ fn a_grit_texture_adds_once_undoes_and_saves() {
|
||||
assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").map(|w| &w.paint));
|
||||
}
|
||||
|
||||
/// Optical Effects is listed after Grit Textures, and reading it adds nothing. Clicking one of
|
||||
/// its patterns brings it with its swatch and fills the selection with it, once, as one undo step
|
||||
/// that also takes both away, and both stay after a save and reopen.
|
||||
#[test]
|
||||
fn an_optical_effect_adds_once_fills_undoes_and_saves() {
|
||||
let mut s = session();
|
||||
let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count());
|
||||
let empty = counts(doc(&s));
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let ids: Vec<&str> =
|
||||
list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["geometric-patterns", "grit-textures", "optical-effects"]);
|
||||
let got = run(&mut s, "swatch.library.get", json!({"library": "Optical Effects"}));
|
||||
let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
["Sine Bands", "Ripple Lines", "Interference Rings", "Offset Rings", "Warped Checks", "Pinched Stripes", "Chevron Pulse", "Radiating Lenses"]
|
||||
);
|
||||
assert_eq!(counts(doc(&s)), empty, "reading a library adds no pattern or swatch");
|
||||
let id = vectorcraft_doc::NodeId(run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap());
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "optical-effects", "names": ["Warped Checks"], "apply": "fill"}));
|
||||
assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Warped Checks"]), json!("Warped Checks")));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1));
|
||||
let def = doc(&s).pattern("Warped Checks").expect("the pattern comes with its swatch").clone();
|
||||
assert_eq!(def.art.len(), 32, "the black cells of an 8 × 8 checkerboard");
|
||||
assert!(matches!(doc(&s).swatch("Warped Checks").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Warped Checks"));
|
||||
let filled = |d: &vectorcraft_doc::Document| matches!(d.node(id).unwrap().appearance.fill_paint(), Paint::Pattern { pattern, .. } if pattern == "Warped Checks");
|
||||
assert!(filled(doc(&s)));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "optical-effects", "names": ["Warped Checks"]}));
|
||||
assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Warped Checks"])));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(counts(doc(&s)), empty);
|
||||
assert!(doc(&s).pattern("Warped Checks").is_none() && doc(&s).swatch("Warped Checks").is_none() && !filled(doc(&s)));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert!(filled(doc(&s)));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap();
|
||||
assert_eq!(back.pattern("Warped Checks"), Some(&def));
|
||||
assert_eq!(back.swatch("Warped Checks").map(|w| &w.paint), doc(&s).swatch("Warped Checks").map(|w| &w.paint));
|
||||
assert!(filled(&back));
|
||||
}
|
||||
|
||||
/// A device name is saved with a `-` after it, which can be another library's own name: neither
|
||||
/// library replaces the other, and saving either again replaces only itself.
|
||||
#[test]
|
||||
|
||||
@@ -526,6 +526,51 @@ fn distort_command_maps_corners() {
|
||||
assert!(close(bounds(&s, a), Rect::new(0.0, 0.0, 100.0, 100.0)));
|
||||
}
|
||||
|
||||
/// Free Distort warps the art of a linked opacity mask with the object it masks, and one undo puts
|
||||
/// both back; an unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn distort_command_warps_a_linked_opacity_mask_with_its_object() {
|
||||
for linked in [true, false] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
if !linked {
|
||||
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
|
||||
}
|
||||
let mask_path = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.path_data().cloned();
|
||||
let path = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().path_data().cloned();
|
||||
let before = (path(&s), mask_path(&s));
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 0], [90, 0], [100, 100], [0, 100]]})).unwrap();
|
||||
assert!(path(&s) != before.0);
|
||||
let want = if linked { path(&s) } else { before.1.clone() };
|
||||
assert_eq!(mask_path(&s), want, "linked: {linked}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((path(&s), mask_path(&s)), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// Free Distort of a group warps the linked opacity mask of a path inside it with the path.
|
||||
#[test]
|
||||
fn distort_command_warps_the_linked_mask_of_a_path_in_a_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 150.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let before = s.doc().unwrap().doc.node(a).unwrap().path_data().cloned();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[10, 0], [190, 0], [200, 100], [0, 100]]})).unwrap();
|
||||
let a = s.doc().unwrap().doc.node(a).unwrap();
|
||||
assert!(a.path_data().cloned() != before, "the path is warped");
|
||||
assert_eq!(a.extras().mask.as_ref().unwrap().art.path_data(), a.path_data(), "and so is its mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distort_perspective_midpoint_is_projective() {
|
||||
// Distort a tiny probe at the centre of a 100×100 source box into a trapezoid: with a real
|
||||
|
||||
@@ -1142,8 +1142,11 @@ impl Session {
|
||||
let place = w.show.then_some(WidgetPlace { screen: view.screen.as_ref(), corner: w.position });
|
||||
v.splice(0..0, vectorcraft_tools::distort::perspective::grid_overlays_in(&d.doc, 1.0 / view.zoom.max(1e-9), place));
|
||||
}
|
||||
// Global Edit: the objects edited with the selected one are highlighted.
|
||||
for (path, color) in crate::cmd::globaledit::highlights(self) {
|
||||
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
|
||||
// with the Selection tool, the objects it would take.
|
||||
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
|
||||
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
|
||||
for (path, color) in shown {
|
||||
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
|
||||
}
|
||||
if let Some((cmd, p)) = deferred_preview {
|
||||
|
||||
@@ -9,11 +9,11 @@ use vectorcraft_engine::{Session, command_specs};
|
||||
use vectorcraft_testkit::catch_quiet;
|
||||
use vectorcraft_testkit::fixtures::Fixture;
|
||||
use vectorcraft_testkit::invariants::{check_all, check_session, doc_json};
|
||||
use vectorcraft_testkit::strategies::{junk_params, junk_values, param_keys, safe_value};
|
||||
use vectorcraft_testkit::strategies::{command_param_keys, junk_params_for_command, junk_values, param_keys, safe_value_for_command};
|
||||
|
||||
/// Commands that replace/close the active document or touch the filesystem are fine to call, but a
|
||||
/// few need their file and folder params redirected into a temp dir (`safe_value`, which
|
||||
/// `junk_params` applies).
|
||||
/// Commands that replace/close the active document or touch the filesystem are fine to call, but
|
||||
/// their file and folder params are redirected into a temp dir (`safe_value_for_command`, which
|
||||
/// `junk_params_for_command` applies, by the keys the command catalog names as files and folders).
|
||||
fn safe_path() -> String {
|
||||
vectorcraft_testkit::temp_dir("sweep").join("out.bin").to_string_lossy().to_string()
|
||||
}
|
||||
@@ -190,6 +190,33 @@ fn heavy(id: &str) -> bool {
|
||||
id.starts_with("document.serialize") || id.starts_with("document.export") || id == "document.open"
|
||||
}
|
||||
|
||||
/// Is `p` a params object with `k` as its only key?
|
||||
fn sends_alone(p: &Value, k: &str) -> bool {
|
||||
p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key(k))
|
||||
}
|
||||
|
||||
/// The junk params the sweeps send `c`: all of them, or for a [`heavy`] command the first 12 and,
|
||||
/// for each key the command catalog names as a file or folder that no case among those sends alone
|
||||
/// ([`sends_alone`]), the first case that sends a string under it alone (or any value when none
|
||||
/// does).
|
||||
fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
|
||||
let mut cases = junk_params_for_command(c, path);
|
||||
if heavy(c.id) {
|
||||
let rest = cases.split_off(cases.len().min(12));
|
||||
for (k, _) in vectorcraft_engine::cmd::location_keys(c) {
|
||||
if cases.iter().any(|p| sends_alone(p, k)) {
|
||||
continue;
|
||||
}
|
||||
let alone = || rest.iter().filter(|p| sends_alone(p, k));
|
||||
let found = alone().find(|p| p.get(k).is_some_and(Value::is_string)).or_else(|| alone().next());
|
||||
if let Some(p) = found {
|
||||
cases.push(p.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_with_junk_params() {
|
||||
let path = safe_path();
|
||||
@@ -197,10 +224,7 @@ fn every_command_with_junk_params() {
|
||||
let mut calls = 0usize;
|
||||
for fx in Fixture::ALL {
|
||||
for c in command_specs() {
|
||||
let mut cases = junk_params(c.params, &path);
|
||||
if heavy(c.id) {
|
||||
cases.truncate(12);
|
||||
}
|
||||
let cases = junk_cases(c, &path);
|
||||
for p in &cases {
|
||||
calls += 1;
|
||||
if let Some(f) = probe(fx, c.id, p) {
|
||||
@@ -234,13 +258,10 @@ fn tool_edit_state(s: &Session) -> ToolEditState {
|
||||
/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and
|
||||
/// off, with a string under a file or folder key replaced by a location inside `path`'s folder.
|
||||
fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
|
||||
let mut cases = junk_params(c.params, path);
|
||||
if heavy(c.id) {
|
||||
cases.truncate(12);
|
||||
}
|
||||
for k in param_keys(c.params) {
|
||||
let mut cases = junk_cases(c, path);
|
||||
for k in command_param_keys(c) {
|
||||
for v in [json!(true), json!(false), json!(1), json!("on")] {
|
||||
cases.push(json!({ k.as_str(): safe_value(&k, &v, path) }));
|
||||
cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) }));
|
||||
}
|
||||
}
|
||||
// Find Objects selects only with a filter, which one key at a time does not give it.
|
||||
@@ -250,35 +271,109 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value
|
||||
cases
|
||||
}
|
||||
|
||||
/// Every string the sweeps send under a key that names a file or folder to write is inside the
|
||||
/// sweep's temp folder, so no run writes into the working directory.
|
||||
/// The strings in `v`, the value at `at` in a case of command `id`, that name a place on disk
|
||||
/// outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when `named` (it is
|
||||
/// under a key that names a file or folder), and in objects at any depth, the values under such
|
||||
/// keys ([`names_location`]).
|
||||
fn outside_locations(id: &str, at: &str, v: &Value, named: bool, dir: &std::path::Path, out: &mut std::collections::BTreeSet<String>) {
|
||||
match v {
|
||||
Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => {
|
||||
out.insert(format!("{id} {at}: {v}"));
|
||||
}
|
||||
Value::Array(a) => {
|
||||
for (i, x) in a.iter().enumerate() {
|
||||
outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out);
|
||||
}
|
||||
}
|
||||
Value::Object(o) => {
|
||||
for (k, x) in o {
|
||||
outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `key` name a file or folder, in command `spec` when given: a key in
|
||||
/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps
|
||||
/// for `spec`.
|
||||
fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool {
|
||||
match spec {
|
||||
Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(),
|
||||
None => vectorcraft_engine::cmd::key_location(key).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every string the sweeps send under a key that names a file or folder, in the command catalog
|
||||
/// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside
|
||||
/// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or
|
||||
/// writes in the working directory. `every_command_with_junk_params` sends every such key of every
|
||||
/// command alone in at least one case ([`junk_cases`]).
|
||||
#[test]
|
||||
fn sweep_cases_name_files_only_inside_the_temp_folder() {
|
||||
let path = safe_path();
|
||||
let dir = vectorcraft_testkit::temp_dir("sweep");
|
||||
let keys = ["path", "diffPath", "folder", "destinationFolder"];
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut unsent = vec![];
|
||||
let mut outside = std::collections::BTreeSet::new();
|
||||
for c in command_specs() {
|
||||
let mut cases = junk_params(c.params, &path);
|
||||
let keys = vectorcraft_engine::cmd::location_keys(c);
|
||||
let run = junk_cases(c, &path);
|
||||
for (k, _) in &keys {
|
||||
if !run.iter().any(|p| sends_alone(p, k)) {
|
||||
unsent.push(format!("{} {k}", c.id));
|
||||
}
|
||||
}
|
||||
let mut cases = junk_params_for_command(c, &path);
|
||||
cases.extend(tool_edit_cases(c, &path));
|
||||
cases.extend(serializable_cases(c, &path));
|
||||
for p in &cases {
|
||||
let Some(o) = p.as_object() else { continue };
|
||||
for (k, v) in o.iter().filter(|(k, _)| keys.contains(&k.as_str())) {
|
||||
seen.insert(k.clone());
|
||||
if let Some(s) = v.as_str()
|
||||
&& !std::path::Path::new(s).starts_with(&dir)
|
||||
{
|
||||
outside.insert(format!("{} {{\"{k}\": {v}}}", c.id));
|
||||
}
|
||||
for (k, v) in o {
|
||||
outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(seen.len(), keys.len(), "the sweeps send only {seen:?}");
|
||||
assert!(unsent.is_empty(), "every_command_with_junk_params sends no case for {unsent:?}");
|
||||
let outside: Vec<String> = outside.into_iter().collect();
|
||||
assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n"));
|
||||
}
|
||||
|
||||
/// The cases sweep keys the command catalog names as files and folders: `document.open`'s
|
||||
/// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s
|
||||
/// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s
|
||||
/// `paths: [{ids, path}]`, each with a string in the temp folder, and a folder key a folder there.
|
||||
#[test]
|
||||
fn sweep_cases_send_the_file_keys_of_the_command_catalog() {
|
||||
let path = safe_path();
|
||||
let dir = vectorcraft_testkit::temp_dir("sweep");
|
||||
let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap();
|
||||
let inside = |v: &Value| v.as_str().is_some_and(|s| std::path::Path::new(s).starts_with(&dir));
|
||||
for (id, key) in [
|
||||
("document.open", "path"),
|
||||
("addon.document.saveTimestampedCopy", "folder"),
|
||||
("document.compare", "diffPath"),
|
||||
("text.addFontFiles", "files"),
|
||||
("file.saveAs", "path"),
|
||||
] {
|
||||
let cases = junk_params_for_command(spec(id), &path);
|
||||
let sent: Vec<&Value> = cases.iter().filter_map(|p| p.get(key)).collect();
|
||||
assert!(sent.iter().any(|v| inside(v) || v.as_array().is_some_and(|a| a.iter().any(inside))), "{id} sends no `{key}` in the temp folder");
|
||||
}
|
||||
for (id, key) in
|
||||
[("document.open", "path"), ("document.open", "name"), ("addon.document.saveTimestampedCopy", "folder"), ("links.relink", "folder")]
|
||||
{
|
||||
assert!(param_keys(spec(id).params).iter().any(|k| k == key), "{id} has no `{key}` key");
|
||||
}
|
||||
let folder = junk_params_for_command(spec("addon.document.saveTimestampedCopy"), &path);
|
||||
assert!(folder.iter().filter_map(|p| p.get("folder")?.as_str()).all(|s| s != path && std::path::Path::new(s).starts_with(&dir)));
|
||||
let relink = junk_params_for_command(spec("links.relink"), &path);
|
||||
let nested = relink.iter().filter_map(|p| p.get("paths")?.as_array()).flatten().filter_map(|e| e.get("path")).filter(|v| v.is_string());
|
||||
assert!(nested.clone().count() > 0 && nested.clone().all(inside), "links.relink sends no `paths[].path` in the temp folder");
|
||||
// A key that names part of the document in a command keeps its junk there.
|
||||
let on_path = junk_params_for_command(spec("text.createInPath"), &path);
|
||||
assert!(on_path.iter().any(|p| p.get("path") == Some(&json!("junk"))));
|
||||
}
|
||||
|
||||
/// Every command that runs at once while the active tool computes an edit on another thread (a
|
||||
/// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the
|
||||
/// documents' revisions and selections, the active document and the current paint as they were,
|
||||
@@ -1007,28 +1102,36 @@ fn polygon_properties_junk() {
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the
|
||||
/// first junk values, a string under a file or folder key replaced by a location inside `path`'s
|
||||
/// folder.
|
||||
fn serializable_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
|
||||
if heavy(c.id) || c.id.starts_with("file.") {
|
||||
return vec![];
|
||||
}
|
||||
let mut cases = vec![];
|
||||
for v in junk_values().iter().take(8) {
|
||||
for k in command_param_keys(c) {
|
||||
cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, v, path) }));
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// After a successful fuzzed call, the document still round-trips and exports.
|
||||
#[test]
|
||||
fn fuzzed_calls_keep_documents_serializable() {
|
||||
let path = safe_path();
|
||||
let mut failures = vec![];
|
||||
for c in command_specs() {
|
||||
if heavy(c.id) || c.id.starts_with("file.") {
|
||||
continue;
|
||||
}
|
||||
for v in junk_values().iter().take(8) {
|
||||
for k in param_keys(c.params) {
|
||||
let k = if k == "path" { continue } else { k };
|
||||
let mut s = Fixture::Multi.session();
|
||||
let p = json!({ k.clone(): v });
|
||||
let ok = catch_quiet(|| s.execute(c.id, &p)).map(|r| r.is_ok()).unwrap_or(false);
|
||||
if ok && let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) {
|
||||
failures.push(format!("{} {p}: {e}", c.id));
|
||||
}
|
||||
for p in serializable_cases(c, &path) {
|
||||
let mut s = Fixture::Multi.session();
|
||||
let ok = catch_quiet(|| s.execute(c.id, &p)).map(|r| r.is_ok()).unwrap_or(false);
|
||||
if ok && let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) {
|
||||
failures.push(format!("{} {p}: {e}", c.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = path;
|
||||
failures.sort();
|
||||
failures.dedup();
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.iter().take(40).cloned().collect::<Vec<_>>().join("\n"));
|
||||
@@ -1091,7 +1194,7 @@ fn recovery_commands_with_a_damaged_store_and_junk_params() {
|
||||
for fx in Fixture::ALL {
|
||||
for id in ["file.recovery.save", "file.recovery.list", "file.recovery.restore", "file.recovery.discard"] {
|
||||
let spec = command_specs().iter().find(|c| c.id == id).unwrap();
|
||||
for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) {
|
||||
for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) {
|
||||
let mut s = fx.session();
|
||||
s.recovery.set_store(store.clone());
|
||||
let r = catch_quiet(|| no_panic(s.execute(id, &p)));
|
||||
@@ -1120,7 +1223,7 @@ fn envelope_commands_with_junk_params_on_envelopes() {
|
||||
command_specs().iter().map(|c| c.id).filter(|id| id.starts_with("object.envelope.") || id.starts_with("object.mesh.")).collect();
|
||||
for id in ids {
|
||||
let spec = command_specs().iter().find(|c| c.id == id).unwrap();
|
||||
for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) {
|
||||
for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) {
|
||||
let mut s = Fixture::Multi.session();
|
||||
if s.execute(make, mp).is_err() {
|
||||
failures.push(format!("{make} failed on the Multi fixture"));
|
||||
@@ -1217,7 +1320,7 @@ fn text_commands_with_junk_params_on_inline_graphics() {
|
||||
}
|
||||
for id in ["text.insertInline", "text.editRange", "text.getRange", "text.setRangeStyle", "type.insert"] {
|
||||
let spec = command_specs().iter().find(|c| c.id == id).unwrap();
|
||||
for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) {
|
||||
for p in std::iter::once(json!({})).chain(junk_params_for_command(spec, &path)) {
|
||||
run(id, &p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7676,3 +7676,144 @@ fn diamond_gradients_are_written_as_radial_gradients_through_their_corners() {
|
||||
let Some(Paint::Gradient(swatch)) = back.swatch("Gem").map(|s| &s.paint) else { panic!("the swatch is lost") };
|
||||
assert_eq!(swatch.gradient.kind, GradientKind::Radial);
|
||||
}
|
||||
|
||||
/// The data has no spread: a fill that repeats or reflects holds its stops repeated across the
|
||||
/// shape and reads back looking as the canvas paints it; a swatch holds its stops repeated along
|
||||
/// its vector; both with a warning.
|
||||
#[test]
|
||||
fn spread_gradients_are_written_with_their_stops_repeated() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, stops) });
|
||||
let (start, end) = (vectorcraft_geom::Point::new(60.0, 50.0), vectorcraft_geom::Point::new(120.0, 50.0));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None });
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let id = doc.alloc_id();
|
||||
let l = doc.layers[0].id;
|
||||
let fill = Paint::Gradient(Box::new(g.clone()));
|
||||
doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0)))
|
||||
.unwrap();
|
||||
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
|
||||
swatches.push(Swatch {
|
||||
name: "Bands".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })),
|
||||
global: false,
|
||||
spot: false,
|
||||
});
|
||||
doc.swatches = swatches.into();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(
|
||||
out.warnings.iter().any(|w| w.contains("gradients that repeat or reflect are written with their stops repeated")),
|
||||
"{:?}",
|
||||
out.warnings
|
||||
);
|
||||
let back = read_back(&doc);
|
||||
let st = vectorcraft_testkit::raster::perceptual_diff(
|
||||
&vectorcraft_testkit::raster::render_artboard(&doc),
|
||||
&vectorcraft_testkit::raster::render_artboard(&back),
|
||||
8.0,
|
||||
);
|
||||
assert!((st.bad_pixels as f64) < 0.02 * st.pixels as f64, "{kind:?}: {} of {} pixels differ", st.bad_pixels, st.pixels);
|
||||
let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") };
|
||||
let colors: Vec<String> = swatch.gradient.stops.iter().map(|s| s.color.to_hex()).collect();
|
||||
assert_eq!(colors, ["#ff0000", "#0000ff", "#0000ff", "#ff0000"], "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's gradient that repeats is written with its stops repeated as far as the stroke's
|
||||
/// miter joins reach, past the box the gradient is placed on, so a sharp join's tip shows the next
|
||||
/// run rather than the color the gradient pads with; a straight line, which has no joins, keeps
|
||||
/// every run within the stops the reader reads.
|
||||
#[test]
|
||||
fn a_stroke_spread_gradient_runs_on_into_its_miter_tips() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(GradientKind::Linear, stops) });
|
||||
// From the top of the box the gradient is placed on (the path's box grown by half the width).
|
||||
let (start, end) = (vectorcraft_geom::Point::new(100.0, 15.0), vectorcraft_geom::Point::new(100.0, 85.0));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None });
|
||||
let mut app = Appearance::basic(Paint::None, Paint::Gradient(Box::new(g)), 10.0);
|
||||
for item in &mut app.items {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
(s.join, s.miter_limit) = (LineJoin::Miter, 10.0);
|
||||
}
|
||||
}
|
||||
// A V whose apex's miter reaches about 10 pt above it, to y = 9.9.
|
||||
let pts = [vectorcraft_geom::Point::new(60.0, 90.0), vectorcraft_geom::Point::new(100.0, 20.0), vectorcraft_geom::Point::new(140.0, 90.0)];
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let id = doc.alloc_id();
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, Node::path(id, PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false)]), app)).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let mut geom = None;
|
||||
back.walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.stroke_paint() {
|
||||
geom = g.geom;
|
||||
}
|
||||
});
|
||||
let geom = geom.expect("the stroke keeps a gradient");
|
||||
assert!(geom.start.y.min(geom.end.y) < 9.9, "the runs start at {:?}", geom);
|
||||
// A straight line has no joins: its 100 runs, 200 stops, fit the 256 the reader reads.
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) });
|
||||
let (start, end) = (vectorcraft_geom::Point::new(50.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: 1.0, focal: None });
|
||||
let line = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&[start, end], false)]);
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let id = doc.alloc_id();
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, Node::path(id, line, Appearance::basic(Paint::None, Paint::Gradient(Box::new(g)), 10.0))).unwrap();
|
||||
let mut stops = None;
|
||||
read_back(&doc).walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.stroke_paint() {
|
||||
stops = Some(g.gradient.stops.len());
|
||||
}
|
||||
});
|
||||
assert_eq!(stops, Some(200));
|
||||
}
|
||||
|
||||
/// A conic fill (written linear, its stops repeated around its turn), a diamond fill (written
|
||||
/// radial) and a swatch whose stops repeat more times than the 256 stops the reader reads stay
|
||||
/// gradients: each holds its stops repeated as far as 256 stops go.
|
||||
#[test]
|
||||
fn spread_gradients_past_the_stops_the_reader_reads_stay_gradients() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let three = || {
|
||||
vec![
|
||||
GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)),
|
||||
GradientStop::new(0.5, Color::rgb(0.0, 1.0, 0.0)),
|
||||
GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0)),
|
||||
]
|
||||
};
|
||||
for kind in [GradientKind::Conic, GradientKind::Diamond] {
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(kind, three()) });
|
||||
let c = vectorcraft_geom::Point::new(100.0, 50.0);
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(40.0, 0.0), aspect: 1.0, focal: None });
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let id = doc.alloc_id();
|
||||
let l = doc.layers[0].id;
|
||||
let fill = Paint::Gradient(Box::new(g));
|
||||
doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, Paint::None, 0.0)))
|
||||
.unwrap();
|
||||
let back = read_back(&doc);
|
||||
let mut stops = None;
|
||||
back.walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.fill_paint() {
|
||||
stops = Some(g.gradient.stops.len());
|
||||
}
|
||||
});
|
||||
let stops = stops.unwrap_or_else(|| panic!("{kind:?}: the gradient is written as a solid color"));
|
||||
assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&stops), "{kind:?}: {stops} stops");
|
||||
}
|
||||
// Stops at 0.1 and 0.9 run from 0 to 1 as four: 70 runs are 280 stops.
|
||||
let stops = vec![GradientStop::new(0.1, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.9, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 70, ..Gradient::new(GradientKind::Linear, stops) });
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
|
||||
swatches.push(Swatch { name: "Bands".into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false });
|
||||
doc.swatches = swatches.into();
|
||||
let back = read_back(&doc);
|
||||
let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") };
|
||||
assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&swatch.gradient.stops.len()), "{} stops", swatch.gradient.stops.len());
|
||||
}
|
||||
@@ -896,7 +896,7 @@ impl<'a> Writer<'a> {
|
||||
self.warn_cut(Some(first));
|
||||
return self.clip_contents(children);
|
||||
};
|
||||
let items = self.items(first, path.to_bezpath().bounding_box());
|
||||
let items = self.items(first, &path.to_bezpath());
|
||||
let painted = self.plain_paint(&items);
|
||||
// The clipping path goes after the others, so its objects are counted first.
|
||||
let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect();
|
||||
@@ -1004,7 +1004,7 @@ impl<'a> Writer<'a> {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
let items = self.items(n, path.to_bezpath().bounding_box());
|
||||
let items = self.items(n, &path.to_bezpath());
|
||||
if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) {
|
||||
self.warn(ITEM_TRANSPARENCY);
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ pub(super) struct PatternOut {
|
||||
|
||||
pub(in crate::ai_editing) const DIAMOND: &str =
|
||||
"diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps";
|
||||
|
||||
/// Can `g` be written as a gradient (a linear, radial, conic or diamond one with stops, no more
|
||||
/// than the `.ai` reader reads; a conic is written linear, [`CONIC`], and a diamond radial,
|
||||
@@ -85,11 +86,13 @@ impl Writer<'_> {
|
||||
pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) {
|
||||
let doc = self.doc;
|
||||
for sw in doc.swatches_iter() {
|
||||
// As `swatch_paint` writes it: the stops of one that repeats or reflects repeated.
|
||||
if let Paint::Gradient(g) = &sw.paint
|
||||
&& writable_gradient(&g.gradient)
|
||||
&& let gradient = g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
{
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false });
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,8 +138,27 @@ impl Writer<'_> {
|
||||
/// placed there (it then no longer depends on the shape it paints, which may be cut); one the
|
||||
/// data can't hold is its average color, with a warning.
|
||||
pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint {
|
||||
self.placed_over(p, bounds, bounds)
|
||||
}
|
||||
|
||||
/// [`Self::placed`] for paint that reaches `area`: a gradient that repeats or reflects is
|
||||
/// written with its stops repeated over `area`.
|
||||
fn placed_over(&mut self, p: &Paint, bounds: Rect, area: Rect) -> Paint {
|
||||
let Paint::Gradient(g) = p else { return p.clone() };
|
||||
let geom = g.resolve(bounds);
|
||||
let mut geom = g.resolve(bounds);
|
||||
// The data has no spread: a gradient that repeats or reflects is written with its stops
|
||||
// repeated over `area` (a conic one, written linear, around its turn).
|
||||
let mut g: GradientPaint = (**g).clone();
|
||||
if g.gradient.is_spread() {
|
||||
self.warn(SPREAD);
|
||||
match g.gradient.padded_within(&geom, area, crate::import::MAX_GRADIENT_STOPS) {
|
||||
Some(padded) => {
|
||||
g.gradient = padded.gradient;
|
||||
geom = padded.geom;
|
||||
}
|
||||
None => g.gradient = g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS).into_owned(),
|
||||
}
|
||||
}
|
||||
let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite());
|
||||
let radial = written_radial(g.gradient.kind);
|
||||
if g.gradient.kind == GradientKind::Freeform {
|
||||
@@ -147,13 +169,16 @@ impl Writer<'_> {
|
||||
self.warn(GRADIENT_SHAPES);
|
||||
return Paint::solid(average(&g.gradient));
|
||||
}
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() }))
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..g }))
|
||||
}
|
||||
|
||||
/// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed
|
||||
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient
|
||||
/// along or across a stroke is its average color (the stroke is written as its outline).
|
||||
pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec<AppearanceItem> {
|
||||
/// The fills and strokes of `n` that paint (outline `bp`), their gradients placed
|
||||
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints, the stops
|
||||
/// of one that repeats or reflects repeated over the box the stroke paints, miter spikes
|
||||
/// included ([`StrokeLayer::bounds_on`]). A gradient along or across a stroke is its average
|
||||
/// color (the stroke is written as its outline).
|
||||
pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bp: &BezPath) -> Vec<AppearanceItem> {
|
||||
let bounds = bp.bounding_box();
|
||||
super::visible_items(n)
|
||||
.into_iter()
|
||||
.map(|i| match i {
|
||||
@@ -164,7 +189,11 @@ impl Writer<'_> {
|
||||
self.warn(GRADIENTS);
|
||||
Paint::solid(average(&g.gradient))
|
||||
}
|
||||
None => self.placed(&s.paint, s.paint_bounds(bounds)),
|
||||
None => {
|
||||
let spread = matches!(&s.paint, Paint::Gradient(g) if g.gradient.is_spread());
|
||||
let reach = if spread { s.bounds_on(bp, bounds) } else { bounds };
|
||||
self.placed_over(&s.paint, s.paint_bounds(bounds), reach)
|
||||
}
|
||||
};
|
||||
AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() })
|
||||
}
|
||||
@@ -521,10 +550,19 @@ impl Writer<'_> {
|
||||
/// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't
|
||||
/// be written.
|
||||
pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool {
|
||||
// A swatch has no placement: one that repeats or reflects holds its stops repeated along
|
||||
// its vector.
|
||||
let unrolled = match &sw.paint {
|
||||
Paint::Gradient(g) => Some(g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS)),
|
||||
_ => None,
|
||||
};
|
||||
match &sw.paint {
|
||||
Paint::Gradient(g) if writable_gradient(&g.gradient) => {
|
||||
Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => {
|
||||
if g.gradient.is_spread() {
|
||||
self.warn(SPREAD);
|
||||
}
|
||||
let swatch = Some(sw.name.as_str());
|
||||
let name = self.define_gradient(&g.gradient, swatch);
|
||||
let name = self.define_gradient(unrolled.as_deref().unwrap_or(&g.gradient), swatch);
|
||||
s.push_str("Bb\n");
|
||||
if written_radial(g.gradient.kind) {
|
||||
s.push_str("0 0 0 0 Bh\n");
|
||||
|
||||
@@ -18,7 +18,6 @@ use vectorcraft_geom::BezPath;
|
||||
|
||||
use super::interp::{Interp, matrix_obj};
|
||||
use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
|
||||
use super::predefined_cmap::Unicode;
|
||||
|
||||
/// Most codespace ranges, character and notdef mappings a CMap may hold.
|
||||
const MAX_RANGES: usize = 1 << 16;
|
||||
@@ -211,32 +210,6 @@ fn number(data: &[u8], at: usize, n: usize) -> Option<u64> {
|
||||
(n <= 8).then(|| bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b)))
|
||||
}
|
||||
|
||||
/// The encoding of predefined Unicode CMap `name` and whether it is vertical: one of Adobe's
|
||||
/// public CMap resources whose name says its codes are Unicode: `Uni` and a character
|
||||
/// collection, then `-UCS2`, `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms),
|
||||
/// then `-H` or `-V` (`UniJIS-UCS2-H`, `UniGB-UTF16-V`:
|
||||
/// <https://github.com/adobe-type-tools/cmap-resources>).
|
||||
pub(super) fn unicode_cmap(name: &str) -> Option<(Unicode, bool)> {
|
||||
let (rest, dir) = name.rsplit_once('-')?;
|
||||
let vertical = match dir {
|
||||
"H" => false,
|
||||
"V" => true,
|
||||
_ => return None,
|
||||
};
|
||||
let rest = rest.strip_suffix("-HW").unwrap_or(rest);
|
||||
let (collection, form) = rest.rsplit_once('-')?;
|
||||
if !(collection.len() > 3 && collection.starts_with("Uni") && !collection.contains('-')) {
|
||||
return None;
|
||||
}
|
||||
let form = match form {
|
||||
"UCS2" | "UTF16" => Unicode::Utf16,
|
||||
"UTF8" => Unicode::Utf8,
|
||||
"UTF32" => Unicode::Utf32,
|
||||
_ => return None,
|
||||
};
|
||||
Some((form, vertical))
|
||||
}
|
||||
|
||||
/// A predefined Identity CMap: two-byte codes, each the CID of its own value; vertical for
|
||||
/// `Identity-V`.
|
||||
pub(super) fn identity(name: &str, vertical: bool) -> Obj {
|
||||
@@ -396,11 +369,9 @@ impl Interp<'_> {
|
||||
return Ok(d.clone());
|
||||
}
|
||||
let text = name.text().map(|t| t.to_string()).unwrap_or_default();
|
||||
// Another predefined CMap the file doesn't define, without its mappings: its codes are
|
||||
// read by its name when type is set (see `text`).
|
||||
let predefined = unicode_cmap(&text)
|
||||
.map(|(_, vertical)| vertical)
|
||||
.or_else(|| super::predefined_cmap::known(&text).then(|| super::predefined_cmap::vertical(&text)));
|
||||
// A predefined CMap the file doesn't define, without its mappings: its codes are read by
|
||||
// its name when type is set (see `text`).
|
||||
let predefined = super::predefined_cmap::known(&text).then(|| super::predefined_cmap::vertical(&text));
|
||||
match predefined {
|
||||
Some(vertical) => {
|
||||
let mut d = Dict::new();
|
||||
|
||||
@@ -95,6 +95,9 @@ pub(crate) struct Interp<'a> {
|
||||
/// The predefined CMaps type was set in so far, by name, with how their strings decode
|
||||
/// (`None` when one can't be read; see `text`).
|
||||
pub predefined_cmaps: Vec<(Rc<str>, Option<Rc<super::predefined_cmap::CMapCodes>>)>,
|
||||
/// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in
|
||||
/// a font of its own (see `text`).
|
||||
pub kshow_font: Option<DictRef>,
|
||||
pub g: GState,
|
||||
pub saved: Vec<GState>,
|
||||
pub out: Out,
|
||||
@@ -236,6 +239,7 @@ impl<'a> Interp<'a> {
|
||||
cid_subrs: vec![],
|
||||
cmap_font: 0,
|
||||
predefined_cmaps: vec![],
|
||||
kshow_font: None,
|
||||
type42_counted: HashSet::new(),
|
||||
g,
|
||||
saved: vec![],
|
||||
|
||||
@@ -157,7 +157,7 @@ pub(super) enum Unicode {
|
||||
/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`,
|
||||
/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V`
|
||||
/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: <https://github.com/adobe-type-tools/cmap-resources>).
|
||||
fn unicode_cmap(name: &str) -> Option<Unicode> {
|
||||
pub(super) fn unicode_cmap(name: &str) -> Option<Unicode> {
|
||||
let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?;
|
||||
let rest = rest.strip_suffix("-HW").unwrap_or(rest);
|
||||
let (collection, form) = rest.rsplit_once('-')?;
|
||||
@@ -325,6 +325,28 @@ pub(super) fn known(cmap: &str) -> bool {
|
||||
unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other()
|
||||
}
|
||||
|
||||
/// The codes of string `bytes` in predefined CMap `cmap` when its mappings can't be read, each
|
||||
/// standing for no character: as long as the code space range it falls in ([`code_space`]; a byte
|
||||
/// that starts no code is a code of its own), or two bytes when the code space isn't listed (the
|
||||
/// row-and-cell codes of `GBT-H` and `CNS2-H`). A 0x0D or 0x09 byte is always a code of its own.
|
||||
pub(super) fn unread_codes(cmap: &str, bytes: &[u8]) -> Decoded {
|
||||
let space = code_space(cmap);
|
||||
let mut out = Decoded::default();
|
||||
let mut at = 0;
|
||||
while let Some(rest) = bytes.get(at..).filter(|r| !r.is_empty()) {
|
||||
let len = match space {
|
||||
// A 0x0D or 0x09 byte is a code of its own, as [`CMapCodes::each_code`] reads it.
|
||||
_ if rest.first().and_then(|&b| control(b)).is_some() => 1,
|
||||
Some(space) => code_len(space, rest).map_or(1, usize::from),
|
||||
None => 2,
|
||||
};
|
||||
let code = rest.get(..len).unwrap_or(rest);
|
||||
out.push(code.iter().fold(0u32, |c, &b| c << 8 | u32::from(b)), None);
|
||||
at += code.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether predefined CMap `cmap` is a vertical CMap (`-V`, or the row-and-cell `V`).
|
||||
pub(super) fn vertical(cmap: &str) -> bool {
|
||||
cmap == "V" || cmap.ends_with("-V")
|
||||
|
||||
@@ -426,8 +426,6 @@ fn named_cidfonts_over_predefined_cmaps_set_their_characters_as_type() {
|
||||
("83pv-RKSJ-H", "93fa967b41", "日本A"),
|
||||
("90ms-RKSJ-H", "93fa", "日"),
|
||||
("EUC-H", "c6fc", "日"),
|
||||
// JIS row and cell: 日 is 0x467C.
|
||||
("H", "467c", "日"),
|
||||
("GBK-EUC-H", "d6d0", "中"),
|
||||
("B5pc-H", "a4a4", "中"),
|
||||
("ETen-B5-H", "a4a4", "中"),
|
||||
@@ -448,6 +446,9 @@ fn named_cidfonts_over_predefined_cmaps_set_their_characters_as_type() {
|
||||
}
|
||||
let r = super::tests::read("/X /GBK-EUC-H [/NotInFile] composefont 20 scalefont setfont 10 20 moveto <d6d041> show");
|
||||
assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::<String>(), "中A");
|
||||
// JIS row and cell: 日 is 0x467C.
|
||||
let r = super::tests::read("/X /H [/Ryumin-Light] composefont 20 scalefont setfont 10 20 moveto <467c> show");
|
||||
assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::<String>(), "日");
|
||||
// The point moves past the type, along the line.
|
||||
check("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont <93fa967b> stringwidth abs 0.01 lt exch dup 5 gt exch 60 lt and and");
|
||||
}
|
||||
@@ -478,8 +479,34 @@ fn named_cidfonts_over_predefined_cmaps_take_the_show_operators_spacing() {
|
||||
measured(&format!(
|
||||
"{gb} 10 20 moveto <56505650> show currentpoint pop 10 20 moveto 7 0 16#5650 <56505650> widthshow currentpoint pop sub -14 sub abs 0.01 lt"
|
||||
));
|
||||
// `xshow` moves 30 a code.
|
||||
// `awidthshow` adds 5 to each code and 7 more to the space.
|
||||
measured(&format!(
|
||||
"{set} 10 20 moveto <93fa20967b> show currentpoint pop 10 20 moveto 7 0 32 5 0 <93fa20967b> awidthshow currentpoint pop sub -22 sub abs 0.01 lt"
|
||||
));
|
||||
// `xshow` moves 30 a code, `yshow` 10 up a code, `xyshow` both.
|
||||
measured(&format!("{set} 10 20 moveto <93fa967b> [30 30] xshow currentpoint pop 70 sub abs 0.01 lt"));
|
||||
measured(&format!("{set} 10 20 moveto <93fa967b> [10 10] yshow currentpoint 40 sub abs 0.01 lt exch 10 sub abs 0.01 lt and"));
|
||||
measured(&format!("{set} 10 20 moveto <93fa967b> [30 10 30 10] xyshow currentpoint 40 sub abs 0.01 lt exch 70 sub abs 0.01 lt and"));
|
||||
// `kshow` runs its procedure between each two codes: it moves the point 100 more here, and a
|
||||
// font it sets stays current.
|
||||
measured(&format!(
|
||||
"{set} 10 20 moveto <93fa967b> show currentpoint 10 20 moveto {{pop pop 100 0 rmoveto}} <93fa967b> kshow currentpoint \
|
||||
3 -1 roll sub abs 0.01 lt 3 1 roll sub -100 sub abs 0.01 lt and"
|
||||
));
|
||||
measured(&format!(
|
||||
"{set} 10 20 moveto {{pop pop /Helvetica findfont 10 scalefont setfont}} <93fa967b> kshow currentfont /FontName get /Helvetica eq"
|
||||
));
|
||||
// The procedure sees the font the file set as current, and the next one the font an earlier
|
||||
// one set.
|
||||
measured(&format!("{set} 10 20 moveto {{pop pop currentfont /FontName get /seen exch def}} <93fa967b> kshow seen /Ryumin-Light-90ms-RKSJ-H eq"));
|
||||
measured(&format!(
|
||||
"{set} 10 20 moveto /n 0 def {{pop pop /n n 1 add def n 1 eq {{/Helvetica findfont 10 scalefont setfont}} {{currentfont /FontName get /seen exch def}} ifelse}} \
|
||||
<93fa967b41> kshow seen /Helvetica eq"
|
||||
));
|
||||
// The procedure gets the two codes' values (left on the stack here).
|
||||
measured(&format!(
|
||||
"{set} 10 20 moveto [ {{}} <93fa967b41> kshow ] dup length 4 eq exch aload pop 65 eq exch 16#967b eq and exch 16#967b eq and exch 16#93fa eq and and"
|
||||
));
|
||||
// Down the column: `ashow`'s 5 down each code.
|
||||
let set = "/Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont";
|
||||
measured(&format!(
|
||||
@@ -530,10 +557,15 @@ fn named_cid_type_is_set_alike_by_every_show_operator() {
|
||||
let r = super::tests::read(&format!("{set} <00660069> {show}"));
|
||||
let t = texts(&r);
|
||||
assert_eq!(t.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["fi"], "{show}");
|
||||
t[0].runs.iter().map(|r| r.style.features.clone()).collect::<Vec<_>>()
|
||||
// Spacing that differs from the advances splits the type into runs of the same features.
|
||||
let mut features = t[0].runs.iter().map(|r| r.style.features.clone()).collect::<Vec<_>>();
|
||||
features.dedup();
|
||||
features
|
||||
};
|
||||
let plain = features("show");
|
||||
assert_eq!(plain, features("0 0 3 -1 roll ashow"));
|
||||
for show in ["0 0 3 -1 roll ashow", "0 0 32 4 -1 roll widthshow", "0 0 32 0 0 6 -1 roll awidthshow", "[25 25] xshow", "{pop pop} exch kshow"] {
|
||||
assert_eq!(plain, features(show), "{show}");
|
||||
}
|
||||
assert!(plain.iter().all(|f| f.iter().any(|f| f == "-liga")), "{plain:?}");
|
||||
check(&format!(
|
||||
"gsave nulldevice {set} <00660069> stringwidth 10 20 moveto 0 0 <00660069> ashow currentpoint grestore \
|
||||
@@ -541,17 +573,77 @@ fn named_cid_type_is_set_alike_by_every_show_operator() {
|
||||
));
|
||||
}
|
||||
|
||||
/// A font name ending in the row-and-cell CMap `H` after a name without a hyphen stays a font of
|
||||
/// the whole name, its strings read byte by byte. Type in a predefined CMap whose mappings aren't
|
||||
/// available is left out with a warning, and a long string in a CID-keyed font over a predefined
|
||||
/// CMap shown in a loop runs out of the budget.
|
||||
/// `charpath`, `cshow` and `glyphshow` in a CID-keyed font over a predefined CMap, its CIDFont only
|
||||
/// named: `charpath` adds the outlines of the characters the codes stand for and moves the point
|
||||
/// as `show` does; `cshow`'s procedure gets each code (two bytes for a two-byte code) with its
|
||||
/// width; `glyphshow` sets the named character itself.
|
||||
#[test]
|
||||
fn named_cid_type_in_charpath_cshow_and_glyphshow() {
|
||||
let set = "/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont";
|
||||
let r = super::tests::read(&format!("{set} 10 20 moveto <4142> true charpath fill"));
|
||||
assert!(texts(&r).is_empty(), "{:?}", all(&r.document));
|
||||
assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{:?}", all(&r.document));
|
||||
check(&format!(
|
||||
"gsave nulldevice {set} 10 20 moveto <93fa41> show currentpoint newpath 10 20 moveto <93fa41> false charpath currentpoint grestore \
|
||||
3 -1 roll sub abs 0.01 lt 3 1 roll sub abs 0.01 lt and"
|
||||
));
|
||||
// Down a column a code that stands for no character (0xFD) moves the outlines one em, as it
|
||||
// moves the type `show` sets.
|
||||
let top = |s: &str| format!("newpath 10 100 moveto <{s}> false charpath pathbbox 4 1 roll pop pop pop");
|
||||
check(&format!(
|
||||
"gsave nulldevice /Ryumin-Light-90ms-RKSJ-V findfont 20 scalefont setfont {} {} grestore sub -20 sub abs 0.5 lt",
|
||||
top("fd41"),
|
||||
top("41")
|
||||
));
|
||||
// The procedure leaves each code: 日 (0x93FA), then A.
|
||||
check(&format!("{set} [ {{pop pop}} <93fa41> cshow ] dup length 2 eq exch dup 0 get 16#93fa eq exch 1 get 65 eq and and"));
|
||||
check(&format!("{set} 0 {{pop exch pop add}} <93fa967b41> cshow <93fa967b41> stringwidth pop sub abs 0.01 lt"));
|
||||
let r = super::tests::read(&format!("{set} 10 20 moveto /uni00E9 glyphshow"));
|
||||
assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["é"]);
|
||||
}
|
||||
|
||||
/// A font name ending in the row-and-cell CMap `H` or `V` stays a font of the whole name, its
|
||||
/// strings read byte by byte, unless the part before the CMap names a CIDFont the file defines (or
|
||||
/// an installed face that covers Japanese). Type in a predefined CMap whose mappings aren't
|
||||
/// available is left out with a warning, each code moving the point one em, and a long string in a
|
||||
/// CID-keyed font over a predefined CMap shown in a loop runs out of the budget.
|
||||
#[test]
|
||||
fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() {
|
||||
let r = super::tests::read("/Futura-H findfont 20 scalefont setfont 10 20 moveto (AB) show");
|
||||
assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["AB"]);
|
||||
for (font, family, style) in [("Futura-H", "Futura", "H"), ("Foo-Bold-H", "Foo", "Bold-H"), ("Foo-Condensed-V", "Foo", "Condensed-V")] {
|
||||
let r = super::tests::read(&format!("/{font} findfont 20 scalefont setfont 10 20 moveto (AB) show"));
|
||||
let t = texts(&r);
|
||||
assert_eq!(t.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["AB"], "{font}");
|
||||
let s = &t[0].runs[0].style;
|
||||
assert_eq!((s.font_family.as_str(), s.font_style.as_str()), (family, style), "{font}");
|
||||
assert!(!t[0].vertical, "{font}");
|
||||
}
|
||||
// The file defines the CIDFont `Ryumin-Light`, as a resource or as a font: `Ryumin-Light-H` is
|
||||
// it over the CMap `H`.
|
||||
// A CIDFont name without a hyphen too, when the file defines it.
|
||||
let cid_font = |name: &str| format!("/{name} << /CIDFontName /{name} /CIDFontType 0 /FontType 9 /FontMatrix [0.001 0 0 0.001 0 0] >>");
|
||||
let defines = [
|
||||
format!("{} /CIDFont defineresource pop /Ryumin-Light-H", cid_font("Ryumin-Light")),
|
||||
format!("{} definefont pop /Ryumin-Light-H", cid_font("Ryumin-Light")),
|
||||
format!("{} /CIDFont defineresource pop /Foo-H", cid_font("Foo")),
|
||||
];
|
||||
for define in defines {
|
||||
let r = super::tests::read(&format!("{define} findfont 20 scalefont setfont 10 20 moveto <467c> show"));
|
||||
assert_eq!(texts(&r).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["日"], "{define}: {:?}", r.warnings);
|
||||
}
|
||||
let r = super::tests::read("/Ryumin-Light-GBT-H findfont 20 scalefont setfont 10 20 moveto (AB) show 0 0 10 10 rectfill");
|
||||
assert!(texts(&r).is_empty(), "{:?}", all(&r.document));
|
||||
assert_eq!(super::tests::program_warnings(&r.warnings), [super::text::UNREAD_CMAP], "{:?}", r.warnings);
|
||||
// Two two-byte codes: two ems along the line, or down the column (a square drawn when the
|
||||
// point moved that far).
|
||||
for cond in [
|
||||
"/Ryumin-Light-GBT-H findfont 20 scalefont setfont <21212121> stringwidth abs 0.01 lt exch 40 sub abs 0.01 lt and",
|
||||
"/Ryumin-Light-GBT-V findfont 20 scalefont setfont 10 100 moveto <21212121> show currentpoint 60 sub abs 0.01 lt exch 10 sub abs 0.01 lt and",
|
||||
// A tab is a code of its own: three codes.
|
||||
"/Ryumin-Light-GBT-H findfont 20 scalefont setfont <09092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and",
|
||||
] {
|
||||
let r = super::tests::read(&format!("{cond} {{ 0 0 10 10 rectfill }} if"));
|
||||
assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{cond}");
|
||||
}
|
||||
super::tests::runs_out_of_budget("/Ryumin-Light-90ms-RKSJ-H findfont 20 scalefont setfont { 100000 string stringwidth pop pop } loop");
|
||||
}
|
||||
|
||||
|
||||
+213
-79
@@ -171,8 +171,8 @@ impl Interp<'_> {
|
||||
ResourceForAll => self.resource_for_all()?,
|
||||
Show | AShow | WidthShow | AWidthShow | XShow | YShow | XYShow | KShow => {
|
||||
let (s, spacing) = self.show_operands(op)?;
|
||||
if let Some((codes, font, vertical)) = self.named_cid_type(&s)? {
|
||||
self.show_named_cid(&codes, &font, vertical, &spacing)?;
|
||||
if let Some(named) = self.named_cid_type(&s)? {
|
||||
self.show_named_cid(&named, &spacing, Draw::Fill)?;
|
||||
} else if let Some(glyphs) = self.composite_glyphs(&s)? {
|
||||
self.show_composite(&glyphs, &spacing)?;
|
||||
} else {
|
||||
@@ -186,6 +186,23 @@ impl Interp<'_> {
|
||||
// The procedure shows or places each character: it gets its code and width.
|
||||
let s = self.pop_str()?.to_vec();
|
||||
let proc = self.pop_proc()?;
|
||||
// In a CIDFont only named, a code may be several bytes: the procedure gets each
|
||||
// code's value.
|
||||
if let Some(named) = self.named_cid_type(&s)? {
|
||||
let mut chars = named.codes.text.chars();
|
||||
for &(code, n) in &named.codes.codes {
|
||||
let mut one = Decoded::default();
|
||||
one.push(code, chars.by_ref().take(n));
|
||||
let v = self.named_cid_width(&named, &one)?;
|
||||
self.push(Obj::Int(i64::from(code)))?;
|
||||
self.push_num(v.x)?;
|
||||
self.push_num(v.y)?;
|
||||
if !self.body(&proc)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for b in s {
|
||||
let v = self.width_of(&[b])?;
|
||||
self.push(Obj::Int(i64::from(b)))?;
|
||||
@@ -208,7 +225,14 @@ impl Interp<'_> {
|
||||
}
|
||||
None => {
|
||||
let ch = glyph_char(&name);
|
||||
self.show(ch.encode_utf8(&mut [0; 4]).as_bytes())?;
|
||||
// In a CIDFont only named, the character is set as it is, not read through
|
||||
// the CMap.
|
||||
if let Some(mut named) = self.named_cid_font()? {
|
||||
named.codes.push(0, Some(ch).filter(|c| !c.is_control()));
|
||||
self.show_named_cid(&named, &Spacing::Plain, Draw::Fill)?;
|
||||
} else {
|
||||
self.show(ch.encode_utf8(&mut [0; 4]).as_bytes())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -283,11 +307,8 @@ impl Interp<'_> {
|
||||
|
||||
/// How far `s` moves the current point (user space).
|
||||
fn width_of(&mut self, s: &[u8]) -> Res<Vec2> {
|
||||
if let Some((codes, font, vertical)) = self.named_cid_type(s)? {
|
||||
let saved = self.g.font.replace(font);
|
||||
let r = self.named_cid_width(&codes, vertical);
|
||||
self.g.font = saved;
|
||||
return r;
|
||||
if let Some(named) = self.named_cid_type(s)? {
|
||||
return self.named_cid_width(&named, &named.codes);
|
||||
}
|
||||
if let Some(glyphs) = self.composite_glyphs(s)? {
|
||||
let mut w = Vec2::ZERO;
|
||||
@@ -399,25 +420,23 @@ impl Interp<'_> {
|
||||
/// is a predefined CMap, the CID-keyed font of those two (the usual name of a CID-keyed font,
|
||||
/// as `composefont` makes them: PLRM 3rd ed., chapter 8; the CMaps are Adobe's public CMap
|
||||
/// resources, <https://github.com/adobe-type-tools/cmap-resources>); else a font of that name.
|
||||
/// A name an installed face has is that face's, and a name split at a bare `H` or `V` (the
|
||||
/// row-and-cell CMaps) needs a CIDFont name with a hyphen in it (`Ryumin-Light-H`), so
|
||||
/// `Futura-H` stays a font of that name.
|
||||
/// A name that ends in a predefined CMap other than a Unicode CMap and that an installed face
|
||||
/// has is that face's ([`Self::predefined_split`]).
|
||||
fn find_font(&mut self, k: &Obj) -> Res<DictRef> {
|
||||
let key = k.key().ok_or(PsError::Ps("typecheck", "findfont".into()))?;
|
||||
if let Some(Obj::Dict(d)) = self.fonts.borrow().get(&key) {
|
||||
return Ok(d.clone());
|
||||
}
|
||||
let text = k.text().map(|t| t.to_string()).unwrap_or_default();
|
||||
let split = text
|
||||
let unicode = text
|
||||
.match_indices('-')
|
||||
.map(|(i, _)| i)
|
||||
.find(|&i| i > 0 && super::cid::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some())
|
||||
.and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?)))
|
||||
.or_else(|| {
|
||||
let (cid_font, cmap) = super::predefined_cmap::composite_font(&text)?;
|
||||
let installed = vectorcraft_text::FontDb::global().find_postscript(&text).is_some();
|
||||
(!installed && !(matches!(cmap, "H" | "V") && !cid_font.contains('-'))).then_some((cid_font, cmap))
|
||||
});
|
||||
.find(|&i| i > 0 && super::predefined_cmap::unicode_cmap(text.get(i + 1..).unwrap_or_default()).is_some())
|
||||
.and_then(|i| Some((text.get(..i)?, text.get(i + 1..)?)));
|
||||
let split = match unicode {
|
||||
Some(split) => Some(split),
|
||||
None => self.predefined_split(&text),
|
||||
};
|
||||
if let Some((cid_font, cmap)) = split {
|
||||
let cmap = self.find_cmap(&Obj::name(cmap))?;
|
||||
let dep = self.find_cid_font(&Obj::name(cid_font))?;
|
||||
@@ -434,6 +453,32 @@ impl Interp<'_> {
|
||||
Ok(font)
|
||||
}
|
||||
|
||||
/// Font name `name` as a CIDFont's name and the name of a predefined CMap other than a Unicode
|
||||
/// CMap ([`super::predefined_cmap::composite_font`]), unless an installed face has the whole
|
||||
/// name. A name that ends in the row-and-cell CMap `H` or `V` splits only when the part before
|
||||
/// it names a CIDFont the file defines, or has a hyphen and names an installed face that covers
|
||||
/// Japanese; otherwise it stays a font of the whole name (`Futura-H`, `Foo-Bold-H`), its
|
||||
/// strings read byte by byte.
|
||||
fn predefined_split<'a>(&mut self, name: &'a str) -> Option<(&'a str, &'a str)> {
|
||||
let (cid_font, cmap) = super::predefined_cmap::composite_font(name)?;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
if db.find_postscript(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
if matches!(cmap, "H" | "V") {
|
||||
let key = Key::name(cid_font);
|
||||
// As a CIDFont resource, or as a font (`definefont`), as `composefont` finds it.
|
||||
let cid_font_in = |d: &DictRef| matches!(d.borrow().get(&key), Some(Obj::Dict(f)) if f.borrow().contains_key(&Key::name("CIDFontType")));
|
||||
let defined = self.instances(&Obj::name("CIDFont")).is_ok_and(|d| d.borrow().contains_key(&key)) || cid_font_in(&self.fonts);
|
||||
// 日 is in the row-and-cell CMaps' character set (JIS X 0208).
|
||||
let installed = || db.find_postscript(cid_font).is_some_and(|face| face.covers('日'));
|
||||
if !(defined || (cid_font.contains('-') && installed())) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some((cid_font, cmap))
|
||||
}
|
||||
|
||||
/// The current font's name and its matrix for a font of one unit (user space).
|
||||
fn font(&mut self) -> Res<(String, Affine)> {
|
||||
let font = match self.g.font.clone() {
|
||||
@@ -575,15 +620,25 @@ impl Interp<'_> {
|
||||
codes.push(u32::from(code), c.filter(|c| !c.is_control()));
|
||||
}
|
||||
let widths: Option<Vec<f64>> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect());
|
||||
self.show_codes(&codes, widths.as_deref(), spacing, false, s)
|
||||
self.show_codes(&codes, widths.as_deref(), spacing, false, s, Draw::Fill)
|
||||
}
|
||||
|
||||
/// The codes `codes` (each standing for some of its characters, or none) shown in the current
|
||||
/// font as [`Self::show_plain`] shows a string's, spaced as `spacing` says, each code `widths`
|
||||
/// wide when given (in glyph space, one unit an em), else as wide as its characters' advances;
|
||||
/// as vertical type when `vertical`, the codes moving the point down the column. `kern` is the
|
||||
/// string `kshow` gives its procedure the codes of.
|
||||
fn show_codes(&mut self, codes: &Decoded, widths: Option<&[f64]>, spacing: &Spacing, vertical: bool, kern: &[u8]) -> Res {
|
||||
/// as vertical type when `vertical`, the codes moving the point down the column. `kern` holds
|
||||
/// the codes `kshow` gives its procedure, one for each code. With `draw` [`Draw::Path`] the
|
||||
/// type's glyph outlines are added to the current path, placed as the type would be
|
||||
/// (`charpath`).
|
||||
fn show_codes<C: Copy + Into<i64>>(
|
||||
&mut self,
|
||||
codes: &Decoded,
|
||||
widths: Option<&[f64]>,
|
||||
spacing: &Spacing,
|
||||
vertical: bool,
|
||||
kern: &[C],
|
||||
draw: Draw,
|
||||
) -> Res {
|
||||
let at = self.user_point()?;
|
||||
let (_, f1) = self.font()?;
|
||||
let text = &codes.text;
|
||||
@@ -627,8 +682,9 @@ impl Interp<'_> {
|
||||
return ps_err("undefinedresult", "a show");
|
||||
}
|
||||
let across = moves.iter().any(|m| m.2.abs() > size * 1e-3);
|
||||
// Nothing shows on the null device (`nulldevice`, a Type 3 glyph only measured).
|
||||
let painted = !self.g.paint.is_none() && !self.g.null;
|
||||
// Nothing shows on the null device (`nulldevice`, a Type 3 glyph only measured);
|
||||
// `charpath` adds the outlines there too.
|
||||
let painted = draw == Draw::Path || (!self.g.paint.is_none() && !self.g.null);
|
||||
if across {
|
||||
// Moves across the baseline (`yshow`, `xyshow`): each character where the file puts it.
|
||||
let mut pen = at;
|
||||
@@ -637,8 +693,12 @@ impl Interp<'_> {
|
||||
let c: String = chars.by_ref().take(n).collect();
|
||||
if painted && !c.trim().is_empty() {
|
||||
let (t, ..) = self.set_text_in(&c, pen, vertical)?;
|
||||
let clips = self.g.clips.clone();
|
||||
self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips);
|
||||
if draw == Draw::Path {
|
||||
self.type_path(&t)?;
|
||||
} else {
|
||||
let clips = self.g.clips.clone();
|
||||
self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips);
|
||||
}
|
||||
}
|
||||
pen += *d;
|
||||
}
|
||||
@@ -686,27 +746,64 @@ impl Interp<'_> {
|
||||
if lead != Vec2::ZERO {
|
||||
t.xf = Affine::translate(self.xf() * Point::new(lead.x, lead.y) - self.xf() * Point::ZERO) * t.xf;
|
||||
}
|
||||
let clips = self.g.clips.clone();
|
||||
if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some()
|
||||
&& let Some(after) = self.out.drawn.get_mut(start..)
|
||||
{
|
||||
after.rotate_right(1);
|
||||
if draw == Draw::Path {
|
||||
self.type_path(&t)?;
|
||||
} else {
|
||||
let clips = self.g.clips.clone();
|
||||
if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some()
|
||||
&& let Some(after) = self.out.drawn.get_mut(start..)
|
||||
{
|
||||
after.rotate_right(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.g.cur = Some(self.xf() * (at + total));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `kshow` between character `i` of `s` and the next: its procedure run with the two codes
|
||||
/// and the current point at user point `pen` (PLRM 3rd ed., `kshow`: the procedure may
|
||||
/// change the current point, as kerning does) → how far it moved the point (user space).
|
||||
/// The glyph outlines of point type `t` added to the current path (`charpath`).
|
||||
fn type_path(&mut self, t: &TextObject) -> Res {
|
||||
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
for g in &layout.glyphs {
|
||||
let mut o = g.outline.clone();
|
||||
o.apply_affine(t.xf);
|
||||
self.extend_path(o)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Glyph outline `o` added to the current path, unless the path would pass its most points.
|
||||
fn extend_path(&mut self, o: vectorcraft_geom::BezPath) -> Res {
|
||||
if self.g.path.elements().len().saturating_add(o.elements().len()) > super::graphics::MAX_PATH {
|
||||
return Err(PsError::Limit("a path has too many points"));
|
||||
}
|
||||
self.g.path.extend(o);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `kshow` between character `i` of `s` (its codes) and the next: its procedure run with the
|
||||
/// two codes and the current point at user point `pen` (PLRM 3rd ed., `kshow`: the procedure
|
||||
/// may change the current point, as kerning does) → how far it moved the point (user space).
|
||||
/// Nothing for other show operators or after the last character.
|
||||
fn kern(&mut self, spacing: &Spacing, s: &[u8], i: usize, pen: Point) -> Res<Vec2> {
|
||||
fn kern<C: Copy + Into<i64>>(&mut self, spacing: &Spacing, s: &[C], i: usize, pen: Point) -> Res<Vec2> {
|
||||
let (Spacing::Kern(p), Some(&code), Some(&next)) = (spacing, s.get(i), s.get(i + 1)) else { return Ok(Vec2::ZERO) };
|
||||
self.g.cur = Some(self.xf() * pen);
|
||||
self.push(Obj::Int(i64::from(code)))?;
|
||||
self.push(Obj::Int(i64::from(next)))?;
|
||||
self.call(p.clone())?;
|
||||
self.push(Obj::Int(code.into()))?;
|
||||
self.push(Obj::Int(next.into()))?;
|
||||
// The procedure sees the font the file set, not the one type in a CIDFont only named is
|
||||
// set in; a font it sets stays current.
|
||||
let Some(outer) = self.kshow_font.take() else {
|
||||
self.call(p.clone())?;
|
||||
return Ok(self.user_point()? - pen);
|
||||
};
|
||||
let inner = self.g.font.replace(outer.clone());
|
||||
let r = self.call(p.clone());
|
||||
// Once the procedure sets a font, it and the later procedures see that one.
|
||||
if self.g.font.as_ref().is_some_and(|f| f.same(&outer)) {
|
||||
self.g.font = inner;
|
||||
self.kshow_font = Some(outer);
|
||||
}
|
||||
r?;
|
||||
Ok(self.user_point()? - pen)
|
||||
}
|
||||
|
||||
@@ -757,15 +854,14 @@ impl Interp<'_> {
|
||||
if paint == Draw::Fill {
|
||||
return self.fill_path(outline, vectorcraft_geom::FillRule::NonZero);
|
||||
}
|
||||
if self.g.path.elements().len().saturating_add(outline.elements().len()) > super::graphics::MAX_PATH {
|
||||
return Err(PsError::Limit("a path has too many points"));
|
||||
}
|
||||
self.g.path.extend(outline);
|
||||
Ok(())
|
||||
self.extend_path(outline)
|
||||
}
|
||||
|
||||
/// `charpath`: the glyph outlines of `s` added to the path.
|
||||
fn char_path(&mut self, s: &[u8]) -> Res {
|
||||
if let Some(named) = self.named_cid_type(s)? {
|
||||
return self.show_named_cid(&named, &Spacing::Plain, Draw::Path);
|
||||
}
|
||||
if let Some(glyphs) = self.composite_glyphs(s)? {
|
||||
for g in &glyphs {
|
||||
let at = self.user_point()?;
|
||||
@@ -791,10 +887,9 @@ impl Interp<'_> {
|
||||
let at = self.user_point()?;
|
||||
let (t, layout, adv) = self.set_type(s, at)?;
|
||||
for g in &layout.glyphs {
|
||||
self.grow()?;
|
||||
let mut o = g.outline.clone();
|
||||
o.apply_affine(t.xf);
|
||||
self.g.path.extend(o);
|
||||
self.extend_path(o)?;
|
||||
}
|
||||
self.g.cur = Some(self.xf() * (at + adv));
|
||||
Ok(())
|
||||
@@ -855,6 +950,16 @@ struct Mapped {
|
||||
vertical: bool,
|
||||
}
|
||||
|
||||
/// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes
|
||||
/// with their characters, the font it is set in, whether it runs down a column, and whether each
|
||||
/// code moves the point one em (down a column, or in a CMap VectorCraft can't read).
|
||||
struct NamedCid {
|
||||
codes: Decoded,
|
||||
font: DictRef,
|
||||
vertical: bool,
|
||||
ems: bool,
|
||||
}
|
||||
|
||||
/// What drawing a glyph does with it.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Draw {
|
||||
@@ -986,9 +1091,9 @@ impl Interp<'_> {
|
||||
/// of that name and its character collection's CID → Unicode CMap (a code it doesn't map
|
||||
/// stands for none), set as type in the font of its CIDFont's name, vertical over a vertical
|
||||
/// CMap (`WMode` 1). Control codes stand for no character. Type in a CMap VectorCraft can't
|
||||
/// read is left out, with a warning.
|
||||
fn named_cid_type(&mut self, s: &[u8]) -> Res<Option<(Decoded, DictRef, bool)>> {
|
||||
let Some((cmap, font, name, vertical)) = self.named_cid_parts() else { return Ok(None) };
|
||||
/// read is left out, with a warning, each of its codes moving the point one em.
|
||||
fn named_cid_type(&mut self, s: &[u8]) -> Res<Option<NamedCid>> {
|
||||
let Some(cmap) = self.named_cid_parts().map(|(cmap, ..)| cmap) else { return Ok(None) };
|
||||
// Each code is looked up in the CMap's mappings.
|
||||
self.spend(s.len() as u64)?;
|
||||
// The decoded codes and characters are held while the string is shown: checked against
|
||||
@@ -996,25 +1101,33 @@ impl Interp<'_> {
|
||||
let held = s.len().saturating_mul(DECODED_BYTES);
|
||||
self.alloc(held)?;
|
||||
self.unalloc(held);
|
||||
let decoded = match self.predefined_codes(&cmap) {
|
||||
Some(codes) => codes.codes(s),
|
||||
let (decoded, read) = match self.predefined_codes(&cmap) {
|
||||
Some(codes) => (codes.codes(s), true),
|
||||
None => {
|
||||
self.out.warn(UNREAD_CMAP);
|
||||
Decoded::default()
|
||||
(super::predefined_cmap::unread_codes(&cmap, s), false)
|
||||
}
|
||||
};
|
||||
let mut codes = Decoded::default();
|
||||
let Some(mut named) = self.named_cid_font()? else { return Ok(None) };
|
||||
let mut chars = decoded.text.chars();
|
||||
for &(code, n) in &decoded.codes {
|
||||
codes.push(code, chars.by_ref().take(n).filter(|c| !c.is_control()));
|
||||
named.codes.push(code, chars.by_ref().take(n).filter(|c| !c.is_control()));
|
||||
}
|
||||
named.ems |= !read;
|
||||
Ok(Some(named))
|
||||
}
|
||||
|
||||
/// The font [`Self::named_cid_type`] sets type in, with no codes yet, when the current font is
|
||||
/// a CID-keyed font over a predefined CMap the file doesn't define.
|
||||
fn named_cid_font(&mut self) -> Res<Option<NamedCid>> {
|
||||
let Some((_, font, name, vertical)) = self.named_cid_parts() else { return Ok(None) };
|
||||
// The composite font is copied under the CIDFont's name for every string: charged by
|
||||
// its size, so a huge font dictionary shown in a loop runs out of the budget.
|
||||
let entries = font.borrow().len();
|
||||
self.spend(entries as u64)?;
|
||||
let mut named = font.borrow().clone();
|
||||
named.insert(Key::name("FontName"), name);
|
||||
Ok(Some((codes, DictRef::new(named), vertical)))
|
||||
Ok(Some(NamedCid { codes: Decoded::default(), font: DictRef::new(named), vertical, ems: vertical }))
|
||||
}
|
||||
|
||||
/// The CMap's name, the composite font, the CIDFont's name and the writing mode of
|
||||
@@ -1032,7 +1145,7 @@ impl Interp<'_> {
|
||||
return None;
|
||||
}
|
||||
let cmap_name = cmap.get(&Key::name("CMapName")).and_then(Obj::text)?.to_string();
|
||||
if super::cid::unicode_cmap(&cmap_name).is_none() && !super::predefined_cmap::known(&cmap_name) {
|
||||
if !super::predefined_cmap::known(&cmap_name) {
|
||||
return None;
|
||||
}
|
||||
let wmode = f.get(&Key::name("WMode")).or_else(|| cmap.get(&Key::name("WMode"))).and_then(Obj::as_num);
|
||||
@@ -1047,7 +1160,7 @@ impl Interp<'_> {
|
||||
/// How strings in predefined CMap `cmap` decode (a CMap other than a Unicode CMap read once a
|
||||
/// file); `None` when VectorCraft can't read it.
|
||||
fn predefined_codes(&mut self, cmap: &str) -> Option<Rc<super::predefined_cmap::CMapCodes>> {
|
||||
if let Some((form, _)) = super::cid::unicode_cmap(cmap) {
|
||||
if let Some(form) = super::predefined_cmap::unicode_cmap(cmap) {
|
||||
return Some(Rc::new(super::predefined_cmap::CMapCodes::Unicode(form)));
|
||||
}
|
||||
if let Some((_, codes)) = self.predefined_cmaps.iter().find(|(n, _)| **n == *cmap) {
|
||||
@@ -1060,32 +1173,53 @@ impl Interp<'_> {
|
||||
codes
|
||||
}
|
||||
|
||||
/// The codes `codes` (with their characters) set as point type at the current point in font
|
||||
/// `font` (see [`Self::named_cid_type`]), running down a column when `vertical`, which moves
|
||||
/// past them, spaced as `spacing` says, as [`Self::show_codes`] shows them. `widthshow` and
|
||||
/// `awidthshow` match a code by its value (font number 0 times 256 plus the code: PLRM 3rd ed.,
|
||||
/// `widthshow` in chapter 8); `kshow`'s procedure isn't run between them (a composite font's
|
||||
/// codes aren't single bytes). Down a column each code moves the point one em, the default
|
||||
/// vertical displacement of a CIDFont whose metrics the file doesn't give (PDF Reference 1.7,
|
||||
/// §5.6.3, `DW2`).
|
||||
fn show_named_cid(&mut self, codes: &Decoded, font: &DictRef, vertical: bool, spacing: &Spacing) -> Res {
|
||||
let widths = vertical.then(|| vec![1.0; codes.codes.len()]);
|
||||
let saved = self.g.font.replace(font.clone());
|
||||
let r = self.show_codes(codes, widths.as_deref(), spacing, vertical, &[]);
|
||||
/// Type `named` (see [`Self::named_cid_type`]) set as point type at the current point in its
|
||||
/// font, running down a column when it is vertical, which moves past it, spaced as `spacing`
|
||||
/// says, as [`Self::show_codes`] shows codes. `widthshow` and `awidthshow` match a code by its
|
||||
/// value (font number 0 times 256 plus the code: PLRM 3rd ed., `widthshow` in chapter 8), and
|
||||
/// `kshow`'s procedure gets the values of the two codes it runs between. Down a column, and in
|
||||
/// a CMap VectorCraft can't read, each code moves the point one em, the default displacement
|
||||
/// of a CIDFont whose metrics the file doesn't give (PDF Reference 1.7, §5.6.3, `DW` and
|
||||
/// `DW2`). With `draw` [`Draw::Path`] the outlines go on the current path (`charpath`).
|
||||
fn show_named_cid(&mut self, named: &NamedCid, spacing: &Spacing, draw: Draw) -> Res {
|
||||
let widths = named.ems.then(|| vec![1.0; named.codes.codes.len()]);
|
||||
let kern: Vec<u32> = match spacing {
|
||||
Spacing::Kern(_) => named.codes.codes.iter().map(|&(code, _)| code).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let saved = self.g.font.replace(named.font.clone());
|
||||
let before = std::mem::replace(&mut self.kshow_font, saved.clone());
|
||||
let r = self.show_codes(&named.codes, widths.as_deref(), spacing, named.vertical, &kern, draw);
|
||||
self.kshow_font = before;
|
||||
// A font the `kshow` procedure set stays current.
|
||||
if self.g.font.as_ref().is_none_or(|f| f.same(&named.font)) {
|
||||
self.g.font = saved;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// How far codes `codes` of type `named` move the current point (user space) when
|
||||
/// [`Self::show_named_cid`] shows them with no extra spacing.
|
||||
fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res<Vec2> {
|
||||
let saved = self.g.font.replace(named.font.clone());
|
||||
let r = self.named_cid_moved(codes, named.vertical, named.ems);
|
||||
self.g.font = saved;
|
||||
r
|
||||
}
|
||||
|
||||
/// How far the codes `codes` move the current point (user space) when [`Self::show_named_cid`]
|
||||
/// shows them with no extra spacing.
|
||||
fn named_cid_width(&mut self, codes: &Decoded, vertical: bool) -> Res<Vec2> {
|
||||
/// [`Self::named_cid_width`] in the current font: codes `codes`, vertical when `vertical`,
|
||||
/// each one em when `ems`.
|
||||
fn named_cid_moved(&mut self, codes: &Decoded, vertical: bool, ems: bool) -> Res<Vec2> {
|
||||
let (_, f1) = self.font()?;
|
||||
let moved = if vertical {
|
||||
Point::new(0.0, -(codes.codes.len() as f64))
|
||||
} else {
|
||||
let (t, layout) = self.set_placed_text(&codes.text, Point::ZERO, false)?;
|
||||
let size = t.runs.first().map_or(1.0, |r| r.style.size);
|
||||
Point::new(layout.glyphs.iter().map(|g| g.advance).sum::<f64>() / size, 0.0)
|
||||
let n = codes.codes.len() as f64;
|
||||
let moved = match (vertical, ems) {
|
||||
(true, _) => Point::new(0.0, -n),
|
||||
(false, true) => Point::new(n, 0.0),
|
||||
(false, false) => {
|
||||
let (t, layout) = self.set_placed_text(&codes.text, Point::ZERO, false)?;
|
||||
let size = t.runs.first().map_or(1.0, |r| r.style.size);
|
||||
Point::new(layout.glyphs.iter().map(|g| g.advance).sum::<f64>() / size, 0.0)
|
||||
}
|
||||
};
|
||||
Ok(f1 * moved - f1 * Point::ZERO)
|
||||
}
|
||||
@@ -1393,7 +1527,7 @@ const MISSING_CID_FONT: &str = "CID-keyed type in a font the file doesn't carry
|
||||
const DECODED_BYTES: usize = 64;
|
||||
|
||||
/// The warning for type in a predefined CMap whose mappings VectorCraft doesn't have.
|
||||
pub(super) const UNREAD_CMAP: &str = "Type in a CMap that couldn't be read was left out";
|
||||
pub(super) const UNREAD_CMAP: &str = "type in a CMap that couldn't be read was left out";
|
||||
|
||||
/// Most Type 42 fonts whose TrueType data is kept between glyphs.
|
||||
const MAX_TYPE42: usize = 16;
|
||||
|
||||
@@ -113,6 +113,8 @@ const PATTERNS: &str = "pattern fills are written as their tiles, clipped to the
|
||||
const FREEFORM: &str = "freeform gradients are written as their average colour";
|
||||
const CONIC: &str = "conic gradients are written as solid wedges clipped to the shape (legacy .ai files have no conic gradient)";
|
||||
const DIAMOND: &str = "diamond gradients are written as four linear gradients clipped to the shape (legacy .ai files have no diamond gradient)";
|
||||
const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)";
|
||||
const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGES: usize = 360;
|
||||
const STROKES: &str =
|
||||
|
||||
@@ -41,8 +41,12 @@ pub(super) fn gradient_def(s: &mut String, w: &Writer, name: &str, g: &Gradient)
|
||||
s.push_str(" 3 ");
|
||||
}
|
||||
}
|
||||
ps::push_nums(s, &[f64::from(stop.midpoint) * 100.0, f64::from(stop.offset) * 100.0]);
|
||||
s.push_str("%_Bs\n");
|
||||
// The ramp point to five decimals of its percent: a gradient's stops repeated many times
|
||||
// keep their places in each run.
|
||||
ps::push_num(s, f64::from(stop.midpoint) * 100.0);
|
||||
s.push(' ');
|
||||
ps::push_num_places(s, f64::from(stop.offset) * 100.0, 5);
|
||||
s.push_str(" %_Bs\n");
|
||||
}
|
||||
s.push_str("BD\n%AI5_EndGradient\n");
|
||||
}
|
||||
|
||||
@@ -110,6 +110,119 @@ fn conic_gradients_are_written_as_wedges_clipped_to_the_shape() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The format's gradients pad past their ends: a linear gradient that repeats or reflects is
|
||||
/// written with its stops repeated across the shape (a definition of its own, not named after the
|
||||
/// swatch), and a conic one as wedges that repeat with the stops (which print as the canvas
|
||||
/// draws them), with a warning.
|
||||
#[test]
|
||||
fn spread_gradients_are_written_with_their_stops_repeated() {
|
||||
use vectorcraft_color::{GradientGeom, GradientSpread};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let linear = |spread| {
|
||||
let mut g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(GradientKind::Linear, stops.clone()) });
|
||||
// Across the shape: three runs.
|
||||
g.geom = Some(GradientGeom {
|
||||
start: vectorcraft_geom::Point::new(20.0, 50.0),
|
||||
end: vectorcraft_geom::Point::new(180.0, 50.0),
|
||||
aspect: 1.0,
|
||||
focal: None,
|
||||
});
|
||||
g.swatch = Some("Bands".into());
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
for (spread, colors) in [
|
||||
(GradientSpread::Repeat, ["0 0 1", "1 0 0", "0 0 1", "1 0 0", "0 0 1", "1 0 0"]),
|
||||
(GradientSpread::Reflect, ["0 0 1", "1 0 0", "1 0 0", "0 0 1", "0 0 1", "1 0 0"]),
|
||||
] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), linear(spread), Paint::None);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings);
|
||||
let text = String::from_utf8_lossy(&out.bytes);
|
||||
assert!(text.contains("(Gradient) 0 6 Bd") && !text.contains("(Bands)"), "{text}");
|
||||
// A linear definition lists its stops from the last to the first, each RGB stop as
|
||||
// `c m y k r g b 2 …`.
|
||||
let def = text.split("(Gradient) 0 6 Bd\n[\n").nth(1).unwrap();
|
||||
for (line, rgb) in def.lines().take(6).zip(colors) {
|
||||
assert!(line.contains(&format!(" {rgb} 2 ")), "{spread:?}: {line} lacks {rgb}\n{def}");
|
||||
}
|
||||
}
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Conic, stops) });
|
||||
g.geom = Some(GradientGeom {
|
||||
start: vectorcraft_geom::Point::new(100.0, 50.0),
|
||||
end: vectorcraft_geom::Point::new(140.0, 30.0),
|
||||
aspect: 1.0,
|
||||
focal: None,
|
||||
});
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned();
|
||||
assert!(text.matches("\nf\n").count() >= 3 * CONIC_WEDGES, "a wedge a degree for each run");
|
||||
}
|
||||
|
||||
/// A gradient repeated more times than the reader keeps stops for is written with no more stops
|
||||
/// than it reads, with a warning, so it opens with every stop that was written.
|
||||
#[test]
|
||||
fn many_repeats_are_written_within_the_stops_the_reader_reads() {
|
||||
use vectorcraft_color::{GradientGeom, GradientSpread};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
// A run of 0.4 pt across a shape 160 pt wide: 400 runs.
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) });
|
||||
g.geom = Some(GradientGeom {
|
||||
start: vectorcraft_geom::Point::new(20.0, 50.0),
|
||||
end: vectorcraft_geom::Point::new(60.0, 50.0),
|
||||
aspect: 1.0,
|
||||
focal: None,
|
||||
});
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(out.warnings.iter().any(|w| w == SPREAD_CAPPED), "{:?}", out.warnings);
|
||||
let text = String::from_utf8_lossy(&out.bytes).into_owned();
|
||||
let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
|
||||
let written = def.matches(" %_Bs\n").count();
|
||||
assert!((2..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
|
||||
let read = crate::import(&out.bytes).unwrap().document;
|
||||
let mut stops = None;
|
||||
read.walk(|n| {
|
||||
if let (None, Paint::Gradient(g)) = (&stops, n.appearance.fill_paint()) {
|
||||
stops = Some(g.gradient.stops.len());
|
||||
}
|
||||
});
|
||||
assert_eq!(stops, Some(written), "every stop written is read");
|
||||
}
|
||||
|
||||
/// A radial gradient repeated out from a center far from the shape is written with its ramp points
|
||||
/// (percent) to five decimals, so its runs keep their places hundreds of runs out.
|
||||
#[test]
|
||||
fn far_runs_keep_their_places() {
|
||||
use vectorcraft_color::{GradientGeom, GradientSpread};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Radial, stops) });
|
||||
// Runs 0.25 pt apart, the shape 480 runs and more from the center.
|
||||
let c = vectorcraft_geom::Point::new(-100.0, 50.0);
|
||||
g.geom = Some(GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(0.25, 0.0), aspect: 1.0, focal: None });
|
||||
let bounds = Rect::new(20.0, 10.0, 180.0, 90.0);
|
||||
let padded = g.gradient.padded_within(&g.geom.unwrap(), bounds, crate::import::MAX_GRADIENT_STOPS).unwrap();
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::rectangle(bounds), Paint::Gradient(Box::new(g)), Paint::None);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned();
|
||||
let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
|
||||
let ramps: Vec<f64> = def.lines().filter_map(|l| l.strip_suffix(" %_Bs")).map(|l| l.rsplit(' ').next().unwrap().parse().unwrap()).collect();
|
||||
assert_eq!(ramps.len(), padded.gradient.stops.len());
|
||||
for (ramp, stop) in ramps.iter().zip(&padded.gradient.stops) {
|
||||
assert!((ramp / 100.0 - f64::from(stop.offset)).abs() < 2e-7, "{ramp} for {}", stop.offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// The format has no diamond gradient: a diamond fill, and a diamond stroke (written as its filled
|
||||
/// outline), are four path objects clipped to the shape, each a linear gradient over a quadrant
|
||||
/// of the diamond's frame, with a warning; the definition is not named after the swatch.
|
||||
@@ -139,6 +252,32 @@ fn diamond_gradients_are_written_as_four_linear_gradients_clipped_to_the_shape()
|
||||
}
|
||||
}
|
||||
|
||||
/// A diamond gradient that repeats is four linear gradients over the quadrants of its frame, each
|
||||
/// with its stops repeated out to the shape's edge, with a warning.
|
||||
#[test]
|
||||
fn a_spread_diamond_repeats_in_each_quadrant() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(GradientKind::Diamond, stops) });
|
||||
g.geom = Some(vectorcraft_color::GradientGeom {
|
||||
start: vectorcraft_geom::Point::new(100.0, 50.0),
|
||||
end: vectorcraft_geom::Point::new(140.0, 30.0),
|
||||
aspect: 0.7,
|
||||
focal: None,
|
||||
});
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(out.warnings.iter().any(|w| w == DIAMOND) && out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings);
|
||||
let text = String::from_utf8_lossy(&out.bytes).into_owned();
|
||||
assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant");
|
||||
let defs: Vec<usize> =
|
||||
text.split("%AI5_BeginGradient: ").skip(1).map(|d| d.split("%AI5_EndGradient").next().unwrap_or("").matches(" %_Bs\n").count()).collect();
|
||||
assert!(!defs.is_empty() && defs.iter().all(|&n| n >= 6), "stops in each definition: {defs:?}");
|
||||
}
|
||||
|
||||
/// `doc` written with options `o`. Every file the tests write is also run as a PostScript program
|
||||
/// ([`prints_as`]) and must draw what `doc` draws.
|
||||
fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput {
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::{
|
||||
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
|
||||
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
|
||||
};
|
||||
use super::{CONIC, CONIC_WEDGES, DIAMOND};
|
||||
use super::{CONIC, CONIC_WEDGES, DIAMOND, SPREAD, SPREAD_CAPPED};
|
||||
|
||||
pub(super) struct Writer<'a> {
|
||||
doc: &'a Document,
|
||||
@@ -487,7 +487,8 @@ impl<'a> Writer<'a> {
|
||||
self.warn(TRANSPARENCY);
|
||||
}
|
||||
let area = path.to_bezpath().bounding_box();
|
||||
let wedges = g.resolve(area).conic_wedges(area, CONIC_WEDGES, true);
|
||||
let wedges = g.resolve(area).conic_wedges(area, g.gradient.conic_wedge_count(CONIC_WEDGES), true);
|
||||
let spread = g.gradient.spreader();
|
||||
self.line("q");
|
||||
self.fill_rule(rule);
|
||||
let several = path.subpaths.len() > 1;
|
||||
@@ -501,7 +502,7 @@ impl<'a> Writer<'a> {
|
||||
self.line("*U");
|
||||
}
|
||||
for (pts, t) in wedges {
|
||||
let (color, _) = g.gradient.sample_keep_model(t as f32);
|
||||
let (color, _) = g.gradient.sample_keep_model(spread(t) as f32);
|
||||
let wedge = FillLayer { paint: Paint::solid(color), ..f.clone() };
|
||||
self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&wedge), None);
|
||||
}
|
||||
@@ -678,6 +679,22 @@ impl<'a> Writer<'a> {
|
||||
/// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center,
|
||||
/// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`.
|
||||
fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String {
|
||||
// A gradient that repeats or reflects (the format's gradients pad past their ends): its
|
||||
// stops repeated as many times as `bounds` needs, in a definition of its own, no more
|
||||
// stops than the reader reads.
|
||||
if let Some(padded) = g.gradient.padded_within(&g.resolve(bounds), bounds, crate::import::MAX_GRADIENT_STOPS) {
|
||||
self.warn(if padded.capped { SPREAD_CAPPED } else { SPREAD });
|
||||
let geom = padded.geom;
|
||||
let p = GradientPaint { gradient: padded.gradient, geom: Some(geom), angle: geom.angle_deg(), swatch: None, ..g.clone() };
|
||||
return self.gradient(&p, bounds);
|
||||
}
|
||||
// One whose levels over `bounds` are not finite (a vector of no length): its stops
|
||||
// repeated along the vector, padding past it.
|
||||
if g.gradient.is_spread() {
|
||||
self.warn(SPREAD_CAPPED);
|
||||
let p = GradientPaint { gradient: g.gradient.unrolled_within(crate::import::MAX_GRADIENT_STOPS).into_owned(), swatch: None, ..g.clone() };
|
||||
return self.gradient(&p, bounds);
|
||||
}
|
||||
let name = self.define(&g.gradient, g.swatch.as_deref());
|
||||
for stop in &g.gradient.stops {
|
||||
if stop.opacity < 1.0 {
|
||||
|
||||
+27
-5
@@ -33,11 +33,19 @@ pub(crate) fn num(v: f64) -> String {
|
||||
|
||||
/// Append [`num`]`(v)` to `s`.
|
||||
pub(crate) fn push_num(s: &mut String, v: f64) {
|
||||
// Beyond ~1.8e304 the scaling overflows; such values have no fractional digits to round.
|
||||
push_num_places(s, v, 4);
|
||||
}
|
||||
|
||||
/// Append `v` to `s` with at most `places` decimals (up to 9), no trailing zeros (0 when not
|
||||
/// finite).
|
||||
pub(crate) fn push_num_places(s: &mut String, v: f64, places: u32) {
|
||||
let places = places.min(9);
|
||||
let scale = 10f64.powi(places as i32);
|
||||
// Past where the scaling overflows, values have no fractional digits to round.
|
||||
let v = if !v.is_finite() {
|
||||
0.0
|
||||
} else if (v * 10_000.0).is_finite() {
|
||||
(v * 10_000.0).round() / 10_000.0
|
||||
} else if (v * scale).is_finite() {
|
||||
(v * scale).round() / scale
|
||||
} else {
|
||||
v
|
||||
};
|
||||
@@ -46,7 +54,7 @@ pub(crate) fn push_num(s: &mut String, v: f64) {
|
||||
return;
|
||||
}
|
||||
let start = s.len();
|
||||
let _ = write!(s, "{v:.4}");
|
||||
let _ = write!(s, "{v:.*}", places as usize);
|
||||
let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len();
|
||||
s.truncate(start + keep);
|
||||
}
|
||||
@@ -291,7 +299,7 @@ pub(crate) fn inflate(data: &[u8], max: u64) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ascii85, ascii85_decode, num};
|
||||
use super::{ascii85, ascii85_decode, num, push_num_places};
|
||||
|
||||
#[test]
|
||||
fn ascii85_first_line_never_starts_with_percent() {
|
||||
@@ -308,4 +316,18 @@ mod tests {
|
||||
assert!(!s.is_empty() && s.chars().all(|c| c.is_ascii_digit() || c == '-' || c == '.'), "{v}: got {s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_keep_the_decimals_asked_for() {
|
||||
let places = |v: f64, n: u32| {
|
||||
let mut s = String::new();
|
||||
push_num_places(&mut s, v, n);
|
||||
s
|
||||
};
|
||||
assert_eq!(num(0.123_456_78), "0.1235");
|
||||
assert_eq!(places(0.123_456_78, 7), "0.1234568");
|
||||
assert_eq!(places(f64::from(0.4f32), 7), "0.4");
|
||||
assert_eq!(places(2.5, 7), "2.5");
|
||||
assert_eq!(places(f64::NAN, 7), "0");
|
||||
}
|
||||
}
|
||||
+40
-6
@@ -44,8 +44,12 @@ const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a Dev
|
||||
const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors";
|
||||
const CONIC_WEDGES: &str = "conic gradients are written as solid wedges (EPS has no conic shading)";
|
||||
const DIAMOND_QUADRANTS: &str = "diamond gradients are written as four linear gradients (EPS has no diamond shading)";
|
||||
const SPREAD_CAPPED: &str =
|
||||
"gradients that repeat or reflect are written with at most 256 runs of their stops (at most 16384 stops); they pad past those";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGE_COUNT: usize = 360;
|
||||
/// Decimals of a smooth shading's stitching function bounds (stop offsets, 0 to 1).
|
||||
const BOUNDS_PLACES: u32 = 7;
|
||||
/// The most colorants a DeviceN color space may have (PostScript's limit).
|
||||
const MAX_DEVICE_N: usize = 32;
|
||||
const MISSING_PATTERN: &str = "missing patterns are written as mid-grey";
|
||||
@@ -940,6 +944,23 @@ impl<'a> Scene<'a> {
|
||||
/// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]).
|
||||
fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) {
|
||||
let geom = g.resolve(bounds);
|
||||
// A linear, radial or diamond gradient that repeats or reflects: PostScript's shadings
|
||||
// pad past their ends, so its stops are repeated as many times as the area needs.
|
||||
if let Some(padded) = g.gradient.padded_over(&geom, area) {
|
||||
if padded.capped {
|
||||
self.warn(SPREAD_CAPPED);
|
||||
}
|
||||
let geom = padded.geom;
|
||||
let paint = GradientPaint { gradient: padded.gradient, geom: Some(geom), angle: geom.angle_deg(), ..g.clone() };
|
||||
return self.gradient(&paint, bounds, area);
|
||||
}
|
||||
// One whose levels over the area are not finite (a vector of no length): its stops
|
||||
// repeated along the vector, padding past it.
|
||||
if g.gradient.is_spread() && g.gradient.kind != GradientKind::Conic {
|
||||
self.warn(SPREAD_CAPPED);
|
||||
let paint = GradientPaint { gradient: g.gradient.unrolled().into_owned(), ..g.clone() };
|
||||
return self.gradient(&paint, bounds, area);
|
||||
}
|
||||
let (space, stops) = self.gradient_stops(&g.gradient);
|
||||
if !stops.windows(2).any(|w| w[1].0 > w[0].0) {
|
||||
if let Some((_, c)) = stops.first() {
|
||||
@@ -951,7 +972,7 @@ impl<'a> Scene<'a> {
|
||||
let space = &space;
|
||||
let smooth = self.o.level == Level::Three && !self.o.compatible_gradients;
|
||||
match g.gradient.kind {
|
||||
GradientKind::Conic => self.conic_steps(&geom, area, space, &stops),
|
||||
GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient),
|
||||
GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth),
|
||||
GradientKind::Radial => {
|
||||
let r = geom.length().max(1e-6);
|
||||
@@ -984,15 +1005,24 @@ impl<'a> Scene<'a> {
|
||||
/// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area`
|
||||
/// (PostScript has no conic shading), each running on to the seam under the next, so no
|
||||
/// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]).
|
||||
fn conic_steps(&mut self, geom: &vectorcraft_color::GradientGeom, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)]) {
|
||||
/// Stops of `g` that repeat or reflect get that many wedges for each time they run around.
|
||||
fn conic_steps(
|
||||
&mut self,
|
||||
geom: &vectorcraft_color::GradientGeom,
|
||||
area: Rect,
|
||||
space: &GradientSpace,
|
||||
stops: &[(f64, Vec<f32>)],
|
||||
g: &vectorcraft_color::Gradient,
|
||||
) {
|
||||
self.warn(CONIC_WEDGES);
|
||||
let spread = g.spreader();
|
||||
let at = |t: f64| match stops.windows(2).find(|w| t <= w[1].0) {
|
||||
Some(w) if w[1].0 > w[0].0 => mix(&w[0].1, &w[1].1, ((t - w[0].0) / (w[1].0 - w[0].0)).clamp(0.0, 1.0) as f32),
|
||||
Some(w) => w[1].1.clone(),
|
||||
None => stops.last().map_or_else(Vec::new, |s| s.1.clone()),
|
||||
};
|
||||
for (pts, t) in geom.conic_wedges(area, CONIC_WEDGE_COUNT, true) {
|
||||
self.set_comps(space, &at(t));
|
||||
for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) {
|
||||
self.set_comps(space, &at(spread(t)));
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
push_nums(&mut self.body, &[p.x, p.y]);
|
||||
self.line(if i == 0 { "newpath moveto" } else { "lineto" });
|
||||
@@ -1059,8 +1089,12 @@ impl<'a> Scene<'a> {
|
||||
f.push('\n');
|
||||
}
|
||||
f.push_str("] /Bounds [");
|
||||
let bounds: Vec<f64> = many.iter().skip(1).map(|w| w[0].0).collect();
|
||||
push_nums(&mut f, &bounds);
|
||||
// Seven decimals: a gradient's stops repeated hundreds or thousands of times
|
||||
// (`Gradient::padded_over`) keep their places in each run.
|
||||
for w in many.iter().skip(1) {
|
||||
ps::push_num_places(&mut f, w[0].0, BOUNDS_PLACES);
|
||||
f.push(' ');
|
||||
}
|
||||
f.push_str("] /Encode [");
|
||||
f.push_str(&"0 1 ".repeat(many.len()));
|
||||
f.push_str("] >>");
|
||||
|
||||
@@ -244,6 +244,82 @@ fn diamond_gradients_are_four_linear_gradients_clipped_to_quadrants() {
|
||||
);
|
||||
}
|
||||
|
||||
/// PostScript's shadings pad past their ends: a linear, radial or diamond gradient that repeats or
|
||||
/// reflects is written with its stops repeated over the shape, a conic one as wedges that repeat
|
||||
/// with the stops; read back from the PostScript, each looks as the canvas paints it, at Level 3
|
||||
/// and Level 2.
|
||||
#[test]
|
||||
fn spread_gradients_are_written_with_their_stops_repeated() {
|
||||
use vectorcraft_color::{GradientGeom, GradientSpread};
|
||||
let c = Point::new(100.0, 100.0);
|
||||
let around = GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(60.0, -25.0), aspect: 0.7, focal: None };
|
||||
let cases = [
|
||||
(GradientKind::Linear, GradientGeom { start: Point::new(70.0, 80.0), end: Point::new(150.0, 110.0), aspect: 1.0, focal: None }),
|
||||
(GradientKind::Radial, around),
|
||||
(GradientKind::Radial, GradientGeom { focal: Some(c + vectorcraft_geom::Vec2::new(-15.0, 12.0)), ..around }),
|
||||
(GradientKind::Conic, around),
|
||||
(GradientKind::Diamond, around),
|
||||
];
|
||||
for (kind, geom) in cases {
|
||||
for spread in [GradientSpread::Repeat, GradientSpread::Reflect] {
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, stops) });
|
||||
g.geom = Some(geom);
|
||||
let paint = Paint::Gradient(Box::new(g));
|
||||
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint, Paint::None, 0.0)]);
|
||||
for o in [opts(&d), EpsOptions { level: Level::Two, ..opts(&d) }] {
|
||||
let out = export(&d, &o, None, None).unwrap();
|
||||
let back = import_with(&out.bytes, false).unwrap().document;
|
||||
let (a, b) = (vectorcraft_testkit::raster::render_artboard(&d), vectorcraft_testkit::raster::render_artboard(&back));
|
||||
let st = vectorcraft_testkit::raster::perceptual_diff(&a, &b, 12.0);
|
||||
assert!(
|
||||
(st.bad_pixels as f64) < 0.03 * st.pixels as f64,
|
||||
"{kind:?} {spread:?} level {:?}: {} of {} pixels differ",
|
||||
o.level,
|
||||
st.bad_pixels,
|
||||
st.pixels
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats with no stops (a file can hold one) is written as one that pads, to
|
||||
/// EPS, legacy `.ai` and the `.ai` editing data.
|
||||
#[test]
|
||||
fn a_spread_gradient_without_stops_is_written() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
|
||||
let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) });
|
||||
let paint = Paint::Gradient(Box::new(g));
|
||||
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]);
|
||||
export(&d, &opts(&d), None, None).unwrap();
|
||||
export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap();
|
||||
crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient repeated 256 times across the shape keeps each run's place: the smooth shading's
|
||||
/// stitching bounds lie where the runs meet, to well under a run's thousandth.
|
||||
#[test]
|
||||
fn many_repeats_keep_their_places_in_a_smooth_shading() {
|
||||
use vectorcraft_color::{GradientGeom, GradientSpread};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
// A run of 0.4 pt across a shape 160 pt wide: capped at 256 runs.
|
||||
let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) });
|
||||
g.geom = Some(GradientGeom { start: Point::new(20.0, 100.0), end: Point::new(60.0, 100.0), aspect: 1.0, focal: None });
|
||||
let paint = Paint::Gradient(Box::new(g));
|
||||
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint, Paint::None, 0.0)]);
|
||||
let page = page_of(&d, &opts(&d));
|
||||
let bounds: Vec<f64> =
|
||||
page.split("/Bounds [").nth(1).and_then(|s| s.split(']').next()).unwrap().split_whitespace().map(|v| v.parse().unwrap()).collect();
|
||||
let runs = (bounds.len() + 1) as f64;
|
||||
assert_eq!(runs, 256.0, "{bounds:?}");
|
||||
for b in bounds {
|
||||
assert!((b * runs - (b * runs).round()).abs() < 1e-3, "bound {b} is {} runs along", b * runs);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strokes_keep_their_caps_joins_and_dashes() {
|
||||
let d = doc_with(|d| {
|
||||
|
||||
@@ -18,6 +18,25 @@ use std::io::{self, Write as _};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Whether the returned write error refuses this location. Recovery errors must still be shown:
|
||||
/// their message names copies the user may need, even when their kind is PermissionDenied.
|
||||
pub fn read_only_location(error: &io::Error) -> bool {
|
||||
matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied)
|
||||
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>())
|
||||
}
|
||||
|
||||
/// Marks the existing recovery message without changing its text or the returned error kind.
|
||||
#[derive(Debug)]
|
||||
struct RecoveryError(String);
|
||||
|
||||
impl std::fmt::Display for RecoveryError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RecoveryError {}
|
||||
|
||||
/// Write `bytes` to `path` atomically (see the module docs).
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
write_atomic_with(path, |f| f.write_all(bytes))
|
||||
@@ -102,7 +121,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
let _ = std::fs::remove_file(old);
|
||||
let why =
|
||||
format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display());
|
||||
return Err(io::Error::new(refused.kind(), why));
|
||||
return Err(io::Error::new(refused.kind(), RecoveryError(why)));
|
||||
}
|
||||
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
|
||||
drop((from, to));
|
||||
@@ -115,10 +134,11 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
(Err(e), Some(old)) => {
|
||||
Err(io::Error::new(e.kind(), format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())))
|
||||
}
|
||||
(Err(e), None) => Err(io::Error::new(e.kind(), format!("{e} (the new content is kept in {})", tmp.display()))),
|
||||
(Err(e), Some(old)) => Err(io::Error::new(
|
||||
e.kind(),
|
||||
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())),
|
||||
)),
|
||||
(Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,6 +338,24 @@ fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn readonly_classification_uses_the_terminal_kind_and_excludes_recovery() {
|
||||
for (kind, expected) in [
|
||||
(io::ErrorKind::PermissionDenied, true),
|
||||
(io::ErrorKind::ReadOnlyFilesystem, true),
|
||||
(io::ErrorKind::StorageFull, false),
|
||||
(io::ErrorKind::QuotaExceeded, false),
|
||||
(io::ErrorKind::NotFound, false),
|
||||
(io::ErrorKind::Other, false),
|
||||
] {
|
||||
assert_eq!(read_only_location(&io::Error::new(kind, "injected")), expected, "{kind:?}");
|
||||
let recovery = io::Error::new(kind, RecoveryError("the new content is kept in a.tmp".into()));
|
||||
assert!(!read_only_location(&recovery), "recovery: {kind:?}");
|
||||
assert_eq!(recovery.kind(), kind);
|
||||
assert_eq!(recovery.to_string(), "the new content is kept in a.tmp");
|
||||
}
|
||||
}
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vc-atomic-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
|
||||
@@ -55,7 +55,7 @@ use serde::{Deserializer, Serialize};
|
||||
use vectorcraft_doc::{Document, ImageBlob};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
pub use craft_vectorcraft_format::{
|
||||
BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part,
|
||||
|
||||
@@ -358,6 +358,29 @@ fn save_file_waits_for_the_file_in_the_app() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_save_file_keeps_the_stable_error_prefix() {
|
||||
struct Refused(bool);
|
||||
impl Backend for Refused {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
assert_eq!(method, "app.save");
|
||||
assert_eq!(params.get("wait").and_then(Value::as_bool), self.0.then_some(true));
|
||||
Err(vectorcraft_engine::EngineError::ReadOnlyLocation("Poster.svg: injected refusal".into()).to_string())
|
||||
}
|
||||
fn has_ui(&self) -> bool {
|
||||
self.0
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
"injected save refusal".into()
|
||||
}
|
||||
}
|
||||
for desktop in [false, true] {
|
||||
let r = call_tool(&mut Refused(desktop), "save_file", &json!({}));
|
||||
assert!(r.is_error);
|
||||
assert_eq!(r.content[0]["text"], "save_file: READ_ONLY_LOCATION: Poster.svg: injected refusal");
|
||||
}
|
||||
}
|
||||
|
||||
fn pdf_pages(pdf: &[u8]) -> usize {
|
||||
let mut h = Headless::new();
|
||||
h.call("engine.execute", json!({"command": "document.open", "params": {"name": "p.pdf", "dataBase64": vectorcraft_format::base64_encode(pdf)}}))
|
||||
|
||||
@@ -39,7 +39,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.save",
|
||||
"Save",
|
||||
"Cmd+S",
|
||||
"{path?, format?, options?, svg?: {…SVG options}} = document.save, written through the app (a document saved as SVG, PDF or .ai, or opened from one Save can write back, saves as that again, with the same options); with no path known (never saved, converted) the Save As panel asks first",
|
||||
"{path?, format?, options?, svg?: {…SVG options}} = document.save, written through the app (a document saved as SVG, PDF or .ai, or opened from one Save can write back, saves as that again, with the same options); with no path known (never saved, converted) the Save As panel asks first; ordinary Save to the document's existing file refused by filesystem permissions or a read-only volume opens Save As in Documents with the same name, format and options; cancelling keeps the original path and modified state. Explicit destinations and Close/Quit keep their existing error dialog. Automation gets READ_ONLY_LOCATION: followed by the reason and no panel",
|
||||
),
|
||||
(
|
||||
"file.place",
|
||||
@@ -801,7 +801,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; Escape cancels it and the colors stay as they were. ui.inspect reports `screenSampler: true` until it answers. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS and in browsers) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
|
||||
@@ -415,13 +415,13 @@ impl<'a> Scene<'a> {
|
||||
field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect()
|
||||
} else {
|
||||
let geom = g.resolve(bounds);
|
||||
let sample = g.gradient.sampler();
|
||||
let (sample, spread) = (g.gradient.sampler(), g.gradient.spreader());
|
||||
let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows));
|
||||
(0..usize::from(rows) * usize::from(cols))
|
||||
.flat_map(|i| {
|
||||
let (x, y) = (i % usize::from(cols), i / usize::from(cols));
|
||||
let p = Point::new(area.x0 + (x as f64 + 0.5) * cw, area.y0 + (y as f64 + 0.5) * ch);
|
||||
let t = geom.param_at(g.gradient.kind, p);
|
||||
let t = spread(geom.param_at(g.gradient.kind, p));
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (c, a) = sample(t as f32);
|
||||
c.to_rgba8(a)
|
||||
|
||||
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user