Merge main into fix/global-edit-stale-points

This commit is contained in:
dotCooCoo committed 2026-12-03 08:56:53 -08:00
commit 5ff65970f9
135 files changed
+5722 -421

No files matched your search

Generated
+2
View File
@@ -10437,7 +10437,9 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
name = "xtask"
version = "0.25.1"
dependencies = [
"craft-fonts-build",
"serde_json",
"tempfile",
]
[[package]]
+104 -29
View File
@@ -177,9 +177,10 @@ mod system {
return Vec::new();
}
let named = cups_server();
let sockets = local_sockets();
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
// so its sizes come from the server.
if scheduler_is_local(named.as_deref()) {
if scheduler_is_local(named.as_deref(), &sockets, real_path) {
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
@@ -199,7 +200,7 @@ mod system {
}
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path);
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -234,17 +235,52 @@ mod system {
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
#[cfg(not(windows))]
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
/// does not go to.
/// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS).
#[cfg(not(windows))]
pub(super) fn real_path(path: &str) -> Option<String> {
std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned())
}
/// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add.
#[cfg(not(windows))]
pub(super) fn local_sockets() -> Vec<String> {
use std::io::Read as _;
let mut text = String::new();
let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text));
cupsd_listen_sockets(if read.is_ok() { &text } else { "" })
}
/// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`.
#[cfg(not(windows))]
pub(super) fn cupsd_listen_sockets(text: &str) -> Vec<String> {
let listed = text.lines().filter_map(|line| {
let line = cups_conf_line(line);
let (key, value) = line.trim().split_once(char::is_whitespace)?;
let value = value.trim();
(key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string())
});
CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect()
}
/// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the
/// real paths of both.
#[cfg(not(windows))]
fn is_local_socket(path: &str, sockets: &[impl AsRef<str>], resolve: impl Fn(&str) -> Option<String>) -> bool {
let path = path.trim();
let real = resolve(path);
sockets.iter().any(|s| {
let s = s.as_ref();
s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real))
})
}
/// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path.
/// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost`
/// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A
/// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named,
/// and the lookup is skipped.
///
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
#[cfg(not(windows))]
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option<String>) -> Option<String> {
match named {
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None,
Some(server) => Some(server),
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
}
@@ -268,14 +304,15 @@ mod system {
client_conf_server_name(&text)
})
}
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
/// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain
/// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix.
/// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder
/// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket.
#[cfg(not(windows))]
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option<String>) -> bool {
let Some(server) = server.map(str::trim) else { return true };
if server.starts_with('/') {
return true;
return is_local_socket(server, sockets, resolve);
}
// A network name may end in `/version=1.1`.
let server = server.split_once('/').map_or(server, |(server, _)| server);
@@ -289,17 +326,22 @@ mod system {
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
loopback && port.is_none_or(|port| port.trim() == "631")
}
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
/// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
/// dropped and the rest of the line is kept as written.
#[cfg(not(windows))]
fn cups_conf_line(line: &str) -> String {
match line.find('#') {
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
Some(at) => line[..at].to_string(),
None => line.to_string(),
}
}
/// The last `ServerName` in a `client.conf`.
#[cfg(not(windows))]
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
text.lines().rev().find_map(|line| {
let kept = match line.find('#') {
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
Some(at) => line[..at].to_string(),
None => line.to_string(),
};
let kept = cups_conf_line(line);
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
})
@@ -604,18 +646,47 @@ mod turn_tests {
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local};
#[test]
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
let none = |_: &str| false;
let socket = |s: &str| s == "/run/cups/cups.sock";
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
assert_eq!(ipp_server(None, socket), None);
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
let real = |_: &str| None;
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631");
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None);
assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket");
let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked);
assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631"));
assert_eq!(ipp_server(None, socket, real), None);
assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost"));
}
#[test]
fn a_socket_the_local_cupsd_listens_on_counts_as_local() {
let real = |_: &str| None;
let sockets = cupsd_listen_sockets(
"Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n",
);
assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue");
assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing");
assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock"));
assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock"));
}
/// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`.
fn linked(path: &str) -> Option<String> {
path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}"))
}
#[test]
fn a_socket_path_counts_as_local_only_when_it_is_cups_own() {
let real = |_: &str| None;
let own = cupsd_listen_sockets("");
assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder");
assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler");
assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked));
}
#[test]
@@ -623,6 +694,8 @@ mod client_conf_tests {
for local in [
None,
Some("/run/cups/cups.sock"),
Some(" /var/run/cups/cups.sock "),
Some("/private/var/run/cupsd"),
Some("localhost"),
Some("LocalHost:631"),
Some("localhost:631"),
@@ -633,7 +706,7 @@ mod client_conf_tests {
Some("localhost/version=1.1"),
Some("localhost:631/version=1.1"),
] {
assert!(scheduler_is_local(local), "{local:?}");
assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}");
}
for remote in [
"print.example.com",
@@ -647,8 +720,10 @@ mod client_conf_tests {
"127.0.0.1:8631",
"[::1]:8631",
"localhost:8631/version=1.1",
"/tmp/other.sock",
"/home/me/.cups/second.sock",
] {
assert!(!scheduler_is_local(Some(remote)), "{remote}");
assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}");
}
}
+12
View File
@@ -2,6 +2,17 @@
//! File › Open and Place, SVG import, and embedded and linked images read their pixels with
//! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`].
thread_local! {
/// Images [`decode_image`] has decoded, or tried, on this thread ([`decodes`]).
static DECODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many images [`decode_image`] has decoded on this thread so far, failed decodes included.
/// Images other threads decode are not counted.
pub fn decodes() -> u64 {
DECODES.with(std::cell::Cell::get)
}
/// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds.
pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
@@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
/// with it.
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
DECODES.with(|n| n.set(n.get() + 1));
let opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
keep_orientation: true,
+127 -6
View File
@@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
id: HALFTONE,
label: "Vector Halftone…",
menu: &["Effect", "Color Effects"],
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; a named style sets the shape and angle over the stored ones: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°; effect.apply and effect.setParams refuse an unknown style), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
defaults: json!({"shape": "circle", "style": "custom", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
raster: false,
lengths: Lengths::default(),
}]
@@ -71,6 +71,23 @@ pub enum DotShape {
Elliptical,
}
/// The named styles: each sets a dot shape and a screen angle.
pub const STYLES: [(&str, DotShape, f64); 4] = [
("grid", DotShape::Euclidean, 0.0),
("gridAngle", DotShape::Euclidean, 45.0),
("gridDots", DotShape::Circle, 0.0),
("gridDotsAngle", DotShape::Circle, 45.0),
];
/// The shape and angle of style `s`: `Some(None)` for `custom` (the shape and angle as given),
/// `None` for an unknown style.
pub fn style(s: &str) -> Option<Option<(DotShape, f64)>> {
if s.eq_ignore_ascii_case("custom") {
return Some(None);
}
STYLES.iter().find(|(name, ..)| name.eq_ignore_ascii_case(s)).map(|&(_, shape, angle)| Some((shape, angle)))
}
impl DotShape {
pub fn parse(s: &str) -> Option<Self> {
Some(match s.to_ascii_lowercase().as_str() {
@@ -89,6 +106,10 @@ impl DotShape {
/// running along x.
fn path(self, t: f64, s: f64) -> PathData {
let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side)));
// A full-tone dot is the cell itself; Line keeps its overlap along the row.
if t >= 1.0 && self != DotShape::Line {
return square(s);
}
match self {
DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle),
DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse),
@@ -413,6 +434,12 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
let r = lo + (hi - lo) * (x - i as f64);
if matches!(kind, CellKind::Circle | CellKind::Ellipse) {
let (a, b) = if matches!(kind, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) };
if t > 0.0 && a <= 1.0 && b <= 1.0 {
return shapes::ellipse(Rect::new(-a * h, -b * h, a * h, b * h));
}
}
let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h));
PathData::from_bezpath(&four_quadrants(&q1))
}
@@ -423,8 +450,13 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
let mut bp = BezPath::new();
let mut end: Option<Point> = None;
// A piece lying on an axis would be drawn back over by its mirror image, so it is left out.
let on_axis = |c: &CubicBez| {
let pts = [c.p0, c.p1, c.p2, c.p3];
pts.iter().all(|p| p.x.abs() < 1e-9) || pts.iter().all(|p| p.y.abs() < 1e-9)
};
let mut add = |curves: Vec<CubicBez>| {
for (k, c) in curves.iter().enumerate() {
for (k, c) in curves.iter().filter(|c| !on_axis(c)).enumerate() {
if k == 0 {
match end {
None => bp.move_to(c.p0),
@@ -440,7 +472,9 @@ fn four_quadrants(q1: &[CubicBez]) -> BezPath {
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))));
add(mapped(q1, |p| Point::new(-p.x, -p.y)));
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))));
bp.close_path();
if end.is_some() {
bp.close_path();
}
bp
}
@@ -540,10 +574,12 @@ impl Halftone {
}
fn from_params(p: &Value) -> Self {
// A named style sets the shape and angle over the stored ones (which hold the defaults).
let styled = style(text(p, "style", "custom")).flatten();
Self {
shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle),
shape: styled.map_or_else(|| DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), |s| s.0),
frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0),
angle: num(p, "angle", 45.0),
angle: styled.map_or_else(|| num(p, "angle", 45.0), |s| s.1),
mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"),
color: crate::raster::color_param(p, Color::BLACK),
from_art: flag(p, "fromArt", false),
@@ -781,6 +817,46 @@ mod tests {
assert_eq!(h.color, Color::BLACK);
}
#[test]
fn round_dots_inside_the_cell_have_four_anchors() {
for (shape, tone) in [(DotShape::Circle, 0.5), (DotShape::Ellipse, 0.3)] {
let dot = shape.path(tone, 10.0);
assert_eq!(dot.subpaths.len(), 1, "{shape:?}");
let sp = &dot.subpaths[0];
assert!(sp.closed, "{shape:?}");
assert_eq!(sp.anchors.len(), 4, "{shape:?}: {:?}", sp.anchors);
}
}
/// Dots whose quadrants meet on the axes have no extra anchors at the joins: a Circle dot small
/// enough to stay inside its cell has the anchors of its arcs only, all distinct.
#[test]
fn dot_quadrants_join_without_extra_anchors() {
let dot = DotShape::Circle.path(0.2, 10.0);
let anchors: Vec<Point> = dot.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect();
for (i, a) in anchors.iter().enumerate() {
assert!(anchors[i + 1..].iter().all(|b| a.distance(*b) > 1e-6), "{anchors:?}");
}
for shape in [DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
for t in [0.2, 0.6, 0.9] {
for sp in &shape.path(t, 10.0).subpaths {
let n = sp.anchors.len();
for i in 0..n {
let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p);
assert!(n < 2 || a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors);
}
}
}
}
}
#[test]
fn zero_tone_quadrant_dots_have_empty_paths() {
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
assert!(shape.path(0.0, 10.0).is_empty(), "{shape:?}");
}
}
#[test]
fn values_out_of_range_are_brought_in() {
let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap();
@@ -817,6 +893,51 @@ mod tests {
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
}
#[test]
fn grid_dots_fill_the_cell_at_full_tone() {
for name in ["gridDots", "gridDotsAngle"] {
let Some(Some((shape, _))) = style(name) else { panic!("{name} is not a style") };
// At 100% the cell's corners are covered, so neighboring cells leave no holes.
assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{name}");
// Below it the corners stay light.
assert!(!covers(shape, 0.9, (0.49, 0.49)), "{name}");
}
}
#[test]
fn full_tone_dots_have_exactly_the_cell_corners() {
let Some(Some((grid_dots, _))) = style("gridDots") else { panic!("gridDots is not a style") };
let corners = [Point::new(-5.0, -5.0), Point::new(5.0, -5.0), Point::new(5.0, 5.0), Point::new(-5.0, 5.0)];
for shape in [grid_dots, DotShape::Ellipse, DotShape::Square, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
let dot = shape.path(1.0, 10.0);
assert_eq!(dot.subpaths.len(), 1, "{shape:?}");
let sp = &dot.subpaths[0];
assert!(sp.closed, "{shape:?}");
let anchors: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
assert_eq!(anchors.len(), 4, "{shape:?}: {anchors:?}");
for corner in corners {
assert!(anchors.contains(&corner), "{shape:?}: {anchors:?}");
}
}
}
#[test]
fn styles_set_the_shape_and_angle() {
let defaults = crate::effect_info(HALFTONE).unwrap().defaults;
let with = |style: &str| {
let mut p = defaults.clone();
p["style"] = json!(style);
let h = Halftone::of(&effect(p)).unwrap();
(h.shape, h.angle)
};
assert_eq!(with("grid"), (DotShape::Euclidean, 0.0));
assert_eq!(with("gridAngle"), (DotShape::Euclidean, 45.0));
assert_eq!(with("gridDots"), (DotShape::Circle, 0.0));
assert_eq!(with("custom"), (DotShape::Circle, 45.0));
assert_eq!(with("checker"), (DotShape::Circle, 45.0));
assert_eq!((style("GRIDDOTS"), style("custom"), style("checker")), (Some(Some((DotShape::Circle, 0.0))), Some(None), None));
}
#[test]
fn spot_dots_cover_the_tone() {
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
+96 -10
View File
@@ -6,12 +6,12 @@
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use vectorcraft_render::drawn_bounds_with;
@@ -36,7 +36,22 @@ pub fn specs() -> Vec<CommandSpec> {
"Mark Bounds of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \
\"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \
\"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 \
(10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), \
color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object \
(the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, \
stacked directly above its object (above the outermost clip group, clipping sublayer or live object that holds it: \
a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, \
mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or \
clipping pieces group, so the clip does not hide them and the live object does not take them in; in isolation mode, \
marks that would go outside the isolated art are an error). Selected parts of compound paths, envelopes, meshes, repeats, \
Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost \
such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. \
A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds \
such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; \
one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
has_selection,
mark_bounds
)]
@@ -81,13 +96,18 @@ fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
.collect()
}
/// Where the marks of object `id` go: directly above it, or above the outermost clip group or
/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer
/// with a clipping mask holds its marks too, since nothing lies outside it.
fn anchor(d: &Document, id: NodeId) -> NodeId {
/// Where the marks of object `id` go: directly above it, or above the outermost clip group,
/// clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group,
/// Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group,
/// graph series, graph design copy or clipping pieces group) that holds it at any
/// depth, which would otherwise clip them or take them in as one of its parts. A top-level layer
/// with a clipping mask holds its marks too, since nothing lies outside it. `held` keeps each
/// container's answer, so that siblings selected together look each container up once.
fn anchor(d: &Document, id: NodeId, held: &mut HashMap<NodeId, bool>) -> NodeId {
let (mut at, mut outermost) = (id, id);
while let Some(up) = d.parent_of(at) {
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
let holds = *held.entry(up).or_insert_with(|| d.node(up).is_some_and(|n| n.clips() || !plain(n)) && d.parent_of(up).is_some());
if holds {
outermost = up;
}
at = up;
@@ -95,6 +115,51 @@ fn anchor(d: &Document, id: NodeId) -> NodeId {
outermost
}
/// Whether `n` is a layer or a group with no live role, which keeps new art as an ordinary member.
fn plain(n: &Node) -> bool {
let e = n.extras();
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
&& !n.is_compound_shape()
&& e.shaper.is_none()
&& e.objects_on_path.is_none()
&& e.dimension.is_none()
&& e.graph.is_none()
&& e.flare.is_none()
&& e.trace.is_none()
&& e.generated.is_none()
&& e.series_index.is_none()
&& !e.graph_design_art
&& !e.clip_pieces
&& e.live_paint_gaps.is_none()
&& !vectorcraft_tools::builder::is_live_paint(n)
}
/// The outermost live object that draws a selected part with different geometry or placement.
fn measured_object(d: &Document, id: NodeId) -> NodeId {
let (mut at, mut measured) = (id, id);
while let Some(up) = d.parent_of(at) {
if let Some(n) = d.node(up) {
let redraws = match &n.kind {
NodeKind::Compound { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => true,
NodeKind::Blend { spec, .. } => {
(spec.spine.is_some() && !spec.no_spine) || spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath
}
_ => {
n.extras().shaper.is_some()
|| (n.extras().trace.is_some()
&& n.children()
.is_some_and(|children| children.first().is_some_and(|c| c.id == at) && n.editing_children().len() < children.len()))
}
};
if redraws {
measured = up;
}
}
at = up;
}
measured
}
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
@@ -106,18 +171,39 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
if roots.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
}
let d = &s.doc()?.doc;
let st = s.doc()?;
let (d, isolation) = (&st.doc, st.isolation);
let symbols = d.symbol_boxes();
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
let mut held: HashMap<NodeId, bool> = HashMap::new();
let mut measured = HashSet::new();
let mut too_small = false;
for id in roots {
if d.node(id).is_none_or(|n| n.is_guide()) {
continue;
}
let id = measured_object(d, id);
if !measured.insert(id) {
continue;
}
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
let placed = matches!(n.kind, NodeKind::Blend { .. }).then(|| {
let mut art = vectorcraft_render::effects::expand_live_deep(Some(d), n);
art.appearance = n.appearance.clone();
art
});
let n = placed.as_ref().unwrap_or(n);
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue };
// Corner legs are at most half a side, so an object too small for any leg gets no marks.
let (lx, ly) = legs(r, length);
if rectangle || lx > FLAT || ly > FLAT {
marked.push((anchor(d, id), r));
let at = anchor(d, id, &mut held);
// Marks placed outside the isolated art could not be selected or edited there.
if isolation.is_some_and(|iso| iso == at || !d.ancestry(at).is_some_and(|a| a.contains(&iso))) {
return Err(bad(C, "the marks would go outside the isolated art: exit isolation mode first"));
}
marked.push((at, r));
} else {
too_small = true;
}
@@ -288,6 +288,228 @@ fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() {
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}");
}
#[test]
fn marks_on_envelope_sources_follow_the_drawn_bounds_once_per_live_object() {
for nested in [false, true] {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 20.0, 0.0, 20.0, 20.0);
let top = rect(&mut s, 180.0, 120.0, 100.0, 60.0);
select(&mut s, &[a, b, top]);
let r = s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap();
let envelope = NodeId(r["id"].as_u64().unwrap());
let outermost = if nested {
let r = s.execute("object.repeat.grid", &json!({"ids": [envelope.0], "rows": 2, "cols": 2})).unwrap();
NodeId(r["id"].as_u64().unwrap())
} else {
envelope
};
let layer = parent(&s, outermost);
let before = node(&s, outermost);
let d = &s.doc().unwrap().doc;
let drawn = vectorcraft_render::drawn_bounds(d, d.node(outermost).unwrap()).unwrap();
assert!(drawn.x0 > marks_bounds(&s, b).x1, "the visible art is away from its sources");
for selected in [vec![a], vec![a, b], vec![a, envelope]] {
for style in ["corners", "rectangle"] {
for bounds in ["geometric", "visual"] {
select(&mut s, &selected);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap();
let marks = ids_of(&r);
assert_eq!(r["count"], 1, "one set of marks for the live object");
assert_eq!(marks.len(), 1);
assert_eq!(children(&s, layer), vec![outermost, marks[0]]);
assert_eq!(node(&s, outermost), before);
assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "{nested}, {style}, {bounds}");
assert_eq!(steps(&s), n + 1);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(children(&s, layer), vec![outermost]);
assert_eq!(node(&s, outermost), before);
}
}
}
}
}
#[test]
fn marks_on_a_blend_key_or_compound_shape_operand_go_above_the_live_object() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("object.blend.make", &json!({})).unwrap();
let blend = s.doc().unwrap().selection.objects[0];
let layer = parent(&s, blend);
select(&mut s, &[a]);
let r = s.execute(COMMAND, &json!({})).unwrap();
let mark = ids_of(&r)[0];
assert_eq!(children(&s, blend), vec![a, b], "the blend keeps its keys");
assert_eq!(children(&s, layer), vec![blend, mark]);
assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 20.0, 20.0)), "the key's own bounds");
s.execute("edit.undo", &json!({})).unwrap();
for stored_spine in [false, true] {
s.execute("object.blend.options", &json!({"id": blend.0, "orientation": if stored_spine { "page" } else { "path" }})).unwrap();
if stored_spine {
s.execute("object.blend.spine.reshapeSegment", &json!({"id": blend.0, "segment": 0, "t": 0.5, "dx": 0, "dy": 60})).unwrap();
}
let before = node(&s, blend);
let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") };
let drawn = vectorcraft_doc::live::blend_expand(keys, spec).iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b)).unwrap();
select(&mut s, &[a, b]);
let r = s.execute(COMMAND, &json!({"bounds": "visual"})).unwrap();
let marks = ids_of(&r);
assert_eq!(r["count"], 1, "repositioned keys are measured as one live object");
assert_eq!(marks.len(), 1);
assert_eq!(children(&s, layer), vec![blend, marks[0]]);
assert_eq!(node(&s, blend), before);
assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1)));
s.execute("edit.undo", &json!({})).unwrap();
}
let c = rect(&mut s, 100.0, 100.0, 30.0, 30.0);
let d = rect(&mut s, 110.0, 100.0, 30.0, 30.0);
select(&mut s, &[c, d]);
s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap();
let shape = s.doc().unwrap().selection.objects[0];
select(&mut s, &[d]);
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
let mark = ids_of(&r)[0];
assert_eq!(children(&s, shape), vec![c, d], "the compound shape keeps its operands");
assert!(near(marks_bounds(&s, mark), (110.0, 100.0, 140.0, 130.0)), "the operand's own bounds");
let stack = children(&s, parent(&s, shape));
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == shape).map(|i| i + 1), "{stack:?}");
s.execute("edit.undo", &json!({})).unwrap();
// With the compound shape isolated, the marks could only go outside the isolated art: refused.
s.execute("object.isolate", &json!({"id": shape.0})).unwrap();
select(&mut s, &[d]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
assert!(refused.contains("outside the isolated art"), "{refused}");
assert_eq!(steps(&s), n, "no undo step");
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn marks_on_an_outlined_glyph_stay_directly_above_it_inside_the_outlines_group() {
for isolated in [false, true] {
let mut s = session();
let text =
s.execute("text.create", &json!({"x": 20, "y": 60, "text": "AB", "size": 24, "font": "Source Sans 3", "style": "Regular"})).unwrap();
select(&mut s, &[NodeId(text["id"].as_u64().unwrap())]);
let outlines = ids_of(&s.execute("type.createOutlines", &json!({})).unwrap())[0];
let glyphs = children(&s, outlines);
if isolated {
s.execute("object.isolate", &json!({"id": outlines.0})).unwrap();
}
select(&mut s, &[glyphs[0]]);
let bounds = marks_bounds(&s, glyphs[0]);
let mark = ids_of(&s.execute(COMMAND, &json!({})).unwrap())[0];
assert_eq!(parent(&s, mark), outlines);
let mut expected = glyphs;
expected.insert(1, mark);
assert_eq!(children(&s, outlines), expected);
assert!(near(marks_bounds(&s, mark), (bounds.x0, bounds.y0, bounds.x1, bounds.y1)));
}
}
#[test]
fn marks_measure_blend_keys_and_steps_placed_on_a_diagonal_spine() {
let mut s = session();
let a = rect(&mut s, 20.0, 30.0, 40.0, 10.0);
let b = rect(&mut s, 120.0, 130.0, 20.0, 40.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 8})).unwrap();
s.execute("object.blend.make", &json!({"spacing": "steps", "steps": 3, "orientation": "path"})).unwrap();
let blend = s.doc().unwrap().selection.objects[0];
let before = node(&s, blend);
let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") };
let placed = vectorcraft_doc::live::blend_expand(keys, spec);
assert!(placed.len() > keys.len());
let geometry = placed.iter().map(|n| n.path_data().unwrap().bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap();
let visual = placed.iter().map(|n| n.visual_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap();
let stored = before.geometric_bounds().unwrap();
assert!(geometry.y0 < stored.y0 || geometry.y1 > stored.y1);
assert!(visual.x0 < geometry.x0 && visual.y0 < geometry.y0 && visual.x1 > geometry.x1 && visual.y1 > geometry.y1);
for selected in [vec![a], vec![a, b], vec![blend]] {
for style in ["corners", "rectangle"] {
for (bounds, expected) in [("geometric", geometry), ("visual", visual)] {
select(&mut s, &selected);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap();
let marks = ids_of(&r);
assert_eq!(r["count"], 1);
assert_eq!(marks.len(), 1);
let actual = marks_bounds(&s, marks[0]);
assert!(
near(actual, (expected.x0, expected.y0, expected.x1, expected.y1)),
"{selected:?}, {style}, {bounds}: {actual:?}, {expected:?}"
);
for shape in &placed {
let r = if bounds == "visual" { shape.visual_bounds().unwrap() } else { shape.path_data().unwrap().bounds().unwrap() };
assert!(actual.x0 <= r.x0 + 1e-6 && actual.y0 <= r.y0 + 1e-6 && actual.x1 >= r.x1 - 1e-6 && actual.y1 >= r.y1 - 1e-6);
}
assert_eq!(node(&s, blend), before);
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, blend), before);
}
}
}
}
#[test]
fn marks_on_a_dimension_part_go_above_the_live_object() {
let mut s = session();
let r = s.execute("dimension.create", &json!({"a": [0, 0], "b": [100, 0]})).unwrap();
let dimension = NodeId(r["id"].as_u64().unwrap());
let layer = parent(&s, dimension);
let parts = children(&s, dimension);
let before = node(&s, dimension);
select(&mut s, &[parts[0]]);
let r = s.execute(COMMAND, &json!({})).unwrap();
let mark = ids_of(&r)[0];
assert_eq!(children(&s, dimension), parts, "the dimension keeps its generated parts");
assert_eq!(node(&s, dimension), before);
assert_eq!(children(&s, layer), vec![dimension, mark]);
let before = node(&s, mark);
s.execute("dimension.update", &json!({"ids": [dimension.0], "offset": 40})).unwrap();
assert_eq!(children(&s, layer), vec![dimension, mark]);
assert_eq!(node(&s, mark), before, "updating the dimension preserves the mark");
}
#[test]
fn marks_on_an_image_trace_part_go_above_the_live_object() {
let mut s = session();
let art = rect(&mut s, 20.0, 30.0, 60.0, 40.0);
select(&mut s, &[art]);
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
let r = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap();
let trace = NodeId(r["id"].as_u64().unwrap());
let layer = parent(&s, trace);
let parts = children(&s, trace);
let before = node(&s, trace);
let part = before.children().unwrap().iter().find(|n| n.path_data().is_some()).unwrap().id;
select(&mut s, &[part]);
let r = s.execute(COMMAND, &json!({})).unwrap();
let mark = ids_of(&r)[0];
assert_eq!(children(&s, trace), parts, "the trace keeps its generated parts");
assert_eq!(node(&s, trace), before);
assert_eq!(children(&s, layer), vec![trace, mark]);
let before = node(&s, mark);
let r = s.execute("imageTrace.make", &json!({"id": trace.0, "params": {"ignoreWhite": true, "threshold": 100}})).unwrap();
let retraced = NodeId(r["id"].as_u64().unwrap());
assert_eq!(children(&s, layer), vec![retraced, mark]);
assert_eq!(node(&s, mark), before, "retracing preserves the mark");
}
#[test]
fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
let mut s = session();
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Fill Colors",
["Object", "Plug-ins", "Color Effects"],
None,
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
has_selection,
random_fill::run
),
@@ -6,7 +6,7 @@
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
@@ -16,7 +16,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint};
#[cfg(test)]
use super::super::super::graph::is_design_art;
use super::super::super::graph::{is_series_group, paint_targets};
use super::super::super::graph::{is_series_group, paint_targets, series_drawn_designs};
use super::super::super::menucmds::whole_or;
use super::super::super::paint::swatch_solid;
use super::super::super::{bad, checked_ids_or_selection, number_or, text_param};
@@ -210,6 +210,39 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
}
let series_groups = cached_series_groups(before, &targets);
let mut seen = std::collections::HashSet::new();
let compound_groups: HashSet<NodeId> = targets
.iter()
.filter_map(|id| {
let n = before.node(*id)?;
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
return None;
}
before.parent_of(*id).filter(|p| series_groups.contains(p))
})
.collect();
let mut drawn_designs = HashMap::new();
// The series groups whose compounds are marks: the series draws no compound design, so the graph made none of
// them from one. Only a design the series draws can have made a compound. Each series is checked once.
let compound_marks: HashSet<NodeId> = compound_groups
.iter()
.copied()
.filter(|group| {
let Some(index) = before.node(*group).and_then(|g| g.extras().series_index).and_then(|i| usize::try_from(i).ok()) else {
return false;
};
let graph = before.parent_of(*group).and_then(|p| before.node(p));
graph.is_some_and(|graph| {
let Some(spec) = graph.extras().graph.as_deref() else { return false };
let drawn = drawn_designs.entry(graph.id).or_insert_with(|| series_drawn_designs(spec));
let (marker, column) = drawn(index);
![column, marker].into_iter().flatten().any(|name| {
before.graph_designs.iter().any(|design| {
design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())
})
})
})
})
.collect();
// A compound directly in a series group is one of the series' marks unless the graph drew it from a design;
// the rest of the series' art below its top level is design art.
let series_compound = |id: NodeId| {
@@ -217,19 +250,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
return false;
}
let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false };
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref());
graph.is_some_and(|spec| {
let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str());
let marker = spec.series_markers.get(index).and_then(Option::as_deref);
![column, marker].into_iter().flatten().any(|name| {
before
.graph_designs
.iter()
.any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()))
})
})
before.parent_of(id).is_some_and(|p| compound_marks.contains(&p))
};
targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups)));
let count = keeping_series_paint(d, &roots, |d| {
@@ -398,6 +398,54 @@ fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() {
}
}
#[test]
fn a_user_compound_in_a_column_series_naming_an_undrawn_compound_marker_takes_a_color() {
let mut s = session();
let tile = rects(&mut s, 2);
select(&mut s, &tile);
let design = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[design]);
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Compound { .. }));
let graph = NodeId(
s.execute(
"graph.create",
&json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
// A column series keeps a marker design it was given as a line series, and does not draw it.
s.edit("Name a marker design on a column series", |d, _| {
let mut extras = d.node_mut(graph).unwrap().extras_mut();
let spec = extras.graph.as_deref_mut().unwrap();
spec.series_markers = vec![Some("Tile".into()), Some("Tile".into())];
Ok(())
})
.unwrap();
let d = &s.doc().unwrap().doc;
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
let group = series.id;
let marks: Vec<NodeId> = series
.children()
.into_iter()
.flatten()
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
.map(|m| m.id)
.collect();
assert!(marks.len() >= 2);
let marks = &marks[..2];
select(&mut s, marks);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group));
for ids in [vec![compound], vec![group], vec![graph]] {
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{ids:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() {
for kind in ["column", "line", "scatter"] {
+1 -1
View File
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Numbers Sequence…",
["Object", "Plug-ins", "Type Tools"],
None,
"{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}",
"{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error, unless replace skips it because its story holds no number or placeholder. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}",
has_selection,
numbers::make_numbers
),
+139 -25
View File
@@ -9,7 +9,7 @@ mod tests;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun};
use vectorcraft_geom::Rect;
use vectorcraft_render::effects;
use vectorcraft_text::edit;
@@ -273,6 +273,109 @@ pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec
spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect()
}
thread_local! {
/// [`text_passes`] of this thread.
static TEXT_PASSES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many times Make Numbers Sequence has gone over a type object's text or style runs on this
/// thread: once to build the text an object would read, and once for each part of the object it
/// changes, however many numbers the text holds.
#[cfg(test)]
pub(crate) fn text_passes() -> u64 {
TEXT_PASSES.get()
}
/// Adds one to [`text_passes`].
fn note_text_pass() {
TEXT_PASSES.set(TEXT_PASSES.get().saturating_add(1));
}
/// `text` with `changes` (from the last to the first, as [`edits`] gives them) made.
pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String {
note_text_pass();
let mut out = String::with_capacity(text.len());
let mut at = 0;
for (a, b, n) in changes.iter().rev() {
out.push_str(text.get(at..*a).unwrap_or_default());
out.push_str(n);
at = *b;
}
out.push_str(text.get(at..).unwrap_or_default());
out
}
/// Makes `changes` (from the last to the first, as [`edits`] gives them) in `t`, with the
/// paragraphs, style runs and ruby that replacing each range by itself with
/// [`edit::replace_range`] would give, in one pass over each.
pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) {
if changes.len() < 2 || !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()) || {
let text = t.plain_text();
changes.iter().any(|(a, b, n)| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n')))
} {
// One change (a whole text), one that adds or removes paragraphs, or text with ruby or
// inline art, whose spans each replacement moves or drops in turn.
for (a, b, n) in changes {
note_text_pass();
t.splice_paras(*a, *b, n);
edit::replace_range(&mut t.runs, *a, *b, n);
t.ruby_after_replace(*a, *b, n.len());
}
return;
}
// Changes inside paragraphs leave every paragraph's style where it is: one splice sets the
// paragraph list as each of them would.
if let Some((a, b, n)) = changes.first() {
t.splice_paras(*a, *b, n);
}
replace_runs(&mut t.runs, changes);
}
/// The runs with each range of `changes` replaced by its number in the style of the range's first
/// character, without a glyph choice, as [`edit::replace_range`] gives it.
fn replace_runs(runs: &mut Vec<TextRun>, changes: &[Edit]) {
note_text_pass();
let old = std::mem::take(runs);
let mut out: Vec<TextRun> = Vec::with_capacity(old.len());
let mut pending = changes.iter().rev().peekable();
// Where the run starts and where the last replaced range ends.
let (mut off, mut cut) = (0, 0);
for r in old {
let (start, end) = (off, off + r.text.len());
off = end;
// The run's style without a glyph choice, for pieces that start inside it and numbers.
let plain = CharStyle { glyph_alternate: None, ..r.style.clone() };
// A piece of the run from `a` to `b`: one that starts inside it has no glyph choice.
let piece = |out: &mut Vec<TextRun>, a: usize, b: usize| {
let style = if a == start { &r.style } else { &plain };
push(out, r.text.get(a - start..b - start).unwrap_or_default(), style);
};
let mut pos = start.max(cut).min(end);
while let Some((a, b, n)) = pending.next_if(|(a, _, _)| *a < end) {
if pos < *a {
piece(&mut out, pos, *a);
}
push(&mut out, n, &plain);
cut = *b;
pos = cut.min(end);
}
if pos < end {
piece(&mut out, pos, end);
}
}
edit::normalize(&mut out);
*runs = out;
}
/// Adds `text` in `style` to the end of `out`, onto the last run when it has the same style, so a
/// style is copied once for each change of style rather than once for each number.
fn push(out: &mut Vec<TextRun>, text: &str, style: &CharStyle) {
match out.last_mut() {
Some(last) if last.style == *style && last.inline.is_none() && style.glyph_alternate.is_none() => last.text.push_str(text),
_ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }),
}
}
pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let o = Options::parse(p)?;
@@ -292,24 +395,43 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
if texts.len() > MAX_TEXTS {
return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}")));
}
let threads = threads::ThreadIndex::of(d);
if texts.iter().any(|id| threads.threaded(*id)) {
return Err(bad(C, "threaded type can't be numbered: its frames share one story"));
}
let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.plain_text(),
_ => String::new(),
};
// Only objects that hold a number or the placeholder count, for the order too.
let mut texts: Vec<(NodeId, String)> = texts
.into_iter()
.map(|id| (id, plain(id)))
.filter(|(_, t)| match o.replace {
"numbers" => t.bytes().any(|b| b.is_ascii_digit()),
"placeholder" => !placeholder_spans(t).is_empty(),
_ => true,
})
.collect();
let threads = threads::ThreadIndex::of(d);
let threaded = || bad(C, "threaded type can't be numbered: its frames share one story");
if o.replace == "all" && texts.iter().any(|id| threads.threaded(*id)) {
return Err(threaded());
}
let holds = |t: &str| match o.replace {
"numbers" => t.bytes().any(|b| b.is_ascii_digit()),
"placeholder" => !placeholder_spans(t).is_empty(),
_ => true,
};
// Only objects that hold a number or the placeholder count, for the order too. Threaded type
// is skipped like other type when its whole story holds none, so a placeholder split across
// two frames is still refused.
let mut kept: Vec<(NodeId, String)> = Vec::with_capacity(texts.len());
let mut checked_threads = std::collections::HashSet::<usize>::new();
for id in texts {
if threads.threaded(id) {
if threads.first_thread_index(id).is_some_and(|index| !checked_threads.insert(index)) {
continue;
}
let frames = threads.story(id);
let story: String = frames.iter().copied().map(plain).collect();
if holds(&story) {
return Err(threaded());
}
continue;
}
let t = plain(id);
if holds(&t) {
kept.push((id, t));
}
}
let mut texts = kept;
if o.order != "stacking" && o.shuffle.is_none() {
let placed: Vec<(NodeId, Rect)> = texts
.iter()
@@ -345,11 +467,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
_ => vec![(0, text.len(), number.clone())],
};
// The text it would have, to leave out objects that already read so.
let mut after = text.clone();
for (a, b, n) in &changes {
after.replace_range(*a..*b, n);
}
if after != *text {
if replaced(text, &changes) != *text {
plans.push((*id, changes));
}
}
@@ -367,11 +485,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Make Numbers Sequence", |d, sel| {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
for (a, b, n) in changes {
t.splice_paras(*a, *b, n);
edit::replace_range(&mut t.runs, *a, *b, n);
t.ruby_after_replace(*a, *b, n.len());
}
apply(t, changes);
refresh_bounds(t);
}
d.remove_many(&removed)?;
@@ -2,9 +2,9 @@
//! orders, removed objects, one undo step, and bad params refused without a change.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun};
use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence};
use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes};
use crate::Session;
fn session() -> Session {
@@ -93,6 +93,51 @@ fn threaded_type_is_refused() {
assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n));
}
/// Replacing numbers or placeholders skips threaded type that holds none, as it skips other type.
#[test]
fn threaded_type_with_nothing_to_replace_is_skipped() {
let mut s = session();
let a =
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a b c", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let seat = text_at(&mut s, 40.0, 300.0, "Seat 0");
let scans = super::threads::thread_scans();
let builds = super::threads::story_builds();
let out = s.execute(C, &json!({"ids": [a, b, seat.0], "replace": "numbers", "start": 4})).unwrap();
assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index");
assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check");
assert_eq!(out["count"], json!(1));
assert_eq!((plain(&s, NodeId(a)), plain(&s, seat)), ("a b c".to_string(), "Seat 4".to_string()));
let n = steps(&s);
let scans = super::threads::thread_scans();
let builds = super::threads::story_builds();
assert!(s.execute(C, &json!({"ids": [a, b], "replace": "placeholder"})).is_ok(), "no placeholder in the story");
assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index");
assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check");
assert!(s.execute(C, &json!({"ids": [a, b]})).is_err(), "the whole text of threaded type is still refused");
assert_eq!(steps(&s), n);
}
/// A placeholder in a threaded story is refused even when no one frame holds all of it.
#[test]
fn threaded_type_whose_story_holds_a_placeholder_is_refused() {
let mut s = session();
let words = format!("{} {{%n}}", "word ".repeat(40));
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": words, "area": {"width": 60, "height": 30}})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
let first = plain(&s, NodeId(a));
let second = plain(&s, NodeId(b));
assert!(!first.contains("{%n}"), "the selected frame alone has no placeholder");
assert!((first + &second).contains("{%n}"), "the story contains the placeholder in thread order");
let n = steps(&s);
assert!(s.execute(C, &json!({"ids": [a], "replace": "placeholder"})).is_err());
assert_eq!(steps(&s), n);
}
#[test]
fn the_spans_find_numbers_and_placeholders() {
assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]);
@@ -335,3 +380,65 @@ fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() {
}
assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n));
}
#[test]
fn a_long_text_is_numbered_in_a_few_passes() {
let mut s = session();
let a = text_at(&mut s, 40.0, 100.0, &"9 ".repeat(2_000));
let before = text_passes();
s.execute(C, &json!({"ids": [a.0], "replace": "numbers", "start": 1})).unwrap();
let passes = text_passes() - before;
assert_eq!(plain(&s, a), "1 ".repeat(2_000));
assert!(passes <= 4, "2,000 numbers in one object took {passes} passes over its text");
}
/// `t` with `changes` made one at a time, as the command made them before it made them in one pass.
fn one_at_a_time(t: &TextObject, changes: &[(usize, usize, String)]) -> TextObject {
let mut t = t.clone();
for (a, b, n) in changes {
t.splice_paras(*a, *b, n);
vectorcraft_text::edit::replace_range(&mut t.runs, *a, *b, n);
t.ruby_after_replace(*a, *b, n.len());
}
t
}
#[test]
fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() {
let mut s = session();
let id = text_at(&mut s, 40.0, 100.0, "x");
let NodeKind::Text(base) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") };
let base = base.clone();
let style = |size: f64, glyph: Option<char>| {
let mut st = base.first_style();
st.size = size;
st.glyph_alternate = glyph.map(|ch| serde_json::from_value(json!({"ch": ch.to_string(), "gid": 7, "font": "F"})).unwrap());
st
};
let ruby = |start: usize, end: usize| serde_json::from_value(json!({"start": start, "end": end, "text": "r"})).unwrap();
// Runs that split numbers, start at them and end inside them, with glyph choices and ruby
// over, across and between the numbers.
type Case<'a> = (Vec<(&'a str, f64, Option<char>)>, Vec<(usize, usize)>);
let cases: Vec<Case> = vec![
(vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]),
(vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]),
(vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]),
(vec![("a", 10.0, Some('a')), ("a", 10.0, Some('a')), (" 12 34", 10.0, None)], vec![(3, 5), (6, 8)]),
];
for (runs, spans) in cases {
let mut t = base.clone();
t.runs = runs.iter().map(|(text, size, glyph)| TextRun { text: text.to_string(), style: style(*size, *glyph), inline: None }).collect();
let text = t.plain_text();
// Without ruby the runs are rebuilt in one pass; with it each change is made in turn.
for with_ruby in [false, true] {
t.ruby = if with_ruby { spans.iter().map(|(a, b)| ruby(*a, *b)).collect() } else { Vec::new() };
for number in ["0", "123456", "5", "123"] {
let changes = edits(&text, number_spans(&text), number);
let mut fast = t.clone();
apply(&mut fast, &changes);
let slow = one_at_a_time(&t, &changes);
assert_eq!((&fast.runs, &fast.ruby, &fast.paras), (&slow.runs, &slow.ruby, &slow.paras), "{text:?} numbered {number}");
}
}
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, Node
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{ImageRead, read_image};
pub use flavours::{ImageRead, read_image, read_pixels};
pub(crate) use resources::SwatchChoices;
pub use resources::{ArtResources, SymbolOptions, art_resources};
@@ -461,6 +461,20 @@ pub fn read_image(bytes: &[u8]) -> Result<ImageRead> {
Ok(ImageRead(img))
}
/// [`read_image`] for a bitmap another app put on the clipboard as decoded pixels, on any thread:
/// the pixels are encoded once as the PNG the document keeps, and kept as the decoded image the
/// renderers share, so neither this read nor the first frame that draws the image decodes them.
/// When the renderers' store refuses the pixels (over its budget, or no room beside the images
/// being drawn), they are dropped, and the renderers decode the PNG as they decode any other image,
/// under the same memory limits. An error when the image is empty or too large to draw.
pub fn read_pixels(img: image::RgbaImage) -> Result<ImageRead> {
let img = image::DynamicImage::ImageRgba8(img);
let read = fileio::pixels_png(&img).map_err(|e| bad("clipboard.importImage", e.to_string()))?;
// Refused pixels are not held anywhere else, so the store's budget stays the only one.
let _kept = vectorcraft_render::keep_decoded_image(&read.blob, img);
Ok(ImageRead(read))
}
impl Session {
/// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read
/// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`.
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
+2
View File
@@ -481,6 +481,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, id, &params)?;
super::params::check_effect_channel(C, id, &params)?;
super::params::check_effect_center(C, id, &params)?;
super::params::check_effect_halftone_style(C, id, &params)?;
super::params::check_effect_pathfinder(C, id, &params)?;
// Crop Marks take their style from the preferences when applied.
if id == effects::CROP_MARKS && params.get("style").is_none() {
@@ -826,6 +827,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, effect, &params)?;
super::params::check_effect_channel(C, effect, &params)?;
super::params::check_effect_center(C, effect, &params)?;
super::params::check_effect_halftone_style(C, effect, &params)?;
super::params::check_effect_pathfinder(C, effect, &params)?;
}
if edited.iter().any(|e| texture_load_effect(e)) {
+4 -1
View File
@@ -44,7 +44,7 @@ pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note};
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, pixels_png, preview_with_clip, size_note};
mod heifread;
pub mod hpgl;
mod jp2read;
@@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::is_raster_image;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
@@ -146,6 +147,8 @@ mod commands;
mod export_names;
mod formats;
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) use access::FILES_READ;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
#[cfg(all(test, not(target_arch = "wasm32")))]
+8
View File
@@ -283,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
#[cfg(all(test, not(target_arch = "wasm32")))]
thread_local! {
/// The paths [`read_file`] has read on this thread, in order.
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
may_read(path)?;
#[cfg(test)]
FILES_READ.with(|r| r.borrow_mut().push(path.to_string()));
// A device or pipe may never end: only a regular file is read to its end.
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
return Err(EngineError::Other(format!("{path}: not a file")));
+26
View File
@@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
}
/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of
/// it can be decoded.
pub(crate) fn is_raster_image(bytes: &[u8]) -> bool {
super::pcraftread::is_pcraft(bytes)
|| psdread::is_psd(bytes)
|| jxlread::is_jxl(bytes)
|| super::jp2read::is_jpeg2000(bytes)
|| super::heifread::is_heif(bytes)
|| super::pxrread::is_pxr(bytes)
|| craft_image_codecs::detect(bytes).is_some()
|| super::tgaread::is_targa(bytes)
|| super::pcxread::is_pcx(bytes)
}
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
@@ -1338,6 +1352,18 @@ pub(super) fn as_png(img: impl Into<image::DynamicImage>, icc: Option<Vec<u8>>,
stored(png, "image/png", size, ppi)
}
/// Decoded pixels `img` stored as a PNG, without a resolution or an ICC profile. An image whose
/// pixels as RGBA need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw.
pub(crate) fn pixels_png(img: &image::DynamicImage) -> Result<RasterImage> {
let (w, h) = (img.width(), img.height());
if 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 mut png = Vec::new();
img.write_with_encoder(image::codecs::png::PngEncoder::new(&mut png)).map_err(err)?;
stored(png, "image/png", (w, h), None)
}
/// Effect › Distort › Glass › Load Texture…: encoded image `bytes`, in any format [`raster_image`]
/// reads, as the `textureImage` Glass stores ([`LoadedTexture::to_stored`]). The pixels are decoded
/// within [`MAX_RASTER_ALLOC`], counted as RGBA, as the renderer decodes them (#1717); a CMYK image
+6 -1
View File
@@ -47,7 +47,12 @@ pub const OPTIONS: &[FormatOption] = &[
default: "\"layerNames\"",
description: "layerNames (readable ids from names) | minimal (only referenced ids) | unique (content-hashed prefix on every id and class)",
},
FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" },
FormatOption {
name: "decimals",
ty: "integer",
default: "3",
description: "coordinate precision, 1–7 decimal places; positive root width/height and viewBox size stay positive",
},
FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" },
FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" },
FormatOption {
+1 -1
View File
@@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs, series_drawn_designs};
pub use edit::{GraphTypeSubject, graph_type_subject};
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
pub use generate::calculated_axes;
+20 -6
View File
@@ -88,22 +88,36 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
/// bars.
fn draws_with(g: &GraphSpec, name: &str) -> bool {
let count = g.series_markers.len().max(g.series_columns.len());
let drawn = series_drawn_designs(g);
(0..count).any(|s| {
let (marker, column) = drawn(s);
marker == Some(name) || column == Some(name)
})
}
/// For each series `s` of graph `g`, the designs it draws with, as [`draws_with`] counts them: its
/// marker design and its column design, each only when the series draws it.
pub(crate) fn series_drawn_designs<'a>(g: &'a GraphSpec) -> impl Fn(usize) -> (Option<&'a str>, Option<&'a str>) + 'a {
let scatter = g.kind == GraphKind::Scatter;
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
let in_legend = |s: usize| {
let in_legend = move |s: usize| {
let entries = if scatter { nser.div_ceil(2) } else { nser };
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
};
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
let plotted = if scatter { nser.div_ceil(2) } else { nser };
let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s));
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
let shown = move |s: usize| s < plotted && (g.mark_points || in_legend(s));
let marked = move |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
let columnar = move |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
move |s: usize| {
let marker = g.series_markers.get(s).and_then(Option::as_deref).filter(|_| marked(s));
let column = g.series_columns.get(s).and_then(Option::as_ref).map(|c| c.design.as_str()).filter(|_| columnar(s));
(marker, column)
}
}
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
+11 -4
View File
@@ -8,7 +8,7 @@
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::Node;
use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes};
use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes, style};
use super::edit::selected_roots;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param};
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Vector Halftone…",
["Object"],
None,
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style?: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; sets shape and angle unless they are given: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
has_selection,
halftone
)]
@@ -27,17 +27,24 @@ pub fn specs() -> Vec<CommandSpec> {
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.vectorHalftone";
let styled = match p.get("style") {
Some(v) => {
let v = v.as_str().ok_or_else(|| bad(C, "style must be a string"))?;
style(v).ok_or_else(|| bad(C, format!("unknown style `{v}` (custom|grid|gridAngle|gridDots|gridDotsAngle)")))?
}
None => None,
};
let shape = match text_param(p, "shape", C)? {
Some(v) => {
DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))?
}
None => DotShape::Circle,
None => styled.map_or(DotShape::Circle, |s| s.0),
};
let frequency = number_or(p, "frequency", 20.0, C)?;
if !(1.0..=300.0).contains(&frequency) {
return Err(bad(C, "frequency must be between 1 and 300 lines per inch"));
}
let angle = number_or(p, "angle", 45.0, C)?;
let angle = number_or(p, "angle", styled.map_or(45.0, |s| s.1), C)?;
if !angle.is_finite() {
return Err(bad(C, "invalid angle"));
}
+11 -1
View File
@@ -2392,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
}
// Read before it is copied: a file that can't be shown isn't copied.
let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) };
let img = if images.is_empty() {
None
} else {
Some(linked_image(&bytes, Some(&path)).map_err(|e| {
// A file in no image format; a damaged image keeps its own error.
if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) {
s.image_only.set(Some(false));
}
bad(C, format!("{path}: {e}"))
})?)
};
// A copy beside the document would point at plate files it can't find there.
if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) {
return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are")));
+28 -4
View File
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit};
use vectorcraft_geom::{Point, Rect};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -860,10 +860,34 @@ pub fn find(s: &Session, name: &str) -> Option<DocSettings> {
/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names
/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without
/// `preset`.
/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no
/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads
/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no
/// preset.
fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) };
let found = match str_param(p, "presetCategory") {
if s.replaying() {
let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) };
let found = match str_param(p, "presetCategory") {
Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))),
None => find(s, name),
};
return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)")));
}
let name = text_param(p, "preset", cmd)?;
let wanted = text_param(p, "presetCategory", cmd)?
.map(|c| {
category_names()
.find(|n| n.eq_ignore_ascii_case(c))
.ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::<Vec<_>>().join(", "))))
})
.transpose()?;
let Some(name) = name else {
return match wanted {
Some(_) => Err(bad(cmd, "presetCategory needs a preset")),
None => Ok(s.default_settings()),
};
};
let found = match wanted {
Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))),
None => find(s, name),
};
+6 -2
View File
@@ -106,8 +106,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
}
/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a
/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The
/// selection stays as it is.
/// group (default: the current layer), on top of its contents or at `index` (0 = bottom; refused
/// in an Image Trace object, whose source image stays at the bottom). The selection stays as it is.
pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.newGroup";
// Only an omitted key takes its default; `null` is refused like any other bad value.
@@ -132,6 +132,10 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
if !d.is_editable(parent) {
return Err(bad(C, "the layer or group is hidden or locked"));
}
// An Image Trace object keeps its source image first; a group below it would end the tracing.
if index == 0 && crate::cmd::is_trace_group(n) {
return Err(bad(C, "index 0 of an Image Trace object is its source image; use index 1 or more"));
}
let label = if compound { "Compound Path" } else { "Group" };
let gid = s.edit(label, |d, _| {
let gid = d.alloc_id();
+1 -1
View File
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Group",
[],
None,
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
has_doc,
new_group
),
+13
View File
@@ -525,9 +525,22 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
check_effect_color(id, effect, params)?;
check_effect_channel(id, effect, params)?;
check_effect_center(id, effect, params)?;
check_effect_halftone_style(id, effect, params)?;
check_effect_pathfinder(id, effect, params)
}
/// The `style` in `params` of Vector Halftone (`effect`), as command `id` was given it: a parameter
/// error unless it names Custom or one of the named styles, in any letter case. `effect.apply` and
/// `effect.setParams` run this themselves before they edit, as they run [`check_effect_channel`].
pub(crate) fn check_effect_halftone_style(id: &str, effect: &str, params: &Value) -> Result<()> {
use vectorcraft_render::effects::addons::halftone::{HALFTONE, style};
let Some(v) = params.get("style") else { return Ok(()) };
if effect != HALFTONE || v.as_str().and_then(style).is_some() {
return Ok(());
}
Err(bad(id, "`style` must be one of custom, grid, gridAngle, gridDots, gridDotsAngle"))
}
/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
+9
View File
@@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
Some(read) => read,
None => prepare(s, p)?.read()?,
};
let image = match read.loaded.art {
Art::Image(..) => read.loaded.link.is_some(),
Art::Dcs(_) => true,
_ => false,
};
if s.image_only.get().is_some() && !image {
s.image_only.set(Some(false));
return Err(bad(PLACE, "the file is not an image"));
}
apply(s, read)
}
+88 -5
View File
@@ -15,6 +15,16 @@ const MAX_CELLS: usize = 10_000;
/// The most objects the copies may hold in all, counting every object inside each copy.
const MAX_COPIED_OBJECTS: usize = 250_000;
const EPS: f64 = 1e-9;
/// How far past a whole point a place may be and still count as on it, in points.
const GRID_EPS: f64 = 1e-6;
/// Whether `n` or an object in it, the art of linked opacity masks included, is pixel-aligned: the
/// objects that the snap after a transform moves.
fn holds_pixel_aligned(n: &Node) -> bool {
n.extras().pixel_aligned
|| n.children().is_some_and(|cs| cs.iter().any(|c| holds_pixel_aligned(c)))
|| n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_pixel_aligned(&m.art))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -22,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); when the selection holds a pixel-aligned object, every cell moves by whole points (the pitch is rounded up, with fill the first cell's place is rounded toward the sheet's inside and only cells that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own, with extra pitch only between alternating columns or rows and fill reserving the turn offset on both axes only where turned cells fit), so the copies stay on the pixel grid and the objects in each copy keep their places against each other; otherwise gaps are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; a single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
@@ -166,8 +176,75 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
} else {
None
};
// With a pixel-aligned object in the selection, every cell moves by whole points, so the snap
// leaves each copy as it moved it and the objects in a copy keep their places against each other.
// The pitch and the first cell's place are rounded up, so neighbors never come closer than asked
// and the first cell stays inside the sheet.
let aligned = roots.iter().filter_map(|r| d.node(*r)).any(holds_pixel_aligned);
let whole = |v: f64| if aligned { (v - GRID_EPS).ceil() } else { v };
// A half turn about the center maps x to 2 × center − x. On the pixel grid, twice the center is
// rounded up to whole points, so a turned copy also moves its objects by whole points; it then
// sits up to a point right of and below its cell, and the pitch and the fill make room for that.
let c2 = b.center().to_vec2() * 2.0;
let turn = if aligned && alt != Alternate::None {
let mut rounded = Vec2::new(whole(c2.x), whole(c2.y));
if rounded.x < c2.x - EPS {
rounded.x += 1.0;
}
if rounded.y < c2.y - EPS {
rounded.y += 1.0;
}
rounded - c2
} else {
Vec2::ZERO
};
let center = (c2 + turn) / 2.0;
let clearance = match alt {
Alternate::Columns => Vec2::new(turn.x, 0.0),
Alternate::Rows => Vec2::new(0.0, turn.y),
Alternate::None => Vec2::ZERO,
};
let (gx, gy) = if aligned {
let pitch = |v: f64| {
let rounded = whole(v).max(1.0);
if rounded < v - EPS { rounded + 1.0 } else { rounded }
};
(pitch(w + gx + clearance.x) - w, pitch(h + gy + clearance.y) - h)
} else {
(gx, gy)
};
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| {
let raw = Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0);
let mut origin = Vec2::new(whole(raw.x), whole(raw.y));
if b.x0 + origin.x < sh.x0 + m - EPS {
origin.x += 1.0;
}
if b.y0 + origin.y < sh.y0 + m - EPS {
origin.y += 1.0;
}
origin
});
let (rows, cols) = match anchor {
Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy),
Some((sh, m)) => {
let lead = origin - Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0);
let (sw, sh) = (sh.width() - lead.x - 2.0 * m, sh.height() - lead.y - 2.0 * m);
let (rows, cols) = fill_counts(sw, sh, 0.0, w, h, gx, gy);
// Turned cells have odd indices; an unturned cell may follow the last one that fits.
let alternating_count = |room, size, gap, shift, count: usize| count.min((fit_count(room - shift, size, gap) / 2 * 2).saturating_add(1));
match alt {
Alternate::Columns => {
let cols = alternating_count(sw, w, gx, turn.x, cols);
let turned_rows = fit_count(sh - turn.y, h, gy);
if cols > 1 && turned_rows > 0 { (rows.min(turned_rows), cols) } else { (rows, cols.min(1)) }
}
Alternate::Rows => {
let rows = alternating_count(sh, h, gy, turn.y, rows);
let turned_cols = fit_count(sw - turn.x, w, gx);
if rows > 1 && turned_cols > 0 { (rows, cols.min(turned_cols)) } else { (rows.min(1), cols) }
}
Alternate::None => (rows, cols),
}
}
None => (rows, cols),
};
if rows == 0 || cols == 0 {
@@ -182,14 +259,20 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS {
return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects")));
}
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
if rows == 1 && cols == 1 && origin == Vec2::ZERO && roots.len() == 1 {
let selection = &s.doc()?.selection;
let mut next_selection = selection.clone();
next_selection.set([roots[0]]);
if next_selection == *selection {
return Ok(json!({ "ids": [roots[0].0], "rows": 1, "columns": 1, "count": 1 }));
}
}
let cells = layout(w, h, gx, gy, rows, cols, alt);
let center = b.center().to_vec2();
let place = |c: &Cell| -> Affine {
let t = Affine::translate(origin + Vec2::new(c.dx, c.dy));
if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t }
};
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
let ids = s.edit("Step and Repeat", |d, sel| {
if roots.len() > 1 {
roots = vec![group_nodes(d, &roots)?];
@@ -60,6 +60,158 @@ fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() {
assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none()));
}
#[test]
fn a_single_unchanged_cell_keeps_undo_and_redo() {
for fill in [false, true] {
let (mut s, id) = setup();
let copies = s.execute(CMD, &json!({"columns": 2})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let steps = undo_steps(&s);
let redo = s.doc().unwrap().history.redo.len();
assert!(redo > 0);
let r = s.execute(CMD, &json!({"fill": fill, "sheet": {"x": 0, "y": 0, "width": 50, "height": 30}})).unwrap();
assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1}));
assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0));
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.doc().unwrap().history.redo.len(), redo);
s.execute("edit.redo", &json!({})).unwrap();
let copy = copies["ids"][1].as_u64().unwrap();
assert_eq!(bounds(&s, copy), (50.0, 0.0, 100.0, 30.0));
}
}
#[test]
fn a_single_unchanged_cell_clears_the_layer_target_in_one_undo_step() {
for fill in [false, true] {
let (mut s, id) = setup();
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
let before = s.doc().unwrap().selection.clone();
assert_eq!(before.objects, [NodeId(id)]);
assert_eq!(before.target, Some(layer));
let steps = undo_steps(&s);
let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30});
let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap();
assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1}));
let mut expected = before.clone();
expected.set([NodeId(id)]);
assert_eq!(s.doc().unwrap().selection, expected);
assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0));
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection, before);
assert_eq!(undo_steps(&s), steps);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection, expected);
assert_eq!(undo_steps(&s), steps + 1);
}
}
#[test]
fn a_single_unchanged_cell_records_the_resolved_patterns_setting() {
for fill in [false, true] {
for patterns in [false, true] {
let (mut s, id) = setup();
s.execute("object.pattern.make", &json!({"name": "Dots", "width": 50, "height": 30})).unwrap();
s.execute("object.pattern.done", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "swatch": "Dots"})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.prefs.transform_pattern_tiles = patterns;
let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30});
for explicit in [false, true] {
let mut params = json!({"fill": fill, "sheet": sheet});
let expected = if explicit { !patterns } else { patterns };
if explicit {
params["patterns"] = json!(expected);
}
let start = s.journal.len();
let steps = undo_steps(&s);
let r = s.execute(CMD, &params).unwrap();
assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1}));
params["patterns"] = json!(expected);
assert_eq!(s.journal_for_action(start), [(CMD.to_string(), params)]);
assert_eq!(undo_steps(&s), steps);
}
}
}
}
#[test]
fn a_single_unchanged_cell_selects_the_compound_in_one_undo_step() {
for fill in [false, true] {
let (mut s, member) = setup();
let inner_params = json!({"x": 10, "y": 5, "width": 20, "height": 10});
let inner = s.execute("shape.rectangle", &inner_params).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [member, inner]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let before = bounds(&s, compound);
s.execute(CMD, &json!({"columns": 2})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.select(|_, sel| sel.set([NodeId(member)])).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]);
let steps = undo_steps(&s);
let redo = s.doc().unwrap().history.redo.len();
assert!(redo > 0);
let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30});
let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap();
assert_eq!(r, json!({"ids": [compound], "rows": 1, "columns": 1, "count": 1}));
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]);
assert_eq!(bounds(&s, compound), before);
assert_eq!(undo_steps(&s), steps + 1);
assert!(s.doc().unwrap().history.redo.is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]);
assert_eq!(bounds(&s, compound), before);
assert_eq!(undo_steps(&s), steps);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]);
assert_eq!(bounds(&s, compound), before);
assert_eq!(undo_steps(&s), steps + 1);
}
}
#[test]
fn a_single_unchanged_cell_selects_the_whole_path_in_one_undo_step() {
for fill in [false, true] {
let (mut s, id) = setup();
let id = NodeId(id);
s.select(|_, sel| {
sel.set([id]);
sel.anchors.insert(id, [(0, 0), (0, 1)].into_iter().collect());
})
.unwrap();
let before = s.doc().unwrap().selection.clone();
let steps = undo_steps(&s);
let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30});
let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap();
assert_eq!(r, json!({"ids": [id.0], "rows": 1, "columns": 1, "count": 1}));
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert!(s.doc().unwrap().selection.anchors.is_empty());
assert!(s.doc().unwrap().selection.segments.is_empty());
assert_eq!(bounds(&s, id.0), (0.0, 0.0, 50.0, 30.0));
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection, before);
assert_eq!(undo_steps(&s), steps);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert!(s.doc().unwrap().selection.anchors.is_empty());
assert_eq!(undo_steps(&s), steps + 1);
}
}
#[test]
fn a_single_moved_cell_records_an_undo_step() {
let (mut s, id) = setup();
let steps = undo_steps(&s);
let r = s.execute(CMD, &json!({"fill": true, "sheet": {"x": 5, "y": 5, "width": 50, "height": 30}})).unwrap();
assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1}));
assert_eq!(bounds(&s, id), (5.0, 5.0, 55.0, 35.0));
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0));
}
#[test]
fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() {
let (mut s, _) = setup();
@@ -211,6 +363,285 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_
assert!((pitch - pitch.round()).abs() < 1e-9);
}
#[test]
fn pixel_aligned_pitch_preserves_requested_gaps_near_whole_points() {
for gap in [0.0, 0.25, -0.25] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let params = json!({"x": 0, "y": 0, "width": 50.0000005 - gap, "height": 30.0000005 - gap});
let cut = s.execute("shape.rectangle", &params).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gap": gap, "cutId": cut})).unwrap();
assert_eq!(r["count"], json!(4));
let d = &s.doc().unwrap().doc;
let cut_bounds = |id: &Value| {
let group = d.node(NodeId(id.as_u64().unwrap())).unwrap();
group.children().unwrap()[0].geometric_bounds().unwrap()
};
let ids = r["ids"].as_array().unwrap();
for row in 0..2 {
let left = cut_bounds(&ids[row * 2]);
let right = cut_bounds(&ids[row * 2 + 1]);
assert!(right.x0 - left.x1 >= gap - EPS, "the horizontal gap shrank: {left:?} {right:?}");
let pitch = right.x0 - left.x0;
assert!((pitch - pitch.round()).abs() < EPS);
}
for col in 0..2 {
let top = cut_bounds(&ids[col]);
let bottom = cut_bounds(&ids[col + 2]);
assert!(bottom.y0 - top.y1 >= gap - EPS, "the vertical gap shrank: {top:?} {bottom:?}");
let pitch = bottom.y0 - top.y0;
assert!((pitch - pitch.round()).abs() < EPS);
}
}
}
#[test]
fn a_pixel_aligned_cut_keeps_its_place_against_its_artwork_in_every_copy() {
let (mut s, cut) = setup();
s.execute("object.setPixelAligned", &json!({"ids": [cut], "on": true})).unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 48, "height": 28})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gapX": 0.6, "gapY": 1.3, "cutId": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let inset = |id: &Value| {
let mut rects = vec![];
d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| {
if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) {
rects.push(c.geometric_bounds().unwrap());
}
});
(rects[1].x0 - rects[0].x0, rects[1].y0 - rects[0].y0)
};
let ids = r["ids"].as_array().unwrap();
let first = inset(&ids[0]);
for id in &ids[1..] {
let (x, y) = inset(id);
assert!((x - first.0).abs() < 1e-9 && (y - first.1).abs() < 1e-9, "the artwork moved against the cut: {:?} against {first:?}", (x, y));
}
}
#[test]
fn pixel_aligned_art_stays_registered_in_turned_cells_and_gaps_never_shrink() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30})).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let r = s.execute(CMD, &json!({"columns": 3, "gapX": 0.1, "rotate": "columns", "cutId": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let rects = |id: &Value| {
let mut rects = vec![];
d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| {
if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) {
rects.push(c.geometric_bounds().unwrap());
}
});
(rects[0], rects[1])
};
let ids = r["ids"].as_array().unwrap();
let (c0, a0) = rects(&ids[0]);
let (c1, a1) = rects(&ids[1]);
let (c2, a2) = rects(&ids[2]);
// The turned cell mirrors the art inside its cut; the next unturned cell repeats it.
assert!(((c1.x1 - a1.x1) - (a0.x0 - c0.x0)).abs() < 1e-9, "turned art moved against its cut: {c1:?} {a1:?}");
assert!(((a2.x0 - c2.x0) - (a0.x0 - c0.x0)).abs() < 1e-9);
assert!(c2.x0 - c0.x0 > 2.0 * (50.25 + 0.1) - 1e-9, "the pitch was rounded down: {c2:?}");
assert!(c1.x0 - c0.x1 >= 0.1 - 1e-9 && c2.x0 - c1.x1 >= 0.1 - 1e-9, "a gap next to the turned cell shrank: {c0:?} {c1:?} {c2:?}");
}
#[test]
fn turned_pixel_aligned_cells_stay_on_the_sheet() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let sheet = json!({"x": 0, "y": 0, "width": 101, "height": 30.75});
let steps = undo_steps(&s);
let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!(r["columns"], json!(1));
assert_eq!(r["count"], json!(1));
assert_eq!(undo_steps(&s), steps + 1);
let group = NodeId(r["ids"][0].as_u64().unwrap());
assert!(matches!(s.doc().unwrap().doc.node(group).unwrap().kind, vectorcraft_doc::NodeKind::Group { .. }));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let sheet = json!({"x": 0, "y": 0, "width": 102, "height": 31.75});
let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!(r["columns"], json!(2));
let d = &s.doc().unwrap().doc;
for id in r["ids"].as_array().unwrap() {
let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap();
assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= 102.0 + 1e-9 && b.y1 <= 31.75 + 1e-9, "a cell runs past the sheet: {b:?}");
}
}
#[test]
fn fill_keeps_rounded_turn_offsets_inside_the_sheet_near_whole_points() {
for (height, columns) in [(30.0000005, 1), (31.0000005, 2)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.0000005})).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let sheet = json!({"x": 0, "y": 0, "width": 100, "height": height});
let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(columns), json!(columns)));
for id in r["ids"].as_array().unwrap() {
let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap());
assert!(x0 >= -1e-9 && y0 >= -1e-9 && x1 <= 100.0 + 1e-9 && y1 <= height + 1e-9, "a cell runs past the sheet");
}
}
}
#[test]
fn fill_accepts_exact_fit_when_the_doubled_turn_center_has_roundoff() {
for (rotate, x, y, width, height, sw, sh, rows, columns) in
[("columns", 0.0, 0.1, 50.0, 29.8, 100.0, 29.8, 1, 2), ("rows", 0.1, 0.0, 29.8, 50.0, 29.8, 100.0, 2, 1)]
{
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let params = json!({"x": x, "y": y, "width": width, "height": height});
let cut = s.execute("shape.rectangle", &params).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let b = s.doc().unwrap().doc.node(NodeId(cut)).unwrap().geometric_bounds().unwrap();
let c2 = if rotate == "columns" { b.center().y * 2.0 } else { b.center().x * 2.0 };
assert!(c2 > c2.round() && c2 - c2.round() < EPS);
let sheet = json!({"x": x, "y": y, "width": sw, "height": sh});
let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(rows), json!(columns), json!(2)));
for id in r["ids"].as_array().unwrap() {
let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap());
assert!(x0 >= x - EPS && y0 >= y - EPS && x1 <= x + sw + EPS && y1 <= y + sh + EPS, "a cell runs past the sheet");
}
}
}
#[test]
fn fill_reserves_turn_clearance_only_for_turned_cells() {
for (rotate, width, height, rows, columns) in [
("columns", 101.25, 31.0, 1, 1),
("columns", 102.0, 31.0, 1, 2),
("columns", 152.25, 31.0, 1, 3),
("columns", 152.25, 30.75, 1, 1),
("rows", 51.0, 61.75, 1, 1),
("rows", 51.0, 62.0, 2, 1),
("rows", 51.0, 92.75, 3, 1),
("rows", 50.25, 92.75, 1, 1),
] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30.75})).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let sheet = json!({"x": 0, "y": 0, "width": width, "height": height});
let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(rows), json!(columns)), "{rotate} on {width} by {height}");
let d = &s.doc().unwrap().doc;
for id in r["ids"].as_array().unwrap() {
let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap();
assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= width + 1e-9 && b.y1 <= height + 1e-9, "a cell runs past the sheet: {b:?}");
}
}
}
#[test]
fn turned_columns_keep_the_vertical_pitch_without_turn_clearance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gapY": 0.2, "rotate": "columns", "cutId": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let cut_bounds = |id: &Value| {
let mut rects = vec![];
d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| {
if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) {
rects.push(c.geometric_bounds().unwrap());
}
});
rects[0]
};
let ids = r["ids"].as_array().unwrap();
for col in 0..2 {
let first = cut_bounds(&ids[col]);
let second = cut_bounds(&ids[col + 2]);
assert!((second.y0 - first.y0 - 31.0).abs() < 1e-9, "the vertical pitch includes turn clearance: {first:?} {second:?}");
assert!(second.y0 - first.y1 >= 0.2 - 1e-9, "the vertical gap shrank: {first:?} {second:?}");
}
}
#[test]
fn fill_counts_only_the_pixel_aligned_copies_that_stay_on_the_sheet() {
let (mut s, id) = setup();
// The 1 pt stroke puts the snapped rectangle at (0.5, 0.5), 50 by 30.
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
assert_eq!(bounds(&s, id), (0.5, 0.5, 50.5, 30.5));
let steps = undo_steps(&s);
let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 100.6, "height": 30}})).unwrap();
assert_eq!(r["columns"], json!(1));
assert_eq!(undo_steps(&s), steps);
let (mut s, id) = setup();
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 101, "height": 30}})).unwrap();
assert_eq!(r["columns"], json!(2));
let d = &s.doc().unwrap().doc;
for id in r["ids"].as_array().unwrap() {
let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap();
assert!(b.x1 <= 101.5 + 1e-9, "a copy runs past the sheet: {b:?}");
}
}
#[test]
fn fill_rounds_pixel_aligned_origins_inside_the_sheet_near_whole_points() {
for (dx, dy) in [(0.0000005, 0.0), (0.0, 0.0000005), (-0.9999995, -0.9999995)] {
let (mut s, id) = setup();
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
let (x, y, _, _) = bounds(&s, id);
let (sx, sy) = (x + dx, y + dy);
let steps = undo_steps(&s);
let tight = json!({"x": sx, "y": sy, "width": 50, "height": 30});
assert!(s.execute(CMD, &json!({"fill": true, "sheet": tight})).is_err());
assert_eq!(undo_steps(&s), steps);
let sheet = json!({"x": sx, "y": sy, "width": 51, "height": 31});
let r = s.execute(CMD, &json!({"fill": true, "sheet": sheet})).unwrap();
assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1}));
let (x0, y0, x1, y1) = bounds(&s, id);
assert!(x0 >= sx && y0 >= sy && x1 <= sx + 51.0 && y1 <= sy + 31.0);
}
}
#[test]
fn fill_accepts_exact_fit_when_the_origin_subtraction_has_roundoff() {
for (x, y, sx, sy) in [(1.2, 0.0, 2.2, 0.0), (0.0, 1.2, 0.0, 2.2), (1.2, 1.2, 2.2, 2.2)] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let cut_params = json!({"x": x, "y": y, "width": 50, "height": 30});
let cut = s.execute("shape.rectangle", &cut_params).unwrap()["id"].as_u64().unwrap();
let art_params = json!({"x": 10, "y": 5, "width": 20, "height": 20});
let art = s.execute("shape.rectangle", &art_params).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap();
s.execute("select.set", &json!({"ids": [cut, art]})).unwrap();
let sheet = json!({"x": sx, "y": sy, "width": 50, "height": 30});
let r = s.execute(CMD, &json!({"fill": true, "cutId": cut, "sheet": sheet})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(1), json!(1)));
let (x0, y0, x1, y1) = bounds(&s, cut);
assert!((x0 - sx).abs() < EPS && (y0 - sy).abs() < EPS);
assert!((x1 - (sx + 50.0)).abs() < EPS && (y1 - (sy + 30.0)).abs() < EPS);
}
}
#[test]
fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() {
let first_x = |sheet: Option<Value>| {
+11
View File
@@ -509,6 +509,17 @@ impl<'a> ThreadIndex<'a> {
pub(crate) fn threaded(&self, id: NodeId) -> bool {
self.first.get(&id).and_then(|i| self.live.get(*i)).is_some_and(|n| *n >= 2) && text_of(self.doc, id).is_some()
}
/// The index in the document's threads of the first thread that lists `id`.
pub(crate) fn first_thread_index(&self, id: NodeId) -> Option<usize> {
self.first.get(&id).copied()
}
/// [`story_of`] for `id`, its thread found through the index.
pub(crate) fn story(&self, id: NodeId) -> Vec<NodeId> {
let Some(thread) = self.first.get(&id).and_then(|i| self.doc.text_threads.get(*i)) else { return vec![] };
story_in(self.doc, thread, id)
}
}
/// `ids` followed by the other frames of the threads they are in, each once, in thread order.
+27
View File
@@ -1606,4 +1606,31 @@ mod tests {
assert_eq!(roots.check(&s(base.join("out/x.svg")), Access::Write), Ok(()));
let _ = std::fs::remove_dir_all(base);
}
/// A checked write to a real path passes a script gate only inside the gate's write folder, and
/// only when every gate chained to it passes the path too.
#[cfg(unix)]
#[test]
fn a_checked_write_to_a_real_path_passes_every_chained_gate() {
let (base, _) = folders("check-real");
let base = std::fs::canonicalize(&base).unwrap();
let gate = |dir: &str| ScriptGate {
read: ScriptScope::default(),
write: ScriptScope::of_folder(&base.join(dir)),
documents: vec![],
held: vec![],
linked: LinkedFiles::default(),
also: None,
};
let (inside, outside) = (base.join("out/new.svg"), base.join("outside/new.svg"));
let denied = |p: &Path| Err(format!("Script file access denied: {}", p.display()));
assert_eq!(gate("out").check_real(&inside, Access::Write), Ok(()));
assert_eq!(gate("out").check_real(&outside, Access::Write), denied(&outside));
assert_eq!(with_script_gate(gate("out"), || check_write_real(&inside)), Ok(()), "the running command's gate passes it");
assert_eq!(with_script_gate(gate("out"), || check_write_real(&outside)), denied(&outside), "the running command's gate refuses it");
let chained = gate("out").followed_by(Arc::new(gate("outside")));
assert_eq!(chained.check_real(&inside, Access::Write), denied(&inside), "the chained gate refuses it");
assert_eq!(chained.check_real(&outside, Access::Write), denied(&outside), "the first gate refuses it");
let _ = std::fs::remove_dir_all(base);
}
}
+4
View File
@@ -328,6 +328,10 @@ pub struct Session {
/// While [`Session::place_read`] runs `file.place`: the file read for it, which the command
/// places instead of reading the file; `None` otherwise.
pub(crate) place_hand_off: Option<cmd::place::PlaceRead>,
/// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or
/// `links.relink` refuses a file that holds no image before the document changes, setting it to
/// `Some(false)`; `None` otherwise.
pub(crate) image_only: std::cell::Cell<Option<bool>>,
/// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which
/// the command loads the place cursor with instead of reading them; `None` otherwise.
pub(crate) queue_hand_off: Option<cmd::place::QueueRead>,
+181 -24
View File
@@ -86,8 +86,9 @@ struct Pending {
to: Vec<(Recipient, Vec<&'static str>)>,
/// When it was queued ([`PluginEvents::queued`] then).
seq: u64,
/// The event this enqueue pushed out of the waiting queue.
displaced: Option<u64>,
/// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether
/// that event was a `document.opened`.
pushed_out_by: Option<(u64, bool)>,
/// Queued by a command of the running script, whose run has not ended yet
/// ([`Session::plugin_events_script_ended`]).
by_script: bool,
@@ -162,6 +163,8 @@ pub struct PluginEvents {
/// The events dropped from `pending` since the last delivery, oldest first, which
/// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room.
evicted: VecDeque<Pending>,
/// The [`Pending::seq`] of each `document.opened` the running script's commands queued.
script_opens: HashSet<u64>,
/// How many events have been queued as their own entry.
queued: u64,
dispatching: bool,
@@ -223,11 +226,10 @@ impl PluginEvents {
}
return;
}
let mut displaced = None;
if self.pending.len() >= MAX_PENDING
&& let Some(dropped) = self.pending.pop_front()
&& let Some(mut dropped) = self.pending.pop_front()
{
displaced = Some(dropped.seq);
dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened));
log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name());
// Kept until the next delivery, in case a rollback frees room for it again.
// When that store is full, an open goes first, since only opens are rolled back.
@@ -238,8 +240,37 @@ impl PluginEvents {
self.evicted.push_back(dropped);
}
let to = to.into_iter().map(|r| (r, reasons.clone())).collect();
self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false });
self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false });
self.queued += 1;
self.prune_script_opens();
}
/// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone`
/// picks. The events those opens pushed out of the waiting queue return in their original
/// order, ahead of the events still waiting, while there is room.
fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) {
let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq);
self.pending.retain(|p| !dropped(p));
self.evicted.retain(|p| !dropped(p));
let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min();
while self.pending.len() < MAX_PENDING
&& let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq))
&& let Some(mut p) = self.evicted.remove(at)
{
p.pushed_out_by = None;
self.pending.push_front(p);
}
self.prune_script_opens();
}
/// Forgets the running script's opens that no waiting or pushed-out event refers to.
fn prune_script_opens(&mut self) {
if self.script_opens.is_empty() {
return;
}
let referenced: HashSet<u64> =
self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect();
self.script_opens.retain(|seq| referenced.contains(seq));
}
fn notice(&mut self, n: Notice) {
@@ -362,6 +393,9 @@ impl Session {
&& let Some(p) = self.plugin_events.pending.back_mut()
{
p.by_script = true;
if event == Event::DocumentOpened {
self.plugin_events.script_opens.insert(p.seq);
}
}
}
@@ -370,12 +404,13 @@ impl Session {
/// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since
/// the documents they opened were discarded with its working copy. Its saves stay, since the
/// files they wrote stay written, and so do the events of documents a frontend opened while the
/// run was paused. The next delivery gives what is left in the order it was queued.
/// run was paused. Events those opens pushed out of the waiting queue come back, as after
/// [`Session::forget_plugin_opens_since`]. The next delivery gives what is left in the order it was queued.
pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) {
let events = &mut self.plugin_events;
let opens = std::mem::take(&mut events.script_opens);
if !kept {
events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened));
events.drop_opens(|seq| opens.contains(&seq));
}
for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) {
p.by_script = false;
@@ -389,21 +424,9 @@ impl Session {
/// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback
/// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The
/// saves stay, since the files they wrote stay written.
/// Events displaced by those opens return in their original order, ahead of the events still
/// waiting, while there is room.
/// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]).
pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) {
let events = &mut self.plugin_events;
let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark;
let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect();
events.pending.retain(|p| !undone(p));
events.evicted.retain(|p| !undone(p));
while events.pending.len() < MAX_PENDING
&& let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq))
&& let Some(p) = events.evicted.remove(at)
{
events.pending.push_front(p);
}
self.plugin_events.drop_opens(|seq| seq >= mark);
}
/// Compares each open document with how the last check saw it and queues the events its changes
@@ -489,7 +512,19 @@ impl Session {
}
let subs: HashMap<Recipient, Arc<Plugin>> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect();
self.plugin_events.dispatching = true;
self.plugin_events.evicted.clear();
// Events pushed out by the opens of a running script stay until its run ends, which puts
// them back if the run fails.
let events = &mut self.plugin_events;
let opens = &events.script_opens;
let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq));
let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min();
events.evicted.retain(|p| {
restorable(p)
|| (first.is_some_and(|seq| p.seq >= seq)
&& (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r))))
});
let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min();
events.prune_script_opens();
// A handler's calls are checked as calls from outside, also when the command that ended
// played saved steps ([`Session::replay`] puts its flag back only after this delivery).
let replaying = self.set_replaying(false);
@@ -512,6 +547,11 @@ impl Session {
if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) {
continue;
}
p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event)));
if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) {
held.push_back(p);
continue;
}
let mut served = 0;
for (i, (r, reasons)) in p.to.iter().enumerate() {
let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else {
@@ -547,8 +587,10 @@ impl Session {
self.depth = depth;
self.set_replaying(replaying);
self.plugin_events.dispatching = false;
self.plugin_events.prune_script_opens();
self.plugin_events.pending.iter().any(|p| {
!p.by_script
&& frontend_barrier.is_none_or(|seq| p.seq < seq)
&& (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document))
&& p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0))
})
@@ -854,6 +896,121 @@ mod tests {
);
}
#[test]
fn a_failed_script_run_brings_back_the_events_its_opens_pushed_out() {
let mut s = Session::new();
let r: Recipient = ("a".into(), "h".into(), 1);
for uid in 1..=3 {
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]);
}
let before = s.plugin_events.pending.clone();
// Enough opens to fill the store of pushed-out events, which then drops opens first.
for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 {
queue_script_open(&mut s, 100 + uid, &r);
}
assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED);
assert_eq!(s.plugin_events.pending.len(), MAX_PENDING);
assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out");
s.plugin_events_script_ended(false);
assert_eq!(s.plugin_events.pending, before);
}
#[test]
fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() {
let mut s = Session::new();
let r: Recipient = ("a".into(), "h".into(), 1);
for uid in 1..=MAX_PENDING as u64 {
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]);
}
queue_script_open(&mut s, 100, &r);
s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]);
s.plugin_events.pending.back_mut().unwrap().by_script = true;
s.plugin_events_script_ended(false);
let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect();
let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect();
assert_eq!(saves, expected);
}
#[test]
fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() {
use vectorcraft_plugins::wat as tpl;
let mut s = Session::new();
let manifest = concat!(
r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#,
r#""events":["document.opened","document.saved"]}"#
);
let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap();
let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap());
let r = recipient(&plugin);
s.plugin_events.test_subscribers = Some(vec![plugin]);
s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]);
s.script_in_run = true;
for uid in 0..MAX_PENDING as u64 {
queue_script_open(&mut s, 100 + uid, &r);
}
s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]);
assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame");
assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open");
s.script_in_run = false;
s.plugin_events_script_ended(false);
s.deliver_plugin_events();
let given: Vec<Value> = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect();
let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect();
assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]);
}
#[test]
fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() {
let mut s = Session::new();
let r: Recipient = ("a".into(), "h".into(), 1);
for uid in 0..2 * MAX_PENDING as u64 {
let mark = s.plugin_events_mark();
queue_script_open(&mut s, uid, &r);
s.forget_plugin_opens_since(mark);
assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references");
}
for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 {
queue_script_open(&mut s, uid, &r);
let events = &s.plugin_events;
assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len()));
}
s.plugin_events_script_ended(false);
assert!(s.plugin_events.pending.is_empty());
assert!(s.plugin_events.evicted.is_empty());
assert!(s.plugin_events.script_opens.is_empty());
}
#[test]
fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() {
let mut s = Session::new();
let r: Recipient = ("a".into(), "h".into(), 1);
for uid in 1..=3 {
s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]);
}
let before = s.plugin_events.pending.clone();
s.script_in_run = true;
for uid in 0..MAX_PENDING as u64 {
queue_script_open(&mut s, 100 + uid, &r);
}
// A save a frontend queued while the run is paused pushes out the first open.
s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]);
s.deliver_plugin_events();
assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on");
s.script_in_run = false;
s.plugin_events_script_ended(false);
assert_eq!(s.plugin_events.pending, before);
}
/// Queues a `document.opened` as a command of a running script does.
fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) {
s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]);
if let Some(p) = s.plugin_events.pending.back_mut() {
p.by_script = true;
s.plugin_events.script_opens.insert(p.seq);
}
}
#[test]
fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() {
let mut s = Session::new();
+3 -2
View File
@@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
// A document whose active artboard the script chose uses that choice, not the one the run
// started with.
// started with, nor the Artboard tool's selection from the start of the run.
let chosen = h.session.borrow().active().and_then(|st| {
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
Some((st.uid, super::dom::active_artboard(st)))
@@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
Some(chosen) => std::slice::from_ref(chosen),
None => h.active_artboards.as_slice(),
};
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid));
let start = Start { active, picks, batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
+3 -2
View File
@@ -125,6 +125,7 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
/// What [`after_command`] compares with, taken before each command a script runs
/// ([`variables::before_command`]).
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
tracing::before_command(h);
variables::before_command(h, id)
}
@@ -427,7 +428,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
/// Notes the changes a command made to the points of the paths the run has read
/// ([`paths::see_all_points`]).
pub(super) fn see_points(h: &Host) {
pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> {
paths::see_all_points(h)
}
@@ -1070,7 +1071,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res
/// is made active, so bounds it reads take in type that the switch measured again (in the
/// document's own composite fonts, [`Session::set_active`]).
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
paths::see_all_points(h);
paths::see_all_points(h)?;
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f));
h.dom.editing.set(kept);
+36 -11
View File
@@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool {
/// The real path of the `File` `d` gives as an image to place or relink: one the script may read
/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of
/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no
/// error names the path.
/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path.
/// What the file holds is checked by the command that places or relinks it, which reads it once.
fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?;
if path.len() > super::super::files::MAX_PATH_CHARS {
@@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
if meta.len() > MAX_PLACED_BYTES {
return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20)));
}
let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned();
// What the file holds, read the way `file.place` reads it, before the document changes.
let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?;
if field(&info, "pixelWidth").is_none() {
return Err(HostError::Error(NOT_AN_IMAGE.into()));
Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
}
/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink`
/// refusing a file that holds no image before the document changes: that refusal is
/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check
/// and for the image it places.
fn image_only<T>(h: &Host, f: impl FnOnce(&Host) -> Result<T, HostError>) -> Result<T, HostError> {
let kept = h.session.borrow().image_only.replace(Some(true));
let r = f(h);
let refused = h.session.borrow().image_only.replace(kept) == Some(false);
match r {
Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())),
r => r,
}
Ok(path)
}
// ---- PlacedItem ----
@@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
// The placement and its check run under one savepoint, so an error after the place leaves
// no linked image behind.
let id = super::atomically(h, |h| {
let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?;
let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?;
let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64));
let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId);
let linked =
@@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
fn placed_relink(h: &Host, a: &[Data]) -> Answer {
let item = this_of(h, a, "PlacedItem")?;
let path = image_path(h, arg(a, 1), "relink's file")?;
edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?;
image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?;
Ok(Data::Undefined)
}
@@ -473,7 +481,8 @@ fn area_of(m: Affine) -> bool {
/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix.
/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted
/// image is refused before anything changes; the matrix the image has already changes nothing.
/// image is refused before anything changes, and so is a locked or hidden image or one on a locked
/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing.
fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
let item = this_of(h, a, cls)?;
let m = matrix_value(arg(a, 1))?;
@@ -484,6 +493,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
if n.is_distorted_image() {
return Err(HostError::Error(DISTORTED.into()));
}
// The transform methods' refusals: a locked or hidden image, one inside a locked or hidden
// layer or group, and one on a locked artboard, whether or not the matrix changes.
let d = &st.doc;
let line = d.ancestry(item.id);
let any = |f: fn(&vectorcraft_doc::Node) -> bool| {
line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f)))
};
if any(|n| n.locked) {
return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0)));
}
if any(|n| !n.visible) {
return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0)));
}
if super::on_locked_artboard(h, st, item.id) {
return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0)));
}
let f = frame(st)?;
let target = Affine::new(match h.dom.coords.get() {
Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]],
+32 -4
View File
@@ -309,7 +309,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
let selected = with_doc(h, doc, |_, st| {
// The scan is charged by every selected object it looks at.
let objects = &st.selection.objects;
let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)));
h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?;
Ok::<_, HostError>(found.is_some())
})?;
Ok(Data::Bool(selected))
}
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
@@ -336,7 +343,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
let (doc, id) = this_layer(h, a)?;
let (ids, over) = with_doc(h, doc, |_, st| {
let (ids, over) = with_doc(h, doc, |s, st| {
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
let selected = &st.selection.objects;
h.charge_call(selected.len() as u64)?;
@@ -349,10 +356,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
// The walk is charged by every node it looks at, hidden and locked ones included, whether
// or not anything is added.
h.charge_call(count)?;
// While an object is isolated, the art that holds it is replaced by the isolated object,
// or by what an isolated group or other container holds, as Select All takes it.
let isolated = st.isolation.and_then(|i| st.doc.node(i));
let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default();
let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template()));
let mut candidates = Vec::with_capacity(art.len());
for o in art {
match isolated {
Some(_) if path.contains(&o) && !editable => {}
Some(c) if path.contains(&o) && c.is_container() => {
// The same walk as the layer's, through any sublayer the container holds.
let visited = collect_editable_art(c, &mut candidates);
h.charge_call(visited)?;
}
Some(c) if path.contains(&o) => candidates.push(c.id),
_ => candidates.push(o),
}
}
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
let mut ids = Vec::new();
for o in art {
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
for o in candidates {
if have.contains(&o)
|| !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o)
|| (s.guides_locked() && crate::is_guide_path(&st.doc, o))
{
continue;
}
// Only art that would be added counts toward the limit.
+74 -10
View File
@@ -862,7 +862,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer {
if clipping {
return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0)));
}
see_all_points(h);
see_all_points(h)?;
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
@@ -1236,6 +1236,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
}
/// The largest stroke weight in the path `item`'s own appearance, in points.
pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result<f64, HostError> {
read_path(h, item, |_, n, _| {
n.appearance
.items
.iter()
.filter_map(|item| match item {
vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width),
vectorcraft_doc::AppearanceItem::Fill(_) => None,
})
.fold(0.0, f64::max)
})
}
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
@@ -1377,24 +1391,32 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid; the other Global Edit members, which take the
/// object model's edit too, are looked at as well. A document that is the one the run last looked
/// at is skipped, as are its paths.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
/// at is skipped, as are its paths. The look is charged by the objects it looks at.
pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> {
let (keys, looked_at): (Vec<(u64, u64)>, u64) = {
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
let seen = h.dom.point_nodes.borrow();
let mut keys = Vec::new();
let mut looked_at = 0u64;
docs.retain(|uid, before| {
let state = s.documents().iter().find(|d| d.uid == *uid);
let after = state.map(|st| &st.doc);
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
return true;
}
// A document none of whose paths the run still holds points of is not looked at; reading
// points again keeps it as it is then.
if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) {
return false;
}
// Editing a path in an Objects on Path group can move the other paths in the group, so
// the outermost such group is looked at in place of the path. While Global Edit is on,
// an edit of the selected member (also one made by moving a group that holds it) is
// given to the other members, so each of them, or the outermost Objects on Path group
// holding it, is looked at too. Subtrees the command left as they were are skipped.
// Each node is paired with the node of the same id under the same parent now, so that no
// node is searched for through the whole document.
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
Some(item) => {
let root = |id: NodeId| {
@@ -1405,19 +1427,44 @@ pub(super) fn see_all_points(h: &super::Host) {
};
let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten();
let mut roots = std::collections::HashSet::new();
std::iter::once(item.id).chain(members).map(root).filter(|id| roots.insert(*id)).filter_map(|id| node_arc(before, id)).collect()
std::iter::once(item.id)
.chain(members)
.map(root)
.filter(|id| roots.insert(*id))
.filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))))
.collect()
}
None => before.layers.iter().collect(),
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
};
while let Some(node) = todo.pop() {
if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) {
// A group that moved to another parent keeps its node, so a node with children that is
// not found under its old parent is looked for among all the nodes now, listed once.
let mut all: Option<std::collections::HashMap<NodeId, &Arc<crate::doc::Node>>> = None;
while let Some((node, mut now)) = todo.pop() {
looked_at += 1;
if now.is_none()
&& node.children().is_some()
&& let Some(d) = after
{
let all = all.get_or_insert_with(|| {
let mut m = std::collections::HashMap::new();
let mut stack: Vec<&Arc<crate::doc::Node>> = d.layers.iter().collect();
while let Some(n) = stack.pop() {
m.insert(n.id, n);
stack.extend(n.children().into_iter().flatten());
}
looked_at += m.len() as u64;
m
});
now = all.get(&node.id).copied();
}
if now.is_some_and(|n| Arc::ptr_eq(node, n)) {
continue;
}
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
keys.push((*uid, node.id.0));
}
if let Some(children) = node.children() {
todo.extend(children);
todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at));
}
}
if let Some(after) = after {
@@ -1429,8 +1476,11 @@ pub(super) fn see_all_points(h: &super::Host) {
});
keys.sort_unstable();
keys.dedup();
keys
(keys, looked_at)
};
if looked_at > 0 {
h.charge_call(looked_at)?;
}
let editing = h.dom.editing.get();
for (uid, id) in keys {
let own = || match editing {
@@ -1443,6 +1493,20 @@ pub(super) fn see_all_points(h: &super::Host) {
};
see_points(h, (uid, id), own);
}
Ok(())
}
/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the
/// nodes of `after` it looks at.
fn paired<'a>(
before: &'a [Arc<crate::doc::Node>],
after: Option<&'a Vec<Arc<crate::doc::Node>>>,
looked_at: &mut u64,
) -> Vec<(&'a Arc<crate::doc::Node>, Option<&'a Arc<crate::doc::Node>>)> {
let after = after.map_or(&[][..], Vec::as_slice);
*looked_at += after.len() as u64;
let now: std::collections::HashMap<NodeId, &Arc<crate::doc::Node>> = after.iter().map(|n| (n.id, n)).collect();
before.iter().map(|n| (n, now.get(&n.id).copied())).collect()
}
fn points_at(h: &super::Host, a: &[Data]) -> Answer {
+8 -6
View File
@@ -32,8 +32,8 @@
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one
//! `unit`, more than 0 and at most 1000.
//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is
//! one drawing unit. It is at least 0.0001 and at most 1000.
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
//! the default its help page gives and throws an error that says it is not available yet at any
//! other value; a property the help pages do not list throws an error that names it, unless it is
@@ -739,10 +739,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result:
Data::Number(n) if n.is_finite() => *n,
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
};
if !(n > 0.0 && n <= 1000.0) {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000")));
// A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is
// 0.0001%.
if !(0.0001..=1000.0).contains(&n) {
return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000")));
}
p.insert("scale".into(), json!(n));
p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start())));
}
"version" => {
let version = match pick("AutoCADCompatibility")? {
@@ -1025,7 +1027,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
}
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
if !matches!(kind.format, "svg" | "dxf") {
p.insert("scale".into(), json!(hs / 100.0));
}
+47 -5
View File
@@ -128,6 +128,10 @@ pub(super) struct State {
prev: RefCell<HashMap<(u64, u64), u64>>,
sources: RefCell<HashMap<(u64, u64), NodeId>>,
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
/// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`])
/// and the lowest id the run could allocate after the first note or the latest revert
/// ([`note_document`]).
marks: RefCell<HashMap<u64, (u64, u64)>>,
retraces: Cell<usize>,
}
@@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
});
}
/// Before each command a script runs: notes the active document ([`note_document`]).
pub(super) fn before_command(h: &Host) {
let s = h.session.borrow();
if let Some(st) = s.active() {
note_document(h, st);
}
}
/// Records the next object id when the run first notes the document `st`. A revert resets
/// the mark to the reloaded document's next object id and keeps the descendant snapshots.
/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it.
fn note_document(h: &Host, st: &crate::DocState) {
let mut marks = h.dom.tracing.marks.borrow_mut();
match marks.get_mut(&st.uid) {
Some((reverts, _)) if *reverts == st.reverts => {}
Some((reverts, mark)) => {
*reverts = st.reverts;
*mark = st.doc.peek_next_id();
}
None => {
marks.insert(st.uid, (st.reverts, st.doc.peek_next_id()));
}
}
}
/// Returns the lowest id the run could allocate in document `uid` after its first note or latest
/// revert ([`note_document`]).
fn mark(h: &Host, uid: u64) -> Option<u64> {
h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark)
}
pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool {
let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied();
source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
@@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
/// the replacement would discard. The objects looked at are charged to the run either way.
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
let (visited, result) = read_group(h, item, |_, group| {
let (visited, result) = read_group(h, item, |st, group| {
note_document(h, st);
remember_source(h, item.doc.uid, group);
// The objects the trace made, as the tracing records them; a tracing saved without that
// record is checked against the objects it held when this run first saw it.
// A tracing with a record is checked against the objects its trace made. A tracing without
// a record is checked against its first descendant snapshot, which survives reverts.
// If the group id is below the document's mark, members at or above the mark are also added.
// A revert resets the mark to the reloaded document's next object id.
let made = group.trace_made();
let descendants = h.dom.tracing.descendants.borrow();
let ids = match made {
Some(_) => None,
None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?),
None => descendants.get(&(item.doc.uid, item.id.0)),
};
let newer = match made {
Some(_) => None,
None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m),
};
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
let mut visited = 0u64;
@@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
(Some(m), _) => !m.contains(n.id),
(None, Some(ids)) => !ids.contains(&n.id),
(None, None) => false,
};
} || newer.is_some_and(|m| n.id.0 >= m);
// Added artwork is reported before a locked object, whichever comes first.
if added {
return Ok((visited, Err(HostError::Error(refusal.into()))));
+34 -13
View File
@@ -20,9 +20,13 @@
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to
//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any
//! other value, and a scale of strokes and effects with positions left as they are, throws an
//! error that says so.
//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points.
//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight
//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale
//! of strokes and effects with positions left as they are, throws an error that says so.
//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN`
//! still uses the first artboard's bottom-left corner; other named points use the origin.
//! Its linked opacity mask, strokes, effects and patterns transform with the same options.
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
//! with nothing changed, and so are
@@ -37,16 +41,16 @@ use super::matrix::{self, Matrix};
use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc};
/// The error for an object on a locked artboard.
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
/// The error for a locked object.
const LOCKED: &str = "cannot transform locked objects";
pub(super) const LOCKED: &str = "cannot transform locked objects";
/// The error for a guide while guides are locked.
const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked";
/// The error for a hidden object.
const HIDDEN: &str = "cannot transform hidden objects";
pub(super) const HIDDEN: &str = "cannot transform hidden objects";
/// The identity matrix.
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
@@ -136,8 +140,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> {
}
/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name`
/// ([`anchor_name`]) names.
fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Point, HostError> {
/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`.
fn anchor(h: &Host, item: Item, r: Option<Rect>, name: &str) -> std::result::Result<Point, HostError> {
if r.is_none() && !paths::is_path(h, item) {
return Err(HostError::Error("the object has no bounds".into()));
}
if name == "DOCUMENTORIGIN" {
return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])));
}
let Some(r) = r else {
return Ok(Point::ORIGIN);
};
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
Ok(match name {
"TOPLEFT" => Point::new(r.x0, r.y0),
@@ -148,7 +161,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Poin
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
"BOTTOM" => Point::new(cx, r.y1),
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
_ => Point::new(cx, cy),
})
}
@@ -222,12 +234,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) {
return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0)));
}
// The identity acts the same about every point, so an object without bounds (an empty path)
// takes it too.
// The identity acts the same about every point for any object.
let o = match (about, bounds) {
_ if m == IDENTITY => Point::ORIGIN,
(Some(name), Some(r)) => anchor(h, item, r, name)?,
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
(Some(name), r) => anchor(h, item, r, name)?,
(None, _) => Point::ORIGIN,
};
let xf = on_page(m, o);
@@ -249,6 +259,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
}
let c = xf.as_coeffs();
let identity = xf == Affine::IDENTITY;
// Every stroke layer's weight is checked with the factor `object.transform` applies.
let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None };
if let Some(k) = factor
&& paths::is_path(h, item)
&& (!k.is_finite() || {
let width = paths::largest_stroke_weight(h, item)? * k;
!width.is_finite() || width > paths::MAX_STROKE_WIDTH
})
{
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
}
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
// The transformation and the stroke weight change together or not at all.
atomically(h, |h| {
+3 -1
View File
@@ -1519,8 +1519,10 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::see_points(host);
// The command stays kept when the look at its changes passes a limit, which ends the run.
let seen = dom::see_points(host);
dom::after_kept_command(host);
seen?;
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
}
+1
View File
@@ -143,6 +143,7 @@ impl Session {
composite_names_registered: HashSet::new(),
reading: false,
place_hand_off: None,
image_only: std::cell::Cell::new(None),
queue_hand_off: None,
place_queue_roots: None,
place_queue_loads: 0,
+33
View File
@@ -5189,6 +5189,39 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
assert!(!s.doc().unwrap().selection.contains(b));
}
/// The selection commands and Curvature edits refuse a mode or op they do not know, and leave the
/// selection, the document and the undo history as they were.
#[test]
fn an_unknown_selection_mode_or_curvature_op_is_refused_without_changes() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 30.0, 20.0);
let b = rect(&mut s, 50.0, 10.0, 30.0, 20.0);
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let objects = s.doc().unwrap().selection.objects.clone();
let anchors = s.doc().unwrap().selection.anchors.clone();
let undo = s.doc().unwrap().history.undo.len();
let mut wrong = vec![];
for (cmd, p, says) in [
("select.segments", json!({"id": a.0, "segments": [[0, 0]], "mode": "bogus"}), "unknown mode"),
("select.anchorsMany", json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "bogus"}), "unknown mode"),
("select.magicWand", json!({"id": a.0, "mode": "bogus"}), "unknown mode"),
("path.curvatureEdit", json!({"id": a.0, "op": "bogus", "anchor": 0, "x": 0, "y": 0}), "unknown op"),
] {
match s.execute(cmd, &p) {
Err(e) if e.to_string().contains(says) => {}
other => wrong.push(format!("{cmd}: {other:?}")),
}
let st = s.doc().unwrap();
let changed = st.selection.objects != objects || st.selection.anchors != anchors || st.doc != doc || st.history.undo.len() != undo;
if changed {
wrong.push(format!("{cmd} changed the selection, the document or the undo history"));
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With
/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that
/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked
@@ -225,6 +225,7 @@ fn a_linked_handle_makes_the_anchor_smooth() {
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}),
json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "symmetric": true}),
json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}),
json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}),
json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}),
+17
View File
@@ -444,3 +444,20 @@ fn a_group_used_as_the_clipping_path_adds_none_of_its_own_fills() {
let b = read.heads[0].path.bounds().unwrap();
assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the square alone: {b:?}");
}
/// An arrowheads file over the size limit is refused from its size: no heads are listed, and the
/// error says why.
#[test]
fn an_arrowheads_file_over_the_size_limit_lists_no_heads() {
let dir = folder("too-big");
let file = dir.join(arrowheads::FILE_NAME);
// Sparse: no data blocks are written.
std::fs::File::create(&file).unwrap().set_len(arrowheads::MAX_FILE_BYTES + 1).unwrap();
let (mut s, _) = session_with_line();
s.attach_arrowheads_file(file.to_string_lossy().to_string());
let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(list["arrowheads"], json!([]));
let error = list["error"].as_str().unwrap_or_default();
assert!(error.contains(&format!("larger than {} MB", arrowheads::MAX_FILE_BYTES >> 20)), "{list}");
}
+1
View File
@@ -456,6 +456,7 @@ fn a_linked_spine_handle_makes_the_point_smooth() {
for bad in [
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}),
json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}),
json!({"anchor": 1, "handle": "out", "x": 60, "y": 40, "link": true, "symmetric": true}),
json!({"anchor": 1, "x": 75, "y": 25, "link": true}),
] {
assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}");
+74
View File
@@ -6802,6 +6802,80 @@ fn join_two_subpaths_of_same_path_node() {
assert_eq!(pd.subpaths[0].anchors[3].p, Point::new(250.0, 0.0));
}
/// A path with one open two-anchor subpath per pair of points.
fn path_of_lines(s: &mut Session, lines: &[[Point; 2]]) -> NodeId {
let p = line(s, lines[0][0].x, lines[0][0].y, lines[0][1].x, lines[0][1].y);
let rest: Vec<_> = lines[1..].iter().map(|l| vectorcraft_geom::SubPath::polyline(l, false)).collect();
s.edit("Add Subpaths", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(p).unwrap().kind {
path.subpaths.extend(rest);
}
Ok(())
})
.unwrap();
p
}
fn subpath_points(s: &Session, id: NodeId) -> Vec<Vec<Point>> {
path(s, id).subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p).collect()).collect()
}
/// `path.join` with the same id twice and `subpaths` joins two subpaths of one path. Here the later
/// subpath comes first, so the earlier one is removed and the joined subpath takes the later one's
/// place, the coincident junction anchors become one, and the subpath between them stays as it was.
/// One undo step brings back all three subpaths.
#[test]
fn join_of_one_path_by_ids_and_subpaths_merges_the_junction_and_keeps_the_other_subpath() {
let mut s = session();
let pt = Point::new;
let p = path_of_lines(&mut s, &[[pt(100.0, 0.0), pt(110.0, 0.0)], [pt(500.0, 0.0), pt(510.0, 0.0)], [pt(0.0, 0.0), pt(100.0, 0.0)]]);
let before = subpath_points(&s, p);
let undo = s.doc().unwrap().history.undo.len();
s.execute("path.join", &json!({"ids": [p.0, p.0], "subpaths": [2, 0], "ends": ["last", "first"]})).unwrap();
assert_eq!(subpath_points(&s, p), vec![vec![pt(500.0, 0.0), pt(510.0, 0.0)], vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(110.0, 0.0)]]);
assert!(path(&s, p).subpaths.iter().all(|sp| !sp.closed));
assert_eq!(s.doc().unwrap().selection.objects, vec![p]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(subpath_points(&s, p), before);
}
/// With both ends of one open subpath direct-selected, Join closes that subpath and leaves the
/// other open subpath of the same path as it is, instead of joining the two.
#[test]
fn join_with_both_ends_of_one_subpath_selected_closes_that_subpath() {
let mut s = session();
let pt = Point::new;
let p = path_of_lines(&mut s, &[[pt(0.0, 0.0), pt(100.0, 0.0)], [pt(0.0, 50.0), pt(100.0, 50.0)]]);
s.execute("select.anchors", &json!({"id": p.0, "anchors": [[1, 0], [1, 1]], "mode": "set"})).unwrap();
s.execute("path.join", &json!({})).unwrap();
assert_eq!(subpath_points(&s, p), vec![vec![pt(0.0, 0.0), pt(100.0, 0.0)], vec![pt(0.0, 50.0), pt(100.0, 50.0)]]);
let pd = path(&s, p);
assert!(!pd.subpaths[0].closed, "the other subpath stays open");
assert!(pd.subpaths[1].closed, "the subpath with both ends selected is closed");
}
/// With both ends of one line selected and only the first end of another, Join takes the nearest
/// pair of selected ends: the second line's unselected end is nearer but is not joined.
#[test]
fn join_with_both_ends_of_one_line_selected_takes_the_nearest_selected_pair() {
let mut s = session();
let pt = Point::new;
let a = line(&mut s, 0.0, 0.0, 100.0, 0.0);
let b = line(&mut s, 300.0, 0.0, 105.0, 0.0);
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
s.execute("path.join", &json!({})).unwrap();
let joined = paths(&s);
assert_eq!(joined.len(), 1, "{joined:?}");
let pts: Vec<Point> = joined[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(pts, vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(300.0, 0.0), pt(105.0, 0.0)]);
}
/// Direct-selecting 2 open endpoints in a complex compound path with multiple open segments joins only those 2.
#[test]
fn join_complex_compound_path_direct_endpoints() {
+59
View File
@@ -66,6 +66,65 @@ fn halftone_options() {
}
}
/// The dot path Vector Halftone makes from a gray square with `params`.
fn dots_of(params: serde_json::Value) -> vectorcraft_geom::PathData {
let mut s = session();
red_rect(&mut s);
s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap();
let r = s.execute("object.vectorHalftone", &params).unwrap();
let g = node(&s, NodeId(r["id"].as_u64().unwrap()));
g.children().unwrap()[0].path_data().unwrap().clone()
}
#[test]
fn halftone_styles_set_the_shape_and_angle_unless_given() {
assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots"})), dots_of(json!({"frequency": 18, "shape": "circle", "angle": 0})));
assert_eq!(dots_of(json!({"frequency": 18, "style": "gridAngle"})), dots_of(json!({"frequency": 18, "shape": "euclidean", "angle": 45})));
assert_ne!(dots_of(json!({"frequency": 18, "style": "grid"})), dots_of(json!({"frequency": 18})));
// A given shape or angle wins over the style's.
assert_eq!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "angle": 0})));
assert_ne!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "style": "grid"})));
assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots", "angle": 45})), dots_of(json!({"frequency": 18, "style": "gridDotsAngle"})));
// An unknown style is refused and leaves the document as it was.
let mut s = session();
red_rect(&mut s);
let before = s.doc().unwrap().doc.clone();
assert!(s.execute("object.vectorHalftone", &json!({"style": "checker"})).is_err());
assert_eq!(s.doc().unwrap().doc, before);
}
#[test]
fn halftone_refuses_null_and_non_string_styles() {
for style in [json!(null), json!(42), json!(true), json!([]), json!({})] {
let mut s = session();
red_rect(&mut s);
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let result = s.execute("object.vectorHalftone", &json!({"style": style}));
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{style}: {result:?}");
assert_eq!(s.doc().unwrap().doc, before, "{style}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{style}");
}
assert_eq!(dots_of(json!({"style": "custom"})), dots_of(json!({})));
}
/// The live effect refuses an unknown style when applied or edited, and leaves the document as it
/// was; a known style in another letter case is taken.
#[test]
fn halftone_effect_refuses_an_unknown_style() {
const HALFTONE: &str = "addon.color.halftone";
let mut s = session();
red_rect(&mut s);
let before = s.doc().unwrap().doc.clone();
assert!(s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "gridDot"}})).is_err());
assert_eq!(s.doc().unwrap().doc, before);
s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "GRIDDOTS"}})).unwrap();
let applied = s.doc().unwrap().doc.clone();
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "gridDot"}})).is_err());
assert_eq!(s.doc().unwrap().doc, applied);
s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "custom"}})).unwrap();
}
#[test]
fn halftone_refuses_a_param_of_the_wrong_type() {
for bad in [
+23
View File
@@ -1299,3 +1299,26 @@ fn a_library_is_exported_to_a_file_and_imported_from_it() {
v.libraries.set_dir(Some(folder));
assert_eq!(groups(&mut v), [("Logos".into(), refs(&[("graphic", &g)]))]);
}
/// A library file over 512 MB is refused from its size before it is opened: the file here cannot
/// be opened at all, so only the size check gives this error.
#[cfg(unix)]
#[test]
fn a_library_file_over_the_size_limit_is_refused_before_it_is_read() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("vc-library-too-big-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("big.vclibrary");
// Sparse: no data blocks are written.
std::fs::File::create(&path).unwrap().set_len((512 << 20) + 1).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
// A process that may read any file (root) opens it: nothing to check.
let opened = std::fs::File::open(&path).is_ok();
let r = (!opened).then(|| session().execute("library.import", &json!({"path": path.to_string_lossy()})));
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
let _ = std::fs::remove_dir_all(&dir);
let Some(r) = r else { return }; // root opened the file: the size check is not what refuses it
let e = r.err().unwrap_or_else(|| panic!("the file was imported")).to_string();
assert!(e.contains("the file is larger than 512 MB"), "{e}");
}
+39
View File
@@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() {
assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels);
}
#[test]
fn a_bad_preset_or_preset_category_is_an_error() {
let s = new_doc(json!({"preset": "A4", "presetCategory": "print"}));
assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01);
for p in [
json!({"preset": "A4", "presetCategory": "Napkins"}),
json!({"preset": "A4", "presetCategory": 5}),
json!({"preset": "A4", "presetCategory": ""}),
json!({"preset": "A4", "presetCategory": " Print "}),
json!({"presetCategory": "Print"}),
json!({"presetCategory": "Napkins"}),
json!({"preset": 5}),
json!({"preset": true, "presetCategory": "Print"}),
] {
assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}");
let mut save = p.clone();
save["name"] = json!("Mine");
assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}");
}
let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string();
assert!(e.contains("unknown category `Napkins`"), "{e}");
// Null leaves a param out.
Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap();
// A step this version took replays, and one an earlier version took still plays as it did then.
let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"}));
let mut s = Session::new();
for (id, p) in &recorded.journal {
s.replay(id, p).unwrap();
}
assert_eq!(boards(&s), boards(&recorded));
let mut recorded = new_doc(json!({}));
recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print");
let mut s = Session::new();
for (id, p) in &recorded.journal {
s.replay(id, p).unwrap();
}
assert_eq!(boards(&s), boards(&recorded));
}
#[test]
fn ppi_overprint_preview_and_bad_params() {
// Overprint Preview is process-wide.
+48
View File
@@ -123,6 +123,54 @@ fn intersect_disjoint_is_error_and_no_change() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
/// Pathfinder refuses a selection that holds no paths (an image alone) and paths with an anchor
/// that is not a finite number, and leaves the document and the undo history as they were.
#[test]
fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() {
let mut s = session();
let image = s
.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![0; 8]));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
height: 2,
xf: Default::default(),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string();
assert!(e.contains("select paths"), "{e}");
assert!(s.doc().unwrap().doc == before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 5.0, 0.0, 10.0, 10.0);
s.edit("Break", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(a).unwrap().kind {
path.subpaths[0].anchors[1].p.x = f64::NAN;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let undo_len = s.doc().unwrap().history.undo.len();
let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string();
assert!(e.contains("invalid coordinates"), "{e}");
assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some());
assert!(s.doc().unwrap().doc.node(image).is_some());
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
#[test]
fn exclude_makes_compound() {
let mut s = session();
+72
View File
@@ -2739,6 +2739,78 @@ fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
assert!(vectorcraft_plugins::registry::remove(id));
}
/// Sets the bytes the stored plug-ins of this thread's stores may read together, and puts the
/// usual budget back when dropped, a failed assertion included.
struct StoreBudget;
impl StoreBudget {
fn set(bytes: u64) -> Self {
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(bytes));
StoreBudget
}
}
impl Drop for StoreBudget {
fn drop(&mut self) {
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE));
}
}
/// The failure listed for each stored file of `folder`, as (file name, reason), sorted.
fn stored_failures_in(folder: &std::path::Path) -> Vec<(String, String)> {
let mut rows: Vec<(String, String)> = crate::store::failed_stored_plugins(folder)
.into_iter()
.map(|(p, why)| (p.file_name().unwrap().to_string_lossy().into_owned(), why))
.collect();
rows.sort();
rows
}
/// Once the stored plug-ins have used up the bytes a store may read, the stored files after them
/// are listed as failed and are not installed.
#[test]
fn stored_plugins_past_the_store_budget_are_listed_as_failed() {
let (folder, first) = store_with("plugin-budget-used-up", "test.engine.budgetused.a");
for id in ["test.engine.budgetused.b", "test.engine.budgetused.c"] {
let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap();
std::fs::write(folder.0.join(format!("{id}.wasm")), module).unwrap();
}
let len = std::fs::metadata(&first).unwrap().len();
let mut s = session();
{
let _budget = StoreBudget::set(len);
s.attach_plugin_store(folder.0.clone());
}
let installed: Vec<bool> =
["a", "b", "c"].iter().map(|n| vectorcraft_plugins::registry::get(&format!("test.engine.budgetused.{n}")).is_some()).collect();
let failed = stored_failures_in(&folder.0);
for n in ["a", "b", "c"] {
vectorcraft_plugins::registry::remove(&format!("test.engine.budgetused.{n}"));
}
assert_eq!(installed, [true, false, false], "only the first file fits the budget");
let why = format!("the stored plug-ins hold more than {} bytes together", crate::store::MAX_PLUGIN_STORE);
let expected: Vec<(String, String)> = ["b", "c"].iter().map(|n| (format!("test.engine.budgetused.{n}.wasm"), why.clone())).collect();
assert_eq!(failed, expected);
}
/// A stored file longer than the bytes the store may still read is skipped and listed as failed.
#[test]
fn a_stored_plugin_larger_than_the_store_budget_is_skipped() {
let id = "test.engine.budgetsmall";
let (folder, module) = store_with("plugin-budget-small", id);
let len = std::fs::metadata(&module).unwrap().len();
let mut s = session();
{
let _budget = StoreBudget::set(len - 1);
s.attach_plugin_store(folder.0.clone());
}
let installed = vectorcraft_plugins::registry::remove(id);
assert!(!installed, "a file over the budget is not read");
let failed = stored_failures_in(&folder.0);
assert_eq!(failed.len(), 1, "{failed:?}");
assert!(failed[0].1.contains(&format!("larger than {} bytes", len - 1)), "{failed:?}");
}
/// A stored file replaced after its module loaded, by one of the same length with the same modified
/// time, is skipped: its content no longer holds the module. That holds for a file modified moments
/// ago and for one modified an hour ago.
+12
View File
@@ -458,6 +458,18 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
// Once the script makes an artboard active, the selection from the start of the run no longer holds.
let (mut s, was, _) = setup();
let before = objects(&s);
log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Paste', 'Set');", &actions);
assert_eq!(objects(&s), before + 1, "one copy, on the artboard the script made active");
let pasted = s.active().unwrap().selection.objects.clone();
let copy = s.active().unwrap().doc.bounds_of(&pasted, false).unwrap();
assert!(copy.x0 >= was[1].x0 && copy.x1 <= was[1].x1, "the copy is on artboard 1: {copy:?}");
let (mut s, was, art) = setup();
log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(2); app.doScript('Fit', 'Set');", &actions);
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [was[0], was[1], art[2]], "only the artboard the script made active fits its art");
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
let (mut s, ..) = setup();
s.reset_tool();
+56
View File
@@ -4276,6 +4276,62 @@ fn has_selected_artwork_charges_the_walk_when_nothing_is_added() {
assert!(error.contains("passed more data"), "{error}");
}
/// Reading `hasSelectedArtwork` is charged for every selected object it looks at.
#[test]
fn has_selected_artwork_charges_the_selection_it_reads() {
let repeated = |n: usize| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect();
s.execute("layer.new", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": ids})).unwrap();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13)));
let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork;");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
r
};
repeated(1).unwrap();
let error = repeated(200).unwrap_err().to_string();
assert!(error.contains("passed more data"), "{error}");
}
/// While a group is isolated, `hasSelectedArtwork = true` selects the art inside the group, as
/// Select All does.
#[test]
fn has_selected_artwork_selects_inside_an_isolated_group() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.isolate", &json!({"id": g})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true; vc.log(l.hasSelectedArtwork);");
assert_eq!(out, [json!(true)]);
let sel = &s.active().unwrap().selection.objects;
assert!(sel.contains(&a) && sel.contains(&b), "{sel:?}");
}
/// While Lock Guides is on, a path made into a guide is not counted as art to add, so a selection
/// at the limit does not refuse a layer that holds only such a path.
#[test]
fn has_selected_artwork_skips_locked_guide_paths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0);
s.active_mut().unwrap().selection.objects = vec![other; 10_000];
run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}"));
assert_eq!(s.active().unwrap().selection.objects.len(), 10_000);
s.execute("select.none", &json!({})).unwrap();
let steps = undo_steps(&s);
run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap();
assert_eq!(undo_steps(&s), steps);
assert!(s.active().unwrap().selection.objects.is_empty());
}
#[test]
fn the_report_gives_the_active_artboard_the_run_leaves() {
let (mut s, _, _) = doc();
@@ -287,6 +287,45 @@ fn a_file_that_is_not_an_image_is_refused_before_placing() {
let _ = std::fs::remove_dir_all(base);
}
/// How many times the engine read the file at `path` on this thread since the last call.
#[cfg(not(target_arch = "wasm32"))]
fn reads_of(path: &Path) -> usize {
let path = path.to_string_lossy();
crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn placing_or_relinking_from_a_script_reads_the_file_once() {
let base = folder("read-once");
let (a, b) = (base.join("main/a.png"), base.join("main/b.png"));
std::fs::write(&a, gray_png(10, 10)).unwrap();
std::fs::write(&b, gray_png(20, 10)).unwrap();
let mut s = session();
reads_of(&a);
log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a)));
assert_eq!(reads_of(&a), 1, "placing reads the file once");
log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b)));
assert_eq!(reads_of(&b), 1, "relinking reads the file once");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() {
let base = folder("relink-text");
let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt"));
std::fs::write(&a, gray_png(10, 10)).unwrap();
std::fs::write(&notes, "hello").unwrap();
let mut s = session();
let id = place(&mut s, &a, true);
let before = undo_steps(&s);
let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&notes)));
assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}");
assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]);
assert_eq!(undo_steps(&s), before);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn placed_items_add_is_bounded() {
let base = folder("pending");
@@ -497,6 +536,41 @@ fn a_stale_placed_item_is_not_a_relative_object() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn image_matrix_refuses_locked_hidden_and_locked_artboard_images() {
let base = folder("matrix-locks");
let g = base.join("main/g.png");
std::fs::write(&g, gray_png(10, 20)).unwrap();
let mut s = session();
let id = place(&mut s, &g, true);
// A moved matrix and the matrix the image already has are refused alike.
let sets = [
"var p = app.activeDocument.placedItems[0], m = p.matrix; m.mValueTX = m.mValueTX + 5; p.matrix = m;",
"var p = app.activeDocument.placedItems[0]; p.matrix = p.matrix;",
];
let refused = |s: &mut Session, message: &str| {
for set in sets {
let (was, before) = (s.active().unwrap().doc.clone(), undo_steps(s));
let e = failure(s, &base, set);
assert!(e.contains(message), "{set}: {e}");
assert_eq!(*s.active().unwrap().doc, *was, "{set}");
assert_eq!(undo_steps(s), before, "{set}");
}
};
for (field, set_to, message) in [("locked", true, "cannot transform locked objects"), ("visible", false, "cannot transform hidden objects")] {
s.execute("object.setProps", &json!({"ids": [id.0], field: set_to})).unwrap();
refused(&mut s, message);
s.execute("object.setProps", &json!({"ids": [id.0], field: !set_to})).unwrap();
}
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
refused(&mut s, "cannot transform objects on a locked artboard");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn image_matrix_refuses_bad_values_without_changing_the_image() {
let base = folder("matrix-bad");
@@ -1089,6 +1089,42 @@ fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() {
assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits");
}
/// After a run reads a path's points, each command makes the run look through the document's
/// changed layers for paths whose points it read, and that look is charged by the objects it
/// looks at: a loop of commands on a large layer ends at the limit on data passed to commands.
#[test]
fn looking_for_changed_points_after_each_command_is_charged() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let mut last = NodeId(0);
for i in 0..2000 {
last = rect(&mut s, f64::from(i % 40) * 10.0, f64::from(i / 40) * 5.0, 4.0, 4.0);
}
s.execute("select.none", &json!({})).unwrap();
let source = format!(
"vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor.length);\
for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});",
last.0
);
let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["log"], json!([2]));
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let e = run(&mut s, &source).map(|r| r.to_string());
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = e.map(|r| panic!("100 commands, each followed by a look at 2,000 objects, ran: {r}")).unwrap_err();
assert!(e.to_string().ends_with("(limit)"), "{e}");
// Once the path whose points the run read is gone, later commands look for nothing.
let source = format!(
"var p = app.activeDocument.pathItems[1]; vc.log(p.pathPoints[0].anchor.length); p.remove();\
for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});",
last.0
);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let r = run(&mut s, &source);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2]));
}
#[test]
fn point_edits_are_written_before_the_next_other_member_reads() {
let (mut s, a, _) = doc();
@@ -506,6 +506,57 @@ fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() {
let base = folder("retrace-legacy-paths");
let (mut s, image) = session(&base, false);
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap();
trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE);
let held = members(&s, group);
// The script reaches the tracing's paths before the tracing itself.
let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\
r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);";
let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0)));
assert_eq!(out, [json!(ADDED_ARTWORK)]);
assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() {
let base = folder("retrace-legacy-revert");
let path = base.join("main/legacy.vectorcraft");
for seen_first in [false, true] {
for added in [false, true] {
let (mut s, image) = session(&base, false);
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap();
trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE);
s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
let held = members(&s, group);
s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap();
let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" };
let add = if added {
format!(
"var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\
r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';",
json!(path.to_string_lossy())
)
} else {
String::new()
};
let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0)));
// A revert keeps the snapshot taken before it.
let message = if added || seen_first { ADDED_ARTWORK } else { "" };
assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}");
}
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn engine_trace_can_be_retraced_by_a_script() {
let base = folder("retrace-engine-artwork");
@@ -1367,6 +1418,22 @@ fn unimplemented_tracing_members_are_not_reported() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn new_group_at_the_bottom_of_a_tracing_is_refused() {
let base = folder("new-group-bottom");
let (mut s, id) = session(&base, false);
let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap());
let steps = undo_steps(&s);
let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string();
assert!(e.contains("source image"), "{e}");
assert_eq!(traces(&s), [tid]);
assert_eq!(undo_steps(&s), steps);
let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap());
assert_eq!(traces(&s), [tid]);
assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn retrace_keeps_the_tracing_opacity_and_blend_mode() {
let base = folder("retrace-appearance");
@@ -130,6 +130,69 @@ fn resize_scales_about_the_center_and_line_widths_follow_their_argument() {
assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}");
}
#[test]
fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() {
let (mut s, _, _) = doc();
log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;");
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] {
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};"));
assert!(e.contains("more than 1000 points"), "{call}: {e}");
}
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
// A scale that keeps the weight within the limit still scales it.
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);");
assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}");
// The lower stroke must stay within the limit too.
let (mut s, a, _) = doc();
s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap();
s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap();
log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;");
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);");
assert!(e.contains("more than 1000 points"), "{e}");
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
// A nonfinite scale must not turn a zero-width stroke into NaN.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;");
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);");
assert!(e.contains("more than 1000 points"), "{e}");
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
}
#[test]
fn an_empty_path_takes_any_transformation_about_any_point() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
log(&mut s, "app.activeDocument.pathItems.add();");
let out = log(
&mut s,
"var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\
n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\
n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\
vc.log(n.pathPoints.length);",
);
assert_eq!(out, vec![json!(0)]);
// Its stroke weight still scales with the transformation.
let out = log(
&mut s,
"var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);",
);
assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}");
let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');");
assert!(e.contains("Transformation value"), "{e}");
}
#[test]
fn transform_applies_a_matrix_record_about_the_center() {
let (mut s, _, _) = doc();
+38 -3
View File
@@ -678,9 +678,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\
try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\
o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\
o.unitScaleRatio = 100; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\
o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\
var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\
d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});"
@@ -694,7 +694,8 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it");
assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format");
assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each");
assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b));
// The DXF writes six decimals.
assert!((dxf_widest(&a) - dxf_widest(&b) * 10.0).abs() < 1e-4, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b));
for name in ["c.dxf", "u.dxf"] {
let dxf = std::fs::read_to_string(dir.join(name)).unwrap();
assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24");
@@ -706,6 +707,34 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
let _ = std::fs::remove_dir_all(base);
}
/// `unitScaleRatio` is a percentage: 100 writes the drawing at the size an option left out gives,
/// and 200 writes it twice as wide.
#[test]
fn an_autocad_unit_scale_ratio_is_a_percentage() {
let base = folder("autocad-ratio");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let d = quoted(&dir);
logged(
&mut s,
&base,
&format!(
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF;\n\
d.exportFile(new File(dir + '/n'), ExportType.AutoCAD, o);\n\
o.unitScaleRatio = 100; d.exportFile(new File(dir + '/h'), ExportType.AutoCAD, o);\n\
o.unitScaleRatio = 200; d.exportFile(new File(dir + '/t'), ExportType.AutoCAD, o);\n\
vc.log(1);"
),
);
let width = |name: &str| dxf_widest(&std::fs::read_to_string(dir.join(name)).unwrap());
let (n, h, t) = (width("n.dxf"), width("h.dxf"), width("t.dxf"));
assert!((h - n).abs() < 1e-6, "100 is full size: {h} and {n}");
assert!((t - 2.0 * n).abs() < 1e-5, "200 is twice the size: {t} and {n}");
let _ = std::fs::remove_dir_all(base);
}
/// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and
/// an option the script changes applies over the preset.
#[test]
@@ -1171,6 +1200,12 @@ fn bad_arguments_are_refused_with_an_error() {
),
"at most 1000",
),
(
format!(
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 0.00001; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
),
"ExportOptionsAutoCAD.unitScaleRatio must be at least 0.0001",
),
(
format!(
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
@@ -497,3 +497,60 @@ impl Writer<'_> {
s.push_str("/End X!\n");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A closed outline through `points`, each side a straight segment.
fn outline(points: &[(f64, f64)]) -> PathData {
let mut bp = kurbo::BezPath::new();
for (i, &(x, y)) in points.iter().enumerate() {
if i == 0 {
bp.move_to((x, y));
} else {
bp.line_to((x, y));
}
}
bp.close_path();
PathData::from_bezpath(&bp)
}
fn assert_near(got: Option<Point>, want: (f64, f64)) {
let Some(got) = got else { panic!("no grid point") };
assert!(got.distance(Point::new(want.0, want.1)) < 1e-9, "{got:?} is not {want:?}");
}
/// A top object with two segments on each side is written as a 2 × 2 grid whose middle point
/// blends the four sides' middles less the four corners.
#[test]
fn a_top_object_with_two_segments_a_side_gets_its_middle_point_from_the_sides() {
let path = outline(&[(30.0, 10.0), (100.0, 0.0), (170.0, 10.0), (180.0, 50.0), (170.0, 90.0), (100.0, 90.0), (30.0, 90.0), (30.0, 50.0)]);
let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 2, 4, 6])) else { panic!("the outline is written as a grid") };
assert_eq!((rows, cols), (2, 2));
// (100, 0) and (100, 90) halved, (30, 50) and (180, 50) halved, less the corners' mean.
assert_near(pts.get(4).map(|q| q.0), (105.0, 45.0));
}
/// Three segments across and two down: each middle point is weighted by its column across and
/// its row down, not the other way around.
#[test]
fn a_top_object_wider_than_it_is_tall_blends_by_column_across_and_row_down() {
let path = outline(&[
(0.0, 0.0),
(40.0, -6.0),
(80.0, 4.0),
(120.0, 0.0),
(126.0, 40.0),
(120.0, 80.0),
(80.0, 86.0),
(40.0, 84.0),
(0.0, 80.0),
(-4.0, 40.0),
]);
let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 3, 5, 8])) else { panic!("the outline is written as a grid") };
assert_eq!((rows, cols), (2, 3));
assert_near(pts.get(5).map(|q| q.0), (39.0 + 1.0 / 3.0, 39.0));
assert_near(pts.get(6).map(|q| q.0), (82.0 + 2.0 / 3.0, 45.0));
}
}
+11
View File
@@ -785,6 +785,17 @@ mod tests {
}
}
/// A row of patches with as many columns as a mesh keeps is stitched into one mesh; one more
/// column is not.
#[test]
fn a_mesh_with_more_lines_than_are_kept_is_not_stitched() {
for (n, kept) in [(MAX_LINES, true), (MAX_LINES + 1, false)] {
let r = Grid::new(n, 1).read([n as f64, 1.0]);
let at: Vec<(usize, usize)> = (0..n).map(|i| (0, i)).collect();
assert_eq!(stitch(&r.cells, &at, 1, n).is_some(), kept, "{n} columns");
}
}
/// A 2 × 2 mesh comes in as one mesh of 9 shared points, each where the patches put it, with
/// the colours the separate patches had at every place.
#[test]
+37
View File
@@ -2799,6 +2799,43 @@ fn ai_variable_library_without_the_layers() {
assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default());
}
/// A library whose `variableSets` node writes its children and attributes before its name is
/// still found on its own when reading stops before it.
#[test]
fn a_variable_library_named_after_its_children_is_read_when_reading_stops_early() {
use vectorcraft_doc::DataValue;
use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_text};
let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)));
let value = xml_element("Team", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode("Home Team"))])]);
let set = xml_element(
"variableSet",
&[("locked", "none"), ("varSetName", "binding1")],
&[
xml_element("variables", &[], &[xml_element("variable", &[("trait", "textcontent"), ("varName", "Team")], &[])]),
xml_element(
"v:sampleDataSets",
&[("xmlns", "&ns_custom;"), ("xmlns:v", "&ns_vars;")],
&[xml_element("v:sampleDataSet", &[("dataSetName", "Home")], &[value])],
),
],
);
let named_first = xml_element("variableSets", &[("xmlns", "&ns_vars;")], &[set]);
// Move the name line from the top of the node to just before the line that closes it.
let name = "%_(variableSets) /String (xmlnode-nodename) ,\n";
let body = named_first.strip_prefix(&format!("%_/XMLNode :\n{name}")).and_then(|b| b.strip_suffix("%_;\n")).unwrap_or_default();
assert!(!body.is_empty(), "{named_first}");
let named_last = format!("%_/XMLNode :\n{body}{name}%_;\n");
let early = stream(&format!("LB\n{}{square}", variable_library_data(&named_last)));
assert!(read(early.as_bytes()).is_err());
let found = variables(early.as_bytes(), &mut Names::default());
assert!(found.present);
let names: Vec<&str> = found.variables.variables.iter().map(|v| v.name.as_str()).collect();
assert_eq!(names, ["Team"]);
assert_eq!(found.variables.datasets.len(), 1);
assert_eq!(found.variables.datasets[0].name, "Home");
assert_eq!(found.variables.datasets[0].values.get("Team"), Some(&DataValue::Text("Home Team".into())));
}
#[test]
fn a_drawn_look_stands_for_its_object() {
// The look (a group, with a part on `%_` lines for newer readers), then the object on `%_`
+6
View File
@@ -2361,6 +2361,12 @@ mod tests {
}
let deep = format!("/0 {}", "[".repeat(200));
assert!(read(deep.as_bytes()).is_none());
// Balanced nesting: 65 levels are read, and a 66th ends the parse.
let nest = |open: &str, close: &str, n: usize| format!("/0 {}1{}", open.repeat(n), close.repeat(n));
for (open, close) in [("<< /0 ", " >>"), ("[ ", " ]")] {
assert!(read(nest(open, close, MAX_DEPTH + 1).as_bytes()).is_some(), "{open}nested {} levels", MAX_DEPTH + 1);
assert!(read(nest(open, close, MAX_DEPTH + 2).as_bytes()).is_none(), "{open}nested {} levels", MAX_DEPTH + 2);
}
}
/// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the
+33
View File
@@ -1061,6 +1061,20 @@ fn clipsave_and_cliprestore_bring_the_clip_back() {
assert!(matches!(o[0].kind, NodeKind::Path { .. }), "{:?}", o[0].kind);
}
/// `clipsave` and `gsave` each keep up to 1,000 saved states. One more is a limit error: the
/// square drawn before it stays, and the one after it is left out.
#[test]
fn clipsave_and_gsave_stop_at_a_thousand_saved_states() {
for (op, why) in [("clipsave", "too many saved clips"), ("gsave", "too many saved graphics states")] {
let r = read(&format!("0 0 10 10 rectfill 1000 {{ {op} }} repeat 20 20 10 10 rectfill"));
assert_eq!(objects(&r.document).len(), 2, "{op}: {:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains(why)), "{op}: {:?}", r.warnings);
let r = read(&format!("0 0 10 10 rectfill 1001 {{ {op} }} repeat 20 20 10 10 rectfill"));
assert_eq!(objects(&r.document).len(), 1, "{op}: {:?}", r.warnings);
assert!(r.warnings.first().is_some_and(|w| w.contains(why)), "{op}: {:?}", r.warnings);
}
}
#[test]
fn languagelevel_is_an_integer_and_runs() {
// #234.
@@ -1099,6 +1113,25 @@ fn intervals_share_their_arrays_and_strings() {
);
}
/// `cvs` writes the text of each kind of object (PLRM 3rd ed., `cvs`): a real keeps a decimal
/// point, booleans, names and operators their names, other objects `--nostringval--`. `cvrs`
/// writes a number in a radix from 2 to 36 with uppercase digits, a negative one as its 32-bit
/// two's complement, and refuses any other radix.
#[test]
fn cvs_and_cvrs_write_the_text_of_each_kind() {
check("/s 16 string def 3.0 s cvs (3.0) eq");
check("/s 16 string def 2.5 s cvs (2.5) eq");
check("/s 16 string def true s cvs (true) eq");
check("/s 16 string def /abc s cvs (abc) eq");
check("/s 16 string def /add load s cvs (add) eq");
check("/s 16 string def [1] s cvs (--nostringval--) eq");
check("/s 16 string def 255 16 s cvrs (FF) eq");
check("/s 16 string def 10 2 s cvrs (1010) eq");
check("/s 16 string def 0 2 s cvrs (0) eq");
check("/s 16 string def -1 16 s cvrs (FFFFFFFF) eq");
check("/s 16 string def { 10 1 s cvrs } stopped { 10 37 s cvrs } stopped and");
}
#[test]
fn resourceforall_enumerates_matching_names() {
// #234.
+16
View File
@@ -861,6 +861,11 @@ fn probing_operators_answer() {
"/n 0 def 0 0 moveto 10 0 lineto { pop pop /n n 1 add def } { pop pop /n n 2 add def } { 6 { pop } repeat } {} pathforall n 3 eq",
);
super::tests::check("1 0 0 setrgbcolor currenthsbcolor 1 eq exch 1 eq and exch 0 eq and");
// Green largest: hue (2 + (b - r) / d) / 6 = 5/12; blue largest: (4 + (r - g) / d) / 6 = 9/12;
// each with saturation 0.8 and brightness 1. Gray has no hue and no saturation.
super::tests::check("0.2 1 0.6 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 5 sub abs 1e-5 lt and");
super::tests::check("0.6 0.2 1 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 9 sub abs 1e-5 lt and");
super::tests::check("0.5 setgray currenthsbcolor 0.5 sub abs 1e-6 lt exch 0 eq and exch 0 eq and");
super::tests::check("currentcacheparams counttomark 2 eq exch pop exch pop exch pop");
super::tests::check("cachestatus 7 { pop } repeat true");
super::tests::check("currentcolorrendering /ColorRenderingType known");
@@ -997,6 +1002,17 @@ fn hostile_patterns_glyphs_and_shadings_end() {
/Function << /FunctionType 0 /Domain [0 1] /Range [0 1] /Size [99999999] /BitsPerSample 8 /DataSource () >> >> shfill",
);
assert!(r.warnings[0].contains("rangecheck in `shfill`: a sampled function"), "{:?}", r.warnings);
// A sampled function of two inputs may hold 2^24 samples (4096 × 4096), and no more.
let sized = |size: &str| {
read(&format!(
"0 0 1 1 rectfill << /ShadingType 1 /ColorSpace /DeviceGray \
/Function << /FunctionType 0 /Domain [0 1 0 1] /Range [0 1] /Size [{size}] /BitsPerSample 8 /DataSource () >> >> shfill"
))
};
let r = sized("4096 4096");
assert!(!r.warnings.iter().any(|w| w.contains("error")), "{:?}", r.warnings);
let r = sized("4096 4097");
assert!(r.warnings[0].contains("limitcheck in `shfill`: Size"), "{:?}", r.warnings);
// Procedures nesting through operators that run them end at the nesting limit.
for body in ["/f { { f } exec } def f", "/f { true { f } if } def f", "/f { 1 { f } repeat } def f", "/f { { f } stopped } def f"] {
assert!(import(&super::tests::eps(body)).is_err(), "{body}");
+47 -1
View File
@@ -148,6 +148,35 @@ fn filters_read_the_file_they_were_made_over() {
);
}
/// LZW data (`LZWDecode`, `EarlyChange` 1, PDF 32000 §7.4.4.2) decodes: the specification's
/// example, whose third code is the entry that code adds; data long enough that the table grows
/// past 511, 1023 and 2047 entries (9-, 10-, 11- and 12-bit codes) and is cleared and grown again;
/// and a code past the end of the table is an `ioerror`, the art after it left out.
#[test]
fn lzw_data_decodes_at_every_code_width() {
super::tests::check("<800B6050220C0C8501> /LZWDecode filter 20 string readstring pop (-----A---B) eq");
let mut x = 0x2545_F491_u32;
let data: Vec<u8> = (0..12_000)
.map(|_| {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
(x >> 24) as u8
})
.collect();
let lzw = craft_stream_codecs::lzw::encode(&data, true);
super::tests::check(&format!(
"/f <{}> /LZWDecode filter def f {} string readstring exch <{}> eq and f read {{ pop false }} {{ true }} ifelse and",
hex(&lzw),
data.len(),
hex(&data)
));
// A clear-table code, then code 300 while the table ends at 257.
let r = read("0 0 10 10 rectfill <804B00> /LZWDecode filter 4 string readstring 20 20 10 10 rectfill");
assert_eq!(super::tests::objects(&r.document).len(), 1, "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("ioerror") && w.contains("LZWDecode")), "{:?}", r.warnings);
}
/// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from
/// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through
/// the Decode array. Gray and RGB images stay PNGs.
@@ -656,7 +685,8 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() {
/// An image too large to read even at a lower resolution (its samples are more data than the
/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure
/// is called until the data ends; when its first filter decompresses to more than the reader
/// holds (and can't be read a row at a time), the compressed data is measured without keeping it.
/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is
/// measured without keeping it.
#[test]
fn the_data_of_an_image_too_large_to_hold_is_skipped() {
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
@@ -666,6 +696,20 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
flate.extend(&zeros);
flate.extend(format!("\n{after}").as_bytes());
// The same through LZW, which counts the codes up to its end-of-data code.
let mut lzw =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec();
lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true));
lzw.extend(format!("\n{after}").as_bytes());
// Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of
// 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in
// 200 and every run repeats 200, so a count that lands on a wrong byte reads each 200 as a
// run's length and stays off by one.
let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec();
run_length.extend([2, 200, 200, 200]);
run_length.extend([129u8, 200].repeat((300 << 20) / 128));
run_length.push(128);
run_length.extend(format!("\n{after}").as_bytes());
for program in [
format!(
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
@@ -673,6 +717,8 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
)
.into_bytes(),
flate,
lzw,
run_length,
] {
let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned();
let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
+15
View File
@@ -722,6 +722,21 @@ fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_place
assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image");
}
/// A distorted image on a layer, which the format has no form for, is written as the pieces it is
/// drawn as, with a warning.
#[test]
fn a_distorted_image_on_a_layer_is_written_as_its_pieces() {
let mut doc = Document::new(200.0, 100.0);
let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0));
art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap();
doc.insert(doc.default_layer(), usize::MAX, art).unwrap();
let out = write(&doc);
assert!(out.warnings.iter().any(|w| w == LIVE), "{:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings);
let text = String::from_utf8(out.bytes).unwrap();
assert!(text.lines().filter(|l| l.ends_with(" XI")).count() > 1, "the pieces, not one image");
}
/// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group
/// holding an image and an image; a layer `Above` holding an orange square. Without `images`,
/// `Below` is empty.
+55
View File
@@ -426,6 +426,61 @@ fn strokes_keep_their_caps_joins_and_dashes() {
assert!(page.contains("0 0 0 rg\n20 20 m\n80 20 l\n80 80 l\n20 80 l\n20 20 l\nh\nS\n"), "{page}");
}
/// The page for a square stroked 4 pt with `paint`, aligned `align`.
fn aligned_stroke_page(align: vectorcraft_doc::StrokeAlign, paint: impl FnOnce(&mut Document) -> Paint) -> String {
let d = doc_with(|d| {
let paint = paint(d);
let mut n = path(d, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, paint, 4.0);
for i in &mut n.appearance.items {
if let AppearanceItem::Stroke(s) = i {
s.align = align;
}
}
vec![n]
});
page_of(&d, &opts(&d))
}
/// Where the first line of `page` that `matches` is.
fn line_at(page: &str, matches: impl Fn(&str) -> bool) -> Option<usize> {
page.lines().position(matches)
}
/// A stroke inside or outside a closed path is drawn at twice its width, clipped first: inside to
/// the path, outside to everything but the path (even-odd), so only its own half shows.
#[test]
fn inside_and_outside_strokes_are_clipped_to_their_side_and_drawn_twice_as_wide() {
use vectorcraft_doc::StrokeAlign;
let black = |_: &mut Document| Paint::solid(Color::BLACK);
for (align, clip) in [(StrokeAlign::Inside, "W"), (StrokeAlign::Outside, "W*")] {
let page = aligned_stroke_page(align, black);
let clip_at = line_at(&page, |l| l == clip);
let width_at = line_at(&page, |l| l.starts_with("8 w "));
let stroke_at = line_at(&page, |l| l == "S");
assert!(clip_at.is_some() && clip_at < width_at && width_at < stroke_at, "{align:?}: {page}");
let other = if clip == "W" { "W*" } else { "W" };
assert_eq!(line_at(&page, |l| l == other), None, "{align:?}: {page}");
}
// Centered: the width as set, with no clip.
let page = aligned_stroke_page(StrokeAlign::Center, black);
assert!(line_at(&page, |l| l.starts_with("4 w ")).is_some(), "{page}");
assert_eq!(line_at(&page, |l| l == "W" || l == "W*"), None, "{page}");
}
/// A stroke painted with a pattern is written as the area it covers, filled with the pattern's
/// tiles, not as a stroke.
#[test]
fn a_pattern_stroke_is_written_as_its_filled_outline() {
let pattern = |d: &mut Document| {
let square = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(square)]));
Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY }
};
let page = aligned_stroke_page(vectorcraft_doc::StrokeAlign::Center, pattern);
assert!(page.contains("0 0 1 rg"), "the tile is painted: {page}");
assert_eq!(line_at(&page, |l| l == "S" || l.contains("strokepath") || l.contains(" w ")), None, "{page}");
}
#[test]
fn transparency_is_written_opaque_with_a_warning() {
let d = doc_with(|d| {
+150
View File
@@ -1449,6 +1449,156 @@ mod tests {
let _ = std::fs::remove_dir_all(d);
}
/// A checked write whose fill fails puts nothing in place: the error is returned, the file
/// keeps its old content, and the temporary file is removed.
#[cfg(unix)]
#[test]
fn a_checked_write_keeps_the_original_when_its_fill_fails() {
let (d, root, _) = checked_folders("checked-fill-fails");
let folder = root.join("inside");
std::fs::write(folder.join("doc.txt"), b"original").unwrap();
let r = write_atomic_checked(
&folder.join("doc.txt"),
|f| {
f.write_all(b"half a fi")?;
Err(io::Error::other("disk full"))
},
under(&root),
);
assert_eq!(r.map_err(|e| e.to_string()), Err("disk full".to_string()));
assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original");
assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt"));
let _ = std::fs::remove_dir_all(d);
}
/// A checked write canceled while it fills puts nothing in place: the error is the
/// cancellation, the file keeps its old content, and the temporary file is removed.
#[cfg(unix)]
#[test]
fn a_checked_write_canceled_while_it_fills_keeps_the_original() {
use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope};
let (d, root, _) = checked_folders("checked-cancel");
let folder = root.join("inside");
std::fs::write(folder.join("doc.txt"), b"original").unwrap();
let token = CancelToken::new();
let r = scope(&token, None, || {
write_atomic_checked(
&folder.join("doc.txt"),
|f| {
f.write_all(b"new")?;
token.cancel();
Ok(())
},
under(&root),
)
});
assert!(r.as_ref().is_err_and(|e| e.get_ref().is_some_and(|e| e.is::<Cancelled>())), "{r:?}");
assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original");
assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt"));
let _ = std::fs::remove_dir_all(d);
}
/// Makes `folder` refuse new files (mode 0o555). `false`, with the folder writable again, when
/// a new file can still be created there (root ignores the mode).
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
fn refuse_new_files(folder: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o555)).unwrap();
let probe = folder.join("probe");
if std::fs::write(&probe, b"").is_ok() {
let _ = std::fs::remove_file(&probe);
std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o755)).unwrap();
return false;
}
true
}
/// Files in the system's temporary folder whose names start with the temporary names a write
/// to a file named `name` uses.
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
fn system_temp_files(name: &str) -> Vec<String> {
let prefix = format!(".{name}.{}-", std::process::id());
std::fs::read_dir(std::env::temp_dir())
.unwrap()
.filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string()))
.filter(|n| n.starts_with(&prefix))
.collect()
}
/// A checked write over a file whose folder refuses the rename and then any new file: the copy
/// of the file as it was goes to the system's temporary folder, the new content is copied into
/// the file, and that copy is removed afterwards. (Skipped for root.)
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn a_checked_write_keeps_the_old_copy_outside_a_folder_that_takes_no_new_file() {
use std::os::unix::fs::PermissionsExt;
let name = "checked-old-elsewhere.txt";
let (d, root, _) = checked_folders("checked-old-elsewhere");
let folder = root.join("inside");
std::fs::write(folder.join(name), b"original, and longer").unwrap();
let refused = std::cell::Cell::new(true);
let r = write_atomic_checked(
&folder.join(name),
|f| {
f.write_all(b"new")?;
RENAME_REFUSED.with(|c| c.set(true));
refused.set(refuse_new_files(&folder));
Ok(())
},
under(&root),
);
RENAME_REFUSED.with(|c| c.set(false));
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
if !refused.get() {
let _ = std::fs::remove_dir_all(d);
eprintln!("skipped: the folder takes new files whatever its mode (running as root)");
return;
}
r.unwrap();
assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new");
assert!(!leftovers(&folder, name).iter().any(|n| n.ends_with(".old")), "{:?}", leftovers(&folder, name));
assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name));
let _ = std::fs::remove_dir_all(d);
}
/// A folder that refuses the temporary file of a checked write but lets the file itself be
/// written: the content is written in the system's temporary folder and copied in, and nothing
/// is left behind. A failed fill there leaves the file as it was. (Skipped for root.)
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn a_checked_write_saves_through_the_system_folder_when_its_folder_takes_no_temporary_file() {
use std::os::unix::fs::PermissionsExt;
let name = "checked-no-temp.txt";
let (d, root, _) = checked_folders("checked-no-temp");
let folder = root.join("inside");
std::fs::write(folder.join(name), b"original, and longer").unwrap();
if !refuse_new_files(&folder) {
let _ = std::fs::remove_dir_all(d);
eprintln!("skipped: the folder takes new files whatever its mode (running as root)");
return;
}
let saved = write_atomic_checked(&folder.join(name), |f| f.write_all(b"new"), under(&root));
let saved_content = std::fs::read(folder.join(name)).unwrap();
let saved_temp = system_temp_files(name);
let failed = write_atomic_checked(
&folder.join(name),
|f| {
f.write_all(b"half a fi")?;
Err(io::Error::other("disk full"))
},
under(&root),
);
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
saved.unwrap();
assert_eq!(saved_content, b"new");
assert!(saved_temp.is_empty(), "{saved_temp:?}");
assert_eq!(failed.map_err(|e| e.to_string()), Err("disk full".to_string()));
assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new");
assert!(leftovers(&folder, name).is_empty(), "{:?}", leftovers(&folder, name));
assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name));
let _ = std::fs::remove_dir_all(d);
}
/// The other files in `d` besides `keep`.
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
+30
View File
@@ -374,6 +374,36 @@ mod tests {
assert!(matches!(Unpacked::within(&gz, json.len() as u64 - 1), Err(FormatError::TooBig)));
}
/// A compressed file with data after its JSON is refused past its budget on both paths: the
/// JSON before the marker where the writer puts it, and the whole file when the marker is
/// elsewhere and the file is unpacked whole.
#[test]
fn a_compressed_file_with_data_is_capped_on_both_paths() {
let with_data = |json: &[u8]| {
let mut file = json.to_vec();
file.extend(crate::BLOB_MAGIC);
file.extend([1u8; 64]);
file
};
let mut json = br#"{"pad":""#.to_vec();
json.extend(std::iter::repeat_n(b'x', 4096));
json.extend(br#""}"#);
let streamed = gzip(&with_data(&json));
let max_json = json.len() as u64;
let opened = Unpacked::within(&streamed, max_json).unwrap();
assert!(matches!(opened.tail, Tail::Stream { .. }), "read as a stream");
assert_eq!(opened.json(), json.as_slice());
assert!(matches!(Unpacked::within(&streamed, max_json - 1), Err(FormatError::TooBig)));
// No `}` before the marker: unpacked whole, within the whole-file cap and not one byte past it.
let plain = with_data(b"1");
let whole = gzip(&plain);
let max_whole = plain.len() as u64;
let opened = Unpacked::within_capped(&whole, 64, max_whole, MAX_BLOBS).unwrap();
assert!(matches!(opened.tail, Tail::Whole(_)), "unpacked whole");
assert_eq!(opened.json(), b"1");
assert!(matches!(Unpacked::within_capped(&whole, 64, max_whole - 1, MAX_BLOBS), Err(FormatError::TooBig)));
}
#[test]
fn entries_sharing_bytes_obey_the_limits_in_memory_too() {
// Each entry within MAX_BLOB, together past MAX_BLOBS: many references to the same bytes.
+23
View File
@@ -892,4 +892,27 @@ mod tests {
moved.remove(0);
assert_eq!(before.pairs_not_shared(&moved).count(), 10_000);
}
/// The table bytes are what the chunk table and the running totals have reserved, which is at
/// least what they hold. A short list has no running totals; a list split unevenly by an insert
/// has both, and spare capacity in either table counts.
#[test]
fn table_bytes_count_the_chunk_table_and_the_running_totals() {
let (chunk, total) = (size_of::<Arc<Vec<Anchor>>>(), size_of::<usize>());
let reserved = |a: &Anchors| {
let held = a.chunks.len() * chunk + a.ends.len() * total;
let reserved = a.chunks.capacity() * chunk + a.ends.capacity() * total;
assert!(held <= reserved);
a.table_bytes() == reserved
};
let short = Anchors::from(line(5));
assert!(short.ends.is_empty() && reserved(&short), "{}", short.table_bytes());
let mut uneven = Anchors::from(line(CHUNK));
uneven.insert(10, Anchor::corner(Point::ZERO));
assert!(uneven.chunks.len() == 2 && uneven.ends.len() == 2, "{:?}", uneven.ends);
uneven.chunks.reserve(8);
uneven.ends.reserve(8);
assert!(uneven.chunks.capacity() > uneven.chunks.len() && uneven.ends.capacity() > uneven.ends.len());
assert!(reserved(&uneven), "{}", uneven.table_bytes());
}
}
+11
View File
@@ -106,4 +106,15 @@ mod tests {
assert_eq!(tangent(&c[0], 1.0), Vec2::new(0.0, 1.0));
assert_eq!(unit(Vec2::ZERO), Vec2::new(1.0, 0.0));
}
/// A quadratic whose three points coincide has no length; one whose middle point lies off its
/// coinciding ends has length.
#[test]
fn a_quad_has_length_unless_its_points_coincide() {
use kurbo::{Point, QuadBez};
let (p, q) = (Point::new(3.0, 4.0), Point::new(9.0, -2.0));
assert!(!has_length(&PathSeg::Quad(QuadBez::new(p, p, p))));
assert!(has_length(&PathSeg::Quad(QuadBez::new(p, q, p))));
assert!(has_length(&PathSeg::Quad(QuadBez::new(p, p, q))));
}
}
+27
View File
@@ -316,6 +316,33 @@ mod tests {
assert!(curvature_circle(s, 0.25, false).is_ok());
}
/// A segment that bends by a billionth of a point over 300 points is straight: the limit grows
/// with the segment's speed, so a fast segment needs a larger bend to count as curved. A bend
/// a million times larger is curved.
#[test]
fn a_fast_segment_that_barely_bends_is_straight() {
let nearly = |dy: f64| CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, dy), Point::new(200.0, 0.0), Point::new(300.0, 0.0));
assert_eq!(curvature_circle_with(nearly(1e-9), 0.5, false, false), Err(NoCircle::Straight));
assert_eq!(osculating(nearly(1e-9), 0.5), Err(NoCircle::Straight));
assert!(curvature_circle_with(nearly(1e-3), 0.5, false, false).is_ok());
}
/// The ends of a 60° cubic at radii 100 and 105 from where their normals cross are not the
/// cubic of a circular arc, even with handles of the right length for the mean radius; the
/// same cubic with both ends at radius 100 is one.
#[test]
fn ends_at_different_radii_are_not_a_circular_arc() {
let turn = 60f64.to_radians();
let arc = |r3: f64, mean: f64| {
let handle = 4.0 / 3.0 * (turn / 4.0).tan() * mean;
let (p0, p3) = (Point::new(100.0, 0.0), Point::new(r3 * turn.cos(), r3 * turn.sin()));
CubicBez::new(p0, p0 + Vec2::new(0.0, handle), p3 - Vec2::new(-turn.sin(), turn.cos()) * handle, p3)
};
assert_eq!(circular_arc(arc(105.0, 102.5)), None);
let (center, radius) = circular_arc(arc(100.0, 100.0)).unwrap();
assert!(center.distance(Point::ORIGIN) < 1e-9 && (radius - 100.0).abs() < 1e-9, "{center:?} {radius}");
}
/// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points
/// that are not finite and a `t` outside 0 to 1 have no curvature circle.
#[test]
+17
View File
@@ -194,6 +194,23 @@ fn async_function_prototype_has_its_to_string_tag() {
assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]");
}
#[test]
fn a_class_extends_async_function_and_its_instances_inherit_from_the_class() {
// CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2017 section
// 19.2.1.1.1).
let src = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\
class X extends AF { tag() { return 'x'; } }\n\
var f = new X('a', 'return a + 1');\n\
log.push(Object.getPrototypeOf(f) === X.prototype, f instanceof AF, f.tag(), Object.prototype.toString.call(f));\n\
f(1).then(function (v) { log.push(v); });";
assert_eq!(log(src), "true true x [object AsyncFunction] 2");
// The source is parsed before `new.target.prototype` is read.
let order = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\
var NT = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') log.push('read'); return t[k]; } });\n\
try { Reflect.construct(AF, ['(('], NT); } catch (e) { log.push(e instanceof SyntaxError); }";
assert_eq!(log(order), "true");
}
#[test]
fn an_await_stays_within_the_heap_limit() {
// The activation, its two reactions, the derived promise and the suspended frame's bytes all
+13 -5
View File
@@ -172,7 +172,15 @@ impl Interp {
let i = &self.intrinsics;
Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto]
.contains(&p)
|| i.error_protos.contains(&p))
|| i.error_protos.contains(&p)
|| self.dynamic_function_proto(p))
}
/// Is `p` the prototype of the functions that `GeneratorFunction` or `AsyncFunction` makes?
/// Both constructors take a subclass's prototype from `new.target` (ECMA-262 2017 sections
/// 25.2.1.1 and 25.5.1.1, through CreateDynamicFunction in section 19.2.1.1.1).
fn dynamic_function_proto(&self, p: ObjId) -> bool {
self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) || self.promises.async_function_proto == Some(p)
}
/// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14).
@@ -367,13 +375,13 @@ impl Interp {
return Err(self.type_error("the Promise executor is not a function"));
}
// `Number`, `String` and `Date` convert arguments before reading `prototype`
// (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction`
// convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1).
// (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function`, `GeneratorFunction` and
// `AsyncFunction` convert and parse source first (sections 19.2.1.1.1, 25.2.1.1
// and 25.5.1.1).
let converts_first = {
let i = &self.intrinsics;
intrinsic.is_some_and(|p| {
[i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p)
|| self.symbols.objects.is_some_and(|o| p == o.generator_function_proto)
[i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) || self.dynamic_function_proto(p)
})
};
let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto);
+11
View File
@@ -203,6 +203,17 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() {
assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into())));
}
#[test]
fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() {
// A parameter between the eval code and its variable environment has the name, so the block
// function gets no variable (Annex B.3.2.3) and the parameter keeps its value.
truth("function f(a = eval('{ function a() {} }'), b = a) { return typeof b; } f() === 'undefined'");
truth("function f(a = 1, b = eval('{ function a() {} }'), c = a) { return c + typeof a; } f() === '1number'");
truth("function f(a = 2, b = eval('{ function a() {} }')) { return a; } f() === 2");
// A name that no parameter has still gets the variable.
truth("function f(x = eval('{ function a() { return 3; } }'), b = a) { return b(); } f() === 3");
}
#[test]
fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() {
truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0");
+17
View File
@@ -253,6 +253,23 @@ fn bad_generators_are_syntax_errors() {
truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3");
}
#[test]
fn a_class_extends_generator_function_and_function() {
// CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2015 section
// 19.2.1.1.1).
truth(
"var GF = Object.getPrototypeOf(function* () {}).constructor;\n\
class G extends GF { tag() { return 'g'; } }\n\
var g = new G('yield 7');\n\
Object.getPrototypeOf(g) === G.prototype && g instanceof GF && g.tag() === 'g' && g().next().value === 7",
);
truth(
"class F extends Function { tag() { return 'f'; } }\n\
var f = new F('a', 'return a * 2');\n\
Object.getPrototypeOf(f) === F.prototype && f.tag() === 'f' && f(3) === 6",
);
}
#[test]
fn realms_without_es2015_have_no_generators() {
let es5 = Options::default();
+10 -2
View File
@@ -4813,7 +4813,8 @@ impl Interp {
/// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and
/// B.3.3.3, <https://tc39.es/ecma262/#sec-web-compat-globaldeclarationinstantiation>): no
/// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch`
/// parameter does not count, and on the global object the name is its own property or the
/// parameter does not count, no parameter has the name when the code is in a default
/// parameter's value (B.3.2.3), and on the global object the name is its own property or the
/// object is extensible. Each environment passed takes a unit of fuel.
fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult<bool> {
let mut cur = Some(env).filter(|&e| e != var_env);
@@ -4832,7 +4833,14 @@ impl Interp {
.filter(|&o| o != var_env);
}
if var_env != self.global_env {
return Ok(true);
// Eval code in a default parameter's value declares into the parameters' environment,
// where the parameters are lexical bindings.
self.use_fuel()?;
return match self.heap.env(var_env) {
Some(Env::Decl { bindings, .. }) => Ok(!bindings.get(name).is_some_and(|b| b.lexical)),
Some(Env::Obj { .. }) => Ok(true),
None => internal("environment out of range"),
};
}
let global = self.global;
Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible)
+43 -7
View File
@@ -266,7 +266,10 @@ impl Parser<'_> {
self.bump()?;
return self.export_default(info, span).map(Some);
}
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
let exportable = self.at_keyword(Keyword::Var)
|| self.at_keyword(Keyword::Function)
|| self.at_async_function()
|| self.at_lexical_declaration().is_some();
if !exportable {
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
}
@@ -287,7 +290,7 @@ impl Parser<'_> {
if self.at_keyword(Keyword::Class) {
return Err(self.error_at_token(&self.tok, "classes are not supported"));
}
if self.at_keyword(Keyword::Function) {
if self.at_keyword(Keyword::Function) || self.at_async_function() {
self.enter()?;
let result = self.default_function();
self.leave();
@@ -305,19 +308,22 @@ impl Parser<'_> {
Ok(stmt)
}
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
/// `function name(…) {…}` or `function (…) {…}` after `export default`, either one optionally
/// `async`: a declaration of `name`, or of [`DEFAULT_BINDING`] for a function without one.
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
let is_async = self.at_async();
let async_start = if is_async { Some(self.bump()?.span) } else { None };
let keyword = self.expect_keyword(Keyword::Function)?;
let start = keyword.span;
let generator = self.es2015 && self.eat(Punct::Star)?;
let start = async_start.unwrap_or(keyword.span);
// Async generators (ECMAScript 2018) stay syntax errors, as in a plain declaration.
let generator = !is_async && self.es2015 && self.eat(Punct::Star)?;
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
self.function_name()?
} else {
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
};
let local = name.0.name.clone();
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?;
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?;
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
Ok((stmt, fid, local))
}
@@ -410,6 +416,36 @@ mod tests {
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into())));
}
#[test]
fn async_function_declarations_are_exported() {
let options = Options { es2015: true, es2017: true, ..Options::default() };
let cases = [
("export async function f() {}", "f", "f"),
("export default async function f() {}", "default", "f"),
("export default async function () {}", "default", crate::ast::DEFAULT_BINDING),
];
for (source, export, binding) in cases {
let (program, info) = match parse_module(source, &options) {
Ok(parsed) => parsed,
Err(error) => panic!("{source}: {error:?}"),
};
assert!(
matches!(info.exports.as_slice(), [crate::ExportEntry::Local { export_name, local, .. }] if export_name == export && local == binding),
"{source}: {:?}",
info.exports
);
let declared = program.body.iter().any(|&stmt| match program.ast.stmt(stmt) {
Some(crate::ast::Stmt::FunctionDecl(fid)) => program.ast.function(*fid).is_some_and(|f| f.is_async),
_ => false,
});
assert!(declared, "{source}: an async function declaration");
}
// A line break after `async` ends the declaration; the export is then an expression.
assert!(parse_module("export async\nfunction f() {}", &options).is_err());
// Without ES2017, `async` is an identifier and cannot start an exported declaration.
assert!(parse_module("export async function f() {}", &Options { es2015: true, ..Options::default() }).is_err());
}
#[test]
fn module_specifiers_reject_legacy_octal_escapes() {
for source in
+1 -1
View File
@@ -1768,7 +1768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.placementOptionsDialog",
"Placement Options…",
"",
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions",
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)",
),
(
"ui.relinkDialog",
+15 -1
View File
@@ -99,12 +99,22 @@ impl crate::Renderer {
// Trim View clips each draw when blending reaches the page and clips one composited
// layer otherwise. Changing modes can change unchanged art at an artboard edge.
if opts.trim && !old.artboards.is_empty() {
// `children_blend` caches the groups it reads in `blends`, which holds their nodes,
// so this counts as a measurement for `finish_measurement_only`.
self.measuring = true;
let before = crate::proof::prepare(old, opts, &mut self.proof_art);
let after = crate::proof::prepare(new, opts, &mut self.proof_art);
if self.children_blend(&before.layers) != self.children_blend(&after.layers) {
return Changed::Everything;
}
}
// A change outside the layers (symbol definitions among them) redraws everything without
// measuring anything here; the caches still age so that bounds kept for the old
// definitions expire.
if new.pattern_edit.is_some() || !old.same_outside_layers(new) {
self.measuring = true;
return Changed::Everything;
}
let renderer = (!crate::proof::overprints(opts)).then_some(self);
changed_with(old, new, renderer, opts)
}
@@ -249,7 +259,11 @@ impl Diff<'_, '_> {
Side::New => new,
};
match renderer {
Some(r) => r.bounds_of(symbols, n),
Some(r) => {
// Only a measurement ages the renderer's caches in `finish_measurement_only`.
r.measuring = true;
r.bounds_of(symbols, n)
}
None => crate::brush_fx::cull_bounds(symbols, n),
}
}
+3
View File
@@ -182,6 +182,9 @@ pub struct Renderer {
/// ([`lru::MEASURED_BUDGET`]).
measured_bytes: usize,
measured_budget: usize,
/// [`Renderer::changed`] measured through this renderer since its last frame began or since
/// [`Renderer::finish_measurement_only`] last aged its caches.
measuring: bool,
/// The export bounds of the objects measured without their hidden members
/// (`encode::drawn_bounds`), by the object they were made from: kept for a pass over artboards,
/// let go when a frame ends.
+7
View File
@@ -76,6 +76,7 @@ impl Renderer {
measured: PtrMap::default(),
measured_bytes: 0,
measured_budget: lru::MEASURED_BUDGET,
measuring: false,
pass_bounds: PtrMap::default(),
three_d_bounds: PtrMap::default(),
three_d_kept: 0,
@@ -244,6 +245,7 @@ impl Renderer {
/// Start a frame: cache entries used from now on are marked with its stamp.
fn begin_frame(&mut self) {
self.stamp += 1;
self.measuring = false;
self.inline_depth = 0;
// Nothing is drawn offscreen yet (even if an earlier frame stopped part way).
(self.offscreen_live, self.offscreen_budget) = (0, 0);
@@ -267,7 +269,12 @@ impl Renderer {
/// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update.
/// Age the measurement caches and keep the previous draw's effect rasters available.
/// Without a [`Self::changed`] since the last frame or the last call, nothing changes:
/// the paths of the last frame stay for this renderer's next frame.
pub fn finish_measurement_only(&mut self) {
if !std::mem::take(&mut self.measuring) {
return;
}
self.stamp += 1;
self.sweep_node_geometry();
let g = self.stamp;
+27
View File
@@ -1730,6 +1730,33 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() {
assert!(!image_cached(&cmyk));
}
/// Pixels [`keep_decoded_image`] refuses (here, pixels past the decode allowance) are not
/// kept anywhere: the first render that draws the image decodes it, as for any image.
#[test]
fn a_refused_decoded_image_is_decoded_when_first_drawn() {
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
// Pixels no other test uses, since every test shares the store.
let img = image::RgbaImage::from_fn(29, 17, |x, y| image::Rgba([(x * 5) as u8, (y * 13) as u8, 41, 255]));
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let blob = ImageBlob::new("image/png", png.clone());
paint::TEST_ALLOWANCE.with(|c| c.set(Some(64)));
let kept = keep_decoded_image(&blob, image::load_from_memory(&png).unwrap());
paint::TEST_ALLOWANCE.with(|c| c.set(None));
assert!(!kept, "past the allowance: the pixels are refused");
assert!(!image_cached(&blob));
let mut d = Document::new(29.0, 17.0);
d.images.insert("refused".into(), blob);
let id = d.alloc_id();
let im =
ImageObject { key: "refused".into(), width: 29, height: 17, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
let decodes = image_decodes();
let r = Renderer::new().render(&d, 29, 17, Affine::IDENTITY, &RenderOptions::default());
assert_eq!(image_decodes(), decodes + 1, "the first draw decodes the image");
assert!(r.pixel(14, 8)[3] > 0, "the image is drawn");
}
/// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance
/// before either is made: past it, the image is read as other images are (reduced), not whole.
#[test]
+48
View File
@@ -34,6 +34,54 @@ fn geometry_from_measurement_only_frames_releases_old_node_versions() {
assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw");
}
/// The canvas finishes a measurement in every frame that waits for another renderer's frame, also
/// when it measured nothing (a zoom or a pan). Those frames keep the paths this renderer drew, so
/// its next frame, the next step of a pan, does not build them all again.
#[test]
fn finishing_without_a_measurement_keeps_the_drawn_paths() {
let mut doc = Document::new(100.0, 100.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let path = Node::path(
id,
vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(layer), 0, path).unwrap();
let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize;
let mut renderer = Renderer::new();
renderer.render(&doc, 100, 100, Affine::IDENTITY, &RenderOptions::default());
assert!(renderer.geom.contains_key(&drawn), "the frame keeps the path it drew");
for _ in 0..8 {
renderer.finish_measurement_only();
}
assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path");
}
/// Comparing a document with itself measures nothing, so the frames that follow keep the paths
/// this renderer drew.
#[test]
fn an_unchanged_document_keeps_the_drawn_paths() {
let mut doc = Document::new(100.0, 100.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let path = Node::path(
id,
vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(layer), 0, path).unwrap();
let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize;
let mut renderer = Renderer::new();
let opts = RenderOptions::default();
renderer.render(&doc, 100, 100, Affine::IDENTITY, &opts);
for _ in 0..4 {
assert!(matches!(renderer.changed(&doc, &doc, &opts), Changed::Nothing));
renderer.finish_measurement_only();
}
assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path");
}
/// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by
/// the tests running alongside).
fn png(w: u32, h: u32, seed: u8) -> Vec<u8> {
+9 -8
View File
@@ -85,9 +85,8 @@ fn physical_num(v: f64) -> String {
return "0".into();
}
let leading_zeros = (-v.log10().floor() as i32).max(0);
let decimals = (leading_zeros + 3).clamp(3, 14) as u8;
let s = fmt_num(v, decimals);
if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
let decimals = (leading_zeros + 3).max(3);
if decimals > 14 { format!("{v:e}") } else { fmt_num(v, decimals as u8) }
}
/// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated
@@ -186,7 +185,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
.join(nl);
svg.doctype_internal("svg", &entities, nl);
}
let (ww, hh) = (w.num(rect.width()), w.num(rect.height()));
// A positive pixel size that the chosen decimals round to 0 is written with enough digits to stay positive.
let nonzero = |v: f64, s: String| if v > 0.0 && s == "0" { physical_num(v) } else { s };
let (ww, hh) = (nonzero(rect.width(), w.num(rect.width())), nonzero(rect.height(), w.num(rect.height())));
let mut root = svg.root().attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
for (ns, prefix) in &w.foreign_ns {
root = root.attr(&format!("xmlns:{prefix}"), ns);
@@ -197,7 +198,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
if !opts.responsive {
// Explicit SVG Options override the document unit; absence keeps its native save behavior.
if let Some(unit) = opts.units {
let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals));
// Pixels are written bare at one per point.
let (width, height) =
(nonzero(rect.width(), unit.length(rect.width(), opts.decimals)), nonzero(rect.height(), unit.length(rect.height(), opts.decimals)));
root = root.attr("width", &width).attr("height", &height);
} else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) {
let w_val = physical_num(unit.from_pt(rect.width()));
@@ -207,9 +210,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
root = root.attr("width", &ww).attr("height", &hh);
}
}
let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() };
let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() };
root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open();
root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open();
let mut out = svg.as_str().to_string();
out.push_str(nl);
let css = opts.styling == Styling::InternalCss && !w.classes.is_empty();
+23 -1
View File
@@ -3,7 +3,7 @@
use vectorcraft_doc::{Document, Node, NodeKind, Unit};
use vectorcraft_geom::Rect;
use vectorcraft_svg::{ExportOptions, export, import};
use vectorcraft_svg::{ExportOptions, SizeUnit, export, import};
fn art(d: &Document) -> Vec<&Node> {
let mut v = Vec::new();
@@ -191,6 +191,28 @@ fn export_physical_units_writes_unit_suffixes() {
// Re-importing preserved physical units
let back = import(&s).unwrap();
assert_eq!(back.units, Unit::Millimeters);
// A small positive size in pixels keeps a nonzero width and height, with the document unit
// and with Pixels chosen in the SVG options
for (w, h) in [(0.0004, 0.0002), (1e-17, 2e-17), (5.1e-17, 1e-17), (5.1e-15, 4.9e-15)] {
let mut d = Document::new(w, h);
d.units = Unit::Pixels;
for opts in [ExportOptions::default(), ExportOptions { units: Some(SizeUnit::Px), ..Default::default() }] {
let s = export(&d, &opts);
let num = |name: &str| -> f64 { root_attr(&s, name).and_then(|v| v.parse().ok()).unwrap_or_else(|| panic!("{name}: {s}")) };
let view: Vec<f64> = root_attr(&s, "viewBox").unwrap_or_default().split(' ').filter_map(|v| v.parse().ok()).collect();
for (got, want) in [(num("width"), w), (num("height"), h), (view[2], w), (view[3], h)] {
assert!((got - want).abs() <= want * 1e-3, "{got} for {want}: {s}");
}
}
}
}
/// The value of attribute `name` on `svg`'s root element.
fn root_attr<'a>(svg: &'a str, name: &str) -> Option<&'a str> {
let start = svg.find("<svg")?;
let tag = svg[start..].split('>').next()?;
tag.split(&format!(" {name}=\"")).nth(1)?.split('"').next()
}
/// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units
+38 -8
View File
@@ -8,10 +8,11 @@ use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::keymap::Mods;
use craft::menu::Node;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::{Divider, Text};
use craft::ui::layout_components::Row;
use craft::ui::list::{List, ListRow};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::sections::Section;
use egui::Ui;
use serde_json::{Value, json};
@@ -136,6 +137,8 @@ pub(crate) struct Results {
rows: Vec<(String, String, u64)>,
/// The rows picked in the list, by position in `rows`.
picked: Selection<usize>,
/// The clicked finding and the kinds to fix, captured when its menu opens.
menu: Option<(String, Vec<String>)>,
/// What the last fix did.
status: String,
}
@@ -320,14 +323,41 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option<Ac
/// last fix's status, and Show, Fix Selected and Fix All.
fn results(ui: &mut Ui, r: &mut Results, action: &mut Option<Action>) {
let source = Positional { rows: &r.rows, label: |row| row.1.as_str() };
List::<usize>::new(tl!("Issues").to_string()).empty(tl!("No issues found.").to_string()).selection(Bind::bound(&mut r.picked)).show_items(
ui,
&source,
&mut |key, _| match r.rows.get(*key) {
Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()),
let mut selection = r.picked.clone();
let out = List::<usize>::new(tl!("Issues"))
.id(ui.scope_id().with(("cleanup-issues", r.doc)))
.select(SelectMode::Multi)
.row_menu()
.empty(tl!("No issues found.").to_string())
.selection(Bind::bound(&mut selection))
.show_items(ui, &source, &mut |key, item| match r.rows.get(*key) {
Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()).state(item.row.clone()),
None => ListRow::spacer(),
},
);
});
if let Some(key) = out.events.iter().find_map(|event| match event {
CollectionEvent::ContextMenu(request) => Some(request.key),
_ => None,
}) {
if !r.picked.items.contains(&key) {
r.picked = Selection::single(key);
}
r.menu = r.rows.get(key).map(|row| (row.0.clone(), r.picked_kinds()));
} else {
r.picked = selection;
}
if let Some((kind, kinds)) = &r.menu {
let menu = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Show Affected Artwork")).show(ui).ran {
*action = Some(Action::Show(kind.clone()));
}
if MenuItem::new(tl!("Fix Selected")).show(ui).ran {
*action = Some(Action::Fix(kinds.clone()));
}
});
if menu.output.closed.is_some() || action.is_some() {
r.menu = None;
}
}
if !r.status.is_empty() {
Text::new(r.status.clone()).show(ui);
}
@@ -3,6 +3,7 @@ use vectorcraft_engine::Session;
use super::{check, current, fix};
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
/// An app with a rectangle and a stray point (a path of one anchor), nothing selected.
fn app() -> VectorcraftApp {
@@ -46,3 +47,52 @@ fn a_fix_with_no_results_does_nothing() {
assert!(app.addon_panels.cleanup.is_none());
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing was fixed without a check");
}
#[test]
fn a_selected_rows_menu_shows_its_own_artwork_and_fixes_the_whole_selection() {
let mut app = app();
let outside = app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.none", json!({})).unwrap();
check(&mut app, None);
let mut panel = Panel::new(app, super::show);
panel.click("Off-Artboard Art");
panel.click_with("Stray Points", egui::Modifiers::SHIFT);
panel.secondary_click("Off-Artboard Art");
panel.click_menu_item("Show Affected Artwork");
assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(outside)]);
panel.secondary_click("Off-Artboard Art");
panel.click_menu_item("Fix Selected");
assert!(current(&panel.app()).unwrap().rows.is_empty(), "both findings were fixed");
}
#[test]
fn opening_the_menu_on_an_unselected_row_fixes_only_that_finding() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap();
check(&mut app, Some("document"));
let mut panel = Panel::new(app, super::show);
panel.click("Stray Points");
panel.secondary_click("Off-Artboard Art");
panel.click_menu_item("Fix Selected");
let app = panel.app();
let remaining = &current(&app).unwrap().rows;
assert_eq!(remaining.len(), 1);
assert_eq!(remaining[0].0, "strayPoints");
}
#[test]
fn dismissing_the_keyboard_menu_returns_focus_to_the_finding() {
let mut app = app();
check(&mut app, None);
let mut panel = Panel::new(app, super::show);
panel.focus("Stray Points");
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
panel.frame();
assert!(panel.focused("Show Affected Artwork"));
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.frame();
panel.frame();
assert!(panel.focused("Stray Points"));
assert!(!panel.shows("Show Affected Artwork"));
}
+36 -10
View File
@@ -23,7 +23,7 @@ use craft::ui::display::{Divider, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row as Line;
use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::runtime::env::UnitKind;
use craft::ui::text::NumberField;
@@ -149,6 +149,8 @@ fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
pub(crate) struct FoldLines {
/// The last check of each document.
checks: Checks,
/// The immutable check and row on which the context menu opened.
menu: Option<(Weak<Checked>, usize)>,
/// The role rows for the document state they were read for.
rows: Rows,
}
@@ -210,22 +212,45 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
let Some(checked) = last_check(app) else { return };
let Some(checked) = last_check(app) else {
app.addon_panels.fold.menu = None;
return;
};
Text::new(crate::i18n::msg(&checked.summary())).show(ui);
let findings: Vec<Finding> = (0u64..)
.zip(&checked.issues)
.map(|(id, issue)| Finding::new(id, if issue.error { Severity::Error } else { Severity::Warning }, crate::i18n::msg(&issue.message)))
.collect();
let out =
FindingsList::new(tl!("Issues").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) {
Some(finding) => finding.row(&icx.words::<FindingsWords>()),
None => ListRow::spacer(),
});
for event in &out.events {
if let CollectionEvent::Activate(n) = event {
select_issue(app, &checked, *n as usize);
let list = FindingsList::new(tl!("Issues").to_string()).id(ui.scope_id().with(("fold-issues", Arc::as_ptr(&checked))));
let out = list.show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) {
Some(finding) => finding.row(&icx.words::<FindingsWords>()).row_menu(),
None => ListRow::spacer(),
});
for event in out.events {
match event {
CollectionEvent::Activate(n) => select_issue(app, &checked, n as usize),
CollectionEvent::ContextMenu(request) => app.addon_panels.fold.menu = Some((Arc::downgrade(&checked), request.key as usize)),
_ => {}
}
}
let Some((owner, n)) = &app.addon_panels.fold.menu else { return };
let n = *n;
let Some(issue) = checked.issues.get(n).filter(|_| owner.as_ptr() == Arc::as_ptr(&checked)) else {
app.addon_panels.fold.menu = None;
return;
};
let shown = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Select Affected Objects")).enabled(!issue.ids.is_empty()).show(ui).ran {
select_issue(app, &checked, n);
}
if MenuItem::new(tl!("Copy Finding")).show(ui).ran {
app.clipboard_out = Some(crate::i18n::msg(&issue.message));
app.status(tl!("Copied finding"));
}
});
if shown.output.closed.is_some() {
app.addon_panels.fold.menu = None;
}
}
/// One role row: (role id, swatch name, the swatch's paint if the document has it, count).
@@ -346,6 +371,7 @@ fn role_label(role: &str) -> &str {
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else {
app.addon_panels.fold.menu = None;
empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines."));
return;
};
@@ -116,6 +116,58 @@ fn each_document_keeps_its_own_check() {
assert!(last_check(&app).is_some_and(|kept| Arc::ptr_eq(&kept, &second)));
}
#[test]
fn a_finding_menu_selects_its_objects_and_restores_keyboard_focus_on_escape() {
let (mut app, slit) = blank();
let checked = run_check(&mut app, json!({})).unwrap();
let row = format!("{}, Error", checked.issues[0].message);
let mut panel = Panel::new(app, super::show_check);
panel.focus(&row);
panel.key(Key::F10, Modifiers::SHIFT);
panel.frame();
panel.frame();
assert!(panel.focused("Select Affected Objects"));
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
panel.frame();
assert!(panel.focused(&row));
panel.secondary_click(&row);
panel.frame();
panel.click_menu_item("Select Affected Objects");
assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(slit)]);
}
#[test]
fn a_recheck_and_a_document_switch_dismiss_the_menu_and_an_objectless_finding_can_be_copied() {
let (mut app, a, _) = app();
app.run("select.set", json!({"ids": [a]})).unwrap();
let checked = run_check(&mut app, json!({})).unwrap();
let row = format!("{}, Error", checked.issues[0].message);
let mut panel = Panel::new(app, super::show_check);
panel.secondary_click(&row);
panel.frame();
assert!(!panel.menu_item_enabled("Select Affected Objects"));
panel.click_menu_item("Copy Finding");
assert_eq!(panel.app().clipboard_out.as_deref(), Some(checked.issues[0].message.as_str()));
assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(a)]);
panel.secondary_click(&row);
panel.frame();
assert!(panel.shows("Copy Finding"));
let replacement = run_check(&mut panel.app(), json!({"ids": [a]})).unwrap();
panel.frame();
assert!(!panel.shows("Copy Finding"));
assert!(!panel.shows("Select Affected Objects"));
panel.secondary_click(&format!("{}, Error", replacement.issues[0].message));
panel.frame();
assert!(panel.shows("Copy Finding"));
panel.app().run("file.new", json!({"width": 100, "height": 100})).unwrap();
run_check(&mut panel.app(), json!({})).unwrap();
panel.frame();
assert!(!panel.shows("Copy Finding"));
assert!(!panel.shows("Select Affected Objects"));
}
/// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`).
const ISSUE_MESSAGES: [&str; 17] = [
"No cut lines are in the selection.",
+2
View File
@@ -168,6 +168,8 @@ impl VectorcraftApp {
carry_target: None,
last_drag: None,
escaped_press: false,
pressed_at: None,
keys_at: None,
host_caps_lock: None,
committed_preview: false,
panes: Default::default(),
+6
View File
@@ -129,6 +129,12 @@ pub struct CanvasCache {
/// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up,
/// which gives back a selection tool Cmd lent.
pub escaped_press: bool,
/// The input time of the last pass whose pointer button events all landed on a canvas, with no other layer over it:
/// the menus' state key leaves such a press out (`menus::model::last_press`).
pub pressed_at: Option<f64>,
/// The input time of the last pass in which the canvas or nothing had the focus, so that the canvas or the app's
/// shortcuts took its keys: the menus' state key leaves those keys out (`menus::model::last_press`).
pub keys_at: Option<f64>,
/// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the
/// next reading; `None` before the first pass.
pub host_caps_lock: Option<bool>,
+95 -1
View File
@@ -1,3 +1,5 @@
use craft::behavior::IconId;
use craft::menu::Item;
use craft::ui::canvas::CanvasSpace;
use craft::ui::contract::overlay::Anchor;
use craft::ui::contract::{Bind, ShowContainer as _, Trigger};
@@ -47,7 +49,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
.opened_by(opener, Trigger::Manual)
.anchor(Anchor::Point(at))
.open(Bind::bound(&mut open))
.show(ui, |ui, _| craft::menu::context::rows(ui, &nodes));
.show(ui, |ui, _| craft::menu::context::rows_with_icons(ui, &nodes, canvas_icon));
if shown.output.closed.is_some() || !open {
app.ui.context_menu_at = None;
app.ui.context_locked = None;
@@ -57,6 +59,54 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
}
}
/// The icon each canvas menu command shows in this menu, so a row can be found by its shape (#4602). A command
/// left out has no glyph that says what it does here, and shows its catalog icon, if any, or none.
const ICONS: &[(&str, &str)] = &[
("edit.undo", "undo-2"),
("edit.redo", "redo-2"),
("edit.cut", "scissors"),
("edit.copy", "copy"),
("edit.paste", "clipboard-paste"),
("edit.clear", "trash-2"),
("object.group", "group"),
("object.ungroup", "ungroup"),
("object.path.smooth", "dc-smooth"),
("object.objectsOnPath.attach", "dc-objects-on-path"),
("path.join", "dc-join"),
("type.applyBullets", "dc-para-bullets"),
("type.applyNumbers", "dc-para-numbers"),
("view.grid", "grid-3x3"),
("view.rulers", "ruler"),
("view.guides.lock", "lock"),
("view.fitArtboard", "maximize-2"),
("artboard.new", "file-plus"),
("artboard.duplicate", "copy"),
("artboard.copy", "copy"),
("artboard.cut", "scissors"),
("artboard.delete", "trash-2"),
("artboard.rearrange", "dc-rearrange"),
("file.exportSelection", "share-2"),
("file.exportForScreens", "share-2"),
];
/// The icons of rows whose command alone doesn't say what they do: Artboard Options (`tool.options` for the
/// Artboard tool) and the Lock Artboards and Unlock Artboards rows (`artboard.setProps` with `locked`).
const ARTBOARD_OPTIONS_ICON: &str = "dc-artboard-options";
const LOCK_ICON: &str = "lock";
const UNLOCK_ICON: &str = "lock-open";
/// The canvas menu's icon for `item`: Artboard Options' and the artboard lock rows' by their parameters, otherwise
/// its command's entry in [`ICONS`].
fn canvas_icon(item: &Item) -> Option<IconId> {
let params = &item.command.params;
let icon = match item.command.id.as_str() {
"tool.options" => (params["tool"] == "artboard").then_some(ARTBOARD_OPTIONS_ICON),
"artboard.setProps" => params["artboards"][0]["locked"].as_bool().map(|locked| if locked { LOCK_ICON } else { UNLOCK_ICON }),
id => ICONS.iter().find(|(command, _)| *command == id).map(|(_, icon)| *icon),
};
icon.map(IconId::new)
}
/// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection.
fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) {
let p = space.view.to_doc(at);
@@ -114,3 +164,47 @@ fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 {
}
at
}
#[cfg(test)]
mod tests {
use craft::behavior::IconId;
use craft::ui::primitives::has_icon;
use craft::menu::Node;
use serde_json::json;
use super::{ARTBOARD_OPTIONS_ICON, ICONS, LOCK_ICON, UNLOCK_ICON, canvas_icon};
use crate::menus::cp;
/// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot
/// empty, and a renamed command would quietly lose its icon.
#[test]
fn every_canvas_menu_icon_is_an_icon_of_a_command() {
crate::icons::register();
for (id, icon) in ICONS {
assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} isn't an icon");
let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id);
assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command");
}
for icon in [ARTBOARD_OPTIONS_ICON, LOCK_ICON, UNLOCK_ICON] {
assert!(has_icon(&IconId::new(icon)), "{icon} isn't an icon");
}
}
/// Rows that share a command take their icon from their parameters: the Artboard Options glyph goes on
/// Artboard Options (`tool.options` for the Artboard tool), not on another tool's options, and the Lock
/// Artboards and Unlock Artboards rows (`artboard.setProps`) show a closed and an open lock.
#[test]
fn rows_that_share_a_command_take_their_icon_from_its_parameters() {
let icon = |node: Node| match node {
Node::Item(item) => canvas_icon(&item),
_ => None,
};
let lock = |locked| cp("Lock All", "artboard.setProps", json!({ "artboards": [{ "index": 0, "locked": locked }] }));
assert_eq!(icon(cp("Artboard Options", "tool.options", json!({ "tool": "artboard" }))), Some(IconId::new(ARTBOARD_OPTIONS_ICON)));
assert_eq!(icon(cp("Options", "tool.options", json!({ "tool": "pen" }))), None);
assert_eq!(icon(lock(true)), Some(IconId::new(LOCK_ICON)));
assert_eq!(icon(lock(false)), Some(IconId::new(UNLOCK_ICON)));
assert_ne!(icon(lock(true)), icon(lock(false)));
}
}
+8 -1
View File
@@ -19,7 +19,7 @@ use craft::ui::canvas_controls::TaskBar;
use craft::ui::choice::Segmented;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _};
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::env::{Direction, Env};
use craft::ui::runtime::env::{Direction, Env, WordsOverride, with_env};
use vectorcraft_tools::quickpen::{self, Stroke as Action};
use super::{Ui, VectorcraftApp, json};
@@ -31,6 +31,13 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva
if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID {
return None;
}
let lang = app.ui_language();
let words = super::task_bar::bar_words(lang, "Move Toolbar", "Hide Toolbar", "window.quickPenToolbar.pin", "window.quickPenToolbar.reset");
with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_quick_pen_bar(app, ui, space))
}
/// The Quick Pen toolbar of [`quick_pen_bar`], in a scope with the toolbar's words.
fn shown_quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<egui::Rect> {
// PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3)
if super::tool_adapter::in_gesture(app, ui.ctx()) {
return None;
+34 -2
View File
@@ -1,17 +1,18 @@
use craft::behavior::CanvasView;
use craft::behavior::{IconId, Mixed};
use craft::color_ui::ui::{PaintChip, PaintChipSize};
use craft::i18n::WordSet as _;
use craft::theme::{Srgba, Variant};
use craft::ui::buttons::{Button, IconButton};
use craft::ui::canvas::CanvasSpace;
use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang};
use craft::ui::canvas_controls::{CanvasControlWords, TaskBar, TaskBarGrip, TaskBarHang};
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::display::Text;
use craft::ui::menu::PanelRow;
use craft::ui::popover::Popover;
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env};
use vectorcraft_doc::NodeKind;
use vectorcraft_doc::text::TextKind;
use vectorcraft_geom::{Point, Rect};
@@ -442,12 +443,43 @@ fn more_rows(offer: &Offer) -> Vec<PanelRow> {
]
}
/// VectorCraft's words for a canvas bar's More Options button, its grip (`grip`) and the rows the framework puts in
/// More Options (`hide`, and the commands `pin` and `reset`, named by their titles), over the framework's words. Outside
/// English, a word the language's catalog does not translate keeps the framework's translation.
pub(crate) fn bar_words(lang: crate::i18n::Lang, grip: &'static str, hide: &'static str, pin: &str, reset: &str) -> WordRows {
fn plain(lang: crate::i18n::Lang, english: &'static str) -> (&'static str, &'static str) {
(english, crate::i18n::tr(lang, english))
}
fn command(lang: crate::i18n::Lang, id: &str) -> (&'static str, &'static str) {
let english = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map_or("", |c| c.1);
(english, crate::i18n::tr_id(lang, id, english))
}
let words = [
("taskBar.more", plain(lang, "More Options")),
("taskBar.move", plain(lang, grip)),
("taskBar.hide", plain(lang, hide)),
("taskBar.pin", command(lang, pin)),
("taskBar.reset", command(lang, reset)),
];
words
.into_iter()
.filter(|(_, (english, shown))| !english.is_empty() && (lang == crate::i18n::Lang::EN || shown != english))
.filter_map(|(id, (_, shown))| Some((CanvasControlWords::word(id)?, shown)))
.fold(WordRows::new(), |rows, (word, shown)| rows.row(word, shown))
}
/// The Contextual Task Bar: a floating pill under the selection with the most likely next actions
/// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the
/// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action
/// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the
/// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen.
pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<egui::Rect> {
let words = bar_words(app.ui_language(), "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset");
with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_task_bar(app, ui, space))
}
/// The Contextual Task Bar of [`task_bar`], in a scope with the bar's words.
fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<egui::Rect> {
let offer = offered(app)?;
let key = (app.session.active()?.uid, false);
let mut local = app.ui.task_bar_place.for_key(key);
+74 -17
View File
@@ -897,13 +897,12 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() {
assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it");
}
/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its
/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the
/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts
/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new
/// app, at most 20 times, until the other catalogs held still through it.
#[test]
fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
/// How many times each frame of `steps` builds the menus' states again, with the Selection tool and a 60 × 30
/// rectangle at (100, 100) selected and the pointer resting over its middle (`steps` gets that point). The menus are
/// also built again when a process-wide catalog changes, so the fonts and plug-ins are held steady against tests
/// running alongside for the whole run, and the steps run again on a new app, at most 20 times, until the other
/// catalogs held still through them.
fn selection_tool_rebuilds(steps: impl Fn(Pos2, &craft::behavior::CanvasView) -> Vec<Vec<egui::Event>>) -> (VectorcraftApp, Vec<u64>) {
let fonts = vectorcraft_text::FontDb::global();
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
let catalogs = || {
@@ -920,33 +919,59 @@ fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0)));
let from = xf.to_screen(Point::new(130.0, 115.0));
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
for _ in 0..2 {
app_step(&mut app, &ctx, vec![]);
}
let none = egui::Modifiers::NONE;
let mut steps = vec![vec![primary(from, true, none)]];
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
steps.push(vec![primary(to, false, none)]);
steps.extend([vec![], vec![], vec![]]);
let mut rebuilt = vec![];
for events in steps {
for events in steps(from, &xf) {
let before = app.menus.rebuilds;
app_step(&mut app, &ctx, events);
rebuilt.push(app.menus.rebuilds - before);
}
(app, rebuilt)
};
let (app, rebuilt) = (0..20)
(0..20)
.find_map(|_| {
let before = catalogs();
let out = run();
(catalogs() == before).then_some(out)
})
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"))
}
/// A Selection tool move builds the menus' states again once, for the release that commits it. Its press lands on the
/// canvas, and the frame the move begins in and the frames of its previews, which change the document's revision, keep
/// them.
#[test]
fn a_selection_move_rebuilds_the_menus_for_its_release_only() {
let none = egui::Modifiers::NONE;
let (app, rebuilt) = selection_tool_rebuilds(|from, xf| {
let to = xf.to_screen(Point::new(170.0, 135.0));
let mut steps = vec![vec![primary(from, true, none)]];
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
steps.push(vec![primary(to, false, none)]);
steps.extend([vec![], vec![], vec![]]);
steps
});
assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle");
assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle");
assert_eq!(rebuilt[..9].iter().sum::<u64>(), 0, "the press and the 8 moves keep the menus: {rebuilt:?}");
assert_eq!(rebuilt.iter().sum::<u64>(), 1, "the release that commits the move rebuilds them once: {rebuilt:?}");
}
/// A click on the selected rectangle that leaves it where it was, and F20 pressed and released with no field or dialog
/// taking it and no command on it, change nothing the menus show: no frame builds the menus' states again.
#[test]
fn a_canvas_click_that_changes_nothing_keeps_the_menus() {
let none = egui::Modifiers::NONE;
let f20 = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: none };
let (app, rebuilt) = selection_tool_rebuilds(|from, _| {
vec![vec![primary(from, true, none)], vec![primary(from, false, none)], vec![f20(true)], vec![f20(false)], vec![], vec![]]
});
assert_eq!(drawn_paths(&app), vec![Rect::new(100.0, 100.0, 160.0, 130.0)], "the click leaves the rectangle where it was");
assert_eq!(app.session.active().map(|d| d.selection.objects.len()), Some(1), "the rectangle stays selected");
assert_eq!(rebuilt, [0; 6], "rebuilds in each frame: press, release, a key press and release, 2 idle");
}
/// #6369: only the selection box remains over the temporary halftone, and the original
@@ -4489,6 +4514,38 @@ fn plain(app: &VectorcraftApp, id: u64) -> String {
}
}
/// While the Type tool edits text, a click in the text and an arrow key, which move the caret without an edit, build
/// the menus' states again: the type rows read the caret's range.
#[test]
fn a_click_or_a_key_in_edited_text_rebuilds_the_menus() {
use egui::Event;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.prefs.placeholder_text = false;
let ctx = crate::testing::ui_context();
let id = start_typing(&mut app, &ctx);
typing_frame(&mut app, &ctx, vec![Event::Text("abc".into())]);
typing_frame(&mut app, &ctx, vec![]);
let at = app.canvas_view().unwrap().to_screen(Point::new(101.0, 100.0));
let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
let left = |pressed| Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
let rebuilds = |app: &mut VectorcraftApp, steps: Vec<Vec<Event>>| {
let before = app.menus.rebuilds;
for events in steps {
typing_frame(app, &ctx, events);
}
app.menus.rebuilds - before
};
let click = || vec![vec![Event::PointerMoved(at), button(true)], vec![button(false)]];
// The first click puts the caret there; the second leaves the document's revision as it is.
rebuilds(&mut app, click());
let revision = app.session.active().map(|d| d.revision);
assert!(rebuilds(&mut app, click()) > 0, "a click in the text");
assert_eq!(app.session.active().map(|d| d.revision), revision, "the click changes no revision");
assert!(rebuilds(&mut app, vec![vec![left(true)], vec![left(false)]]) > 0, "an arrow key in the text");
assert_eq!(plain(&app, id), "abc", "neither edits the text");
assert!(app.session.tool_wants_text(), "editing goes on");
}
/// Starts editing new point type with the Type tool; returns its id.
fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 {
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more