Merge main into feat/color-wheel-hsl-sliders

This commit is contained in:
dotCooCoo committed 2026-11-18 15:58:55 -08:00
commit c332e13600
406 files changed
+47270 -2191

No files matched your search

Generated
+16
View File
@@ -1044,6 +1044,20 @@ name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -6630,6 +6644,7 @@ dependencies = [
"webbrowser",
"windows",
"winit",
"winreg",
"winresource",
"winsafe",
"wl-clipboard-rs",
@@ -7109,6 +7124,7 @@ dependencies = [
name = "vectorcraft-text"
version = "0.24.1"
dependencies = [
"craft-font-catalog",
"craft-proof",
"harfrust 0.13.3",
"icu_segmenter",
+2
View File
@@ -154,8 +154,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
+3
View File
@@ -40,6 +40,9 @@ craft-print = { workspace = true }
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
clipboard-win = { workspace = true }
# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs).
# MIT, already in the build through the update client.
winreg = "0.55"
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
+41 -3
View File
@@ -96,7 +96,24 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
Some(folder) => d.folder(folder),
None => d,
};
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
if pick.name.is_empty() {
return d;
}
// Windows' save dialog changes the extension when a different file type is chosen only when
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
// A remaining dot in the stem would look like another explicit extension to Windows.
#[cfg(windows)]
if matches!(request, PickRequest::Save(_))
&& pick.filters.len() > 1
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
&& !stem.contains('.')
{
return d.file_name(stem);
}
d.file_name(&pick.name)
}
#[cfg(test)]
@@ -796,7 +813,7 @@ mod dialog_tests {
/// The file types a dialog was given, by label.
#[derive(Default)]
struct Filters(Vec<(String, Vec<String>)>);
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
impl DialogSettings for Filters {
fn parent(self, _window: &winit::window::Window) -> Self {
@@ -812,7 +829,8 @@ mod dialog_tests {
fn folder(self, _folder: &str) -> Self {
self
}
fn file_name(self, _name: &str) -> Self {
fn file_name(mut self, name: &str) -> Self {
self.1 = Some(name.to_string());
self
}
}
@@ -869,4 +887,24 @@ mod dialog_tests {
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
}
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
#[cfg(windows)]
#[test]
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
}
}
+5
View File
@@ -3,6 +3,8 @@
use std::process::Command;
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
mod direct_pdf;
pub struct SystemPrint;
impl PrintService for SystemPrint {
fn printers(&mut self) -> Vec<Printer> {
@@ -43,6 +45,9 @@ mod system {
craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect()
}
pub fn print(job: &PrintJob) -> Result<String, String> {
if job.direct_pdf {
return super::direct_pdf::print(job);
}
// Copies, layout, marks and colour management are already in the PDF. Preserve its
// physical sheet size and the queue's duplex default without printing copies twice.
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
+127
View File
@@ -0,0 +1,127 @@
//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port.
//!
//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page
//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The
//! PDF already carries the paper size, so the printer's interpreter prints it as laid out.
#[cfg(windows)]
mod imp {
use std::io::Write;
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
use std::time::Duration;
use vectorcraft_ui_egui::print::PrintJob;
use winreg::RegKey;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ};
/// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port.
pub fn print(job: &PrintJob) -> Result<String, String> {
let printer = job
.printer
.map(str::to_string)
.or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name))
.ok_or("direct PDF needs a selected printer")?;
let (host, port) = tcp_port(&printer)?;
send(&host, port, &pjl(job.title, job.pdf))?;
Ok(format!(" (direct PDF to {host}:{port})"))
}
/// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port.
fn tcp_port(printer: &str) -> Result<(String, u16), String> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let printer_key = hklm
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ)
.map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?;
let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?;
let port_key = hklm
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ)
.map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?;
let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1);
if protocol != 1 {
return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port"));
}
let host = port_key
.get_value::<String, _>("HostName")
.ok()
.filter(|h| !h.trim().is_empty())
.or_else(|| port_key.get_value::<String, _>("IPAddress").ok().filter(|h| !h.trim().is_empty()))
.ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?;
let number = port_key.get_value::<u32, _>("PortNumber").unwrap_or(9100);
let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?;
Ok((host.trim().to_string(), port))
}
/// Frame the PDF for the printer's PJL interpreter.
fn pjl(title: &str, pdf: &[u8]) -> Vec<u8> {
let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect();
if name.is_empty() {
name.push_str("VectorCraft");
}
let mut out = Vec::with_capacity(pdf.len() + 96);
out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\"");
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n");
out.extend_from_slice(pdf);
out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n");
out
}
/// Stream `data` to the first reachable address of `host:port`.
fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> {
let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?;
let mut last = None;
for addr in addrs {
match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) {
Ok(mut stream) => {
stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?;
stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?;
stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?;
return Ok(());
}
Err(e) => last = Some(e),
}
}
Err(match last {
Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"),
None => format!("direct PDF: {host}:{port} has no addresses"),
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::net::TcpListener;
#[test]
fn the_pjl_frames_the_pdf() {
let out = pjl("witch hat\"", b"%PDF-1.7");
let text = String::from_utf8_lossy(&out);
assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"));
assert!(text.contains("%PDF-1.7"));
assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n"));
}
#[test]
fn the_pdf_reaches_a_listening_port() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let t = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut got = Vec::new();
stream.read_to_end(&mut got).unwrap();
got
});
send("127.0.0.1", port, b"%PDF-1.7 test").unwrap();
assert_eq!(t.join().unwrap(), b"%PDF-1.7 test");
}
}
}
#[cfg(windows)]
pub use imp::print;
#[cfg(not(windows))]
pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result<String, String> {
Err("direct PDF printing is only available on Windows".into())
}
+12
View File
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
None,
}
impl ArrowStyle {
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
match self {
Self::Filled => Some(crate::Arrowhead::Triangle),
Self::Open => Some(crate::Arrowhead::TriangleOpen),
Self::Tick => Some(crate::Arrowhead::Slash),
Self::None => None,
}
}
}
/// Where the label sits across the dimension line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
+38
View File
@@ -424,6 +424,44 @@ impl Document {
out
}
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
/// them. As for every cached lookup, a second node given an existing id after the cache was
/// built is not found while the first one's cached path checks out (see [`id_index`]).
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
// of the document.
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
let mut paths = Vec::with_capacity(want.len());
let cached = want.iter().all(|id| match cache.get(id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
paths.push(p);
true
}
_ => false,
});
if cached {
// A node's path sorts after the paths of the nodes before it in tree order, its
// ancestors included.
paths.sort_unstable();
return paths.iter().filter_map(|p| self.node_at(p)).collect();
}
}
let mut out = Vec::new();
if !want.is_empty() {
crate::id_index::note_tree_walk();
self.walk(|n| {
if want.contains(&n.id) {
out.push(n);
}
});
}
out
}
/// The node at index path `path` (as [`Document::index_path`] gives it).
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
let (first, rest) = path.split_first()?;
+440
View File
@@ -0,0 +1,440 @@
//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its
//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes};
use crate::Appearance;
use crate::node::{Node, NodeId, NodeKind};
/// The seed of the sizes a flare's rays and rings take when its settings give none.
pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d;
/// One part of a flare: its name, outline, fill and opacity.
pub type Part = (&'static str, PathData, Paint, f32);
/// The number `key` of the settings `v`, or `default`.
fn number(v: &Value, key: &str, default: f64) -> f64 {
v.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright
/// center, a halo ring, rays of varying length and rings along the path to the end point.
pub fn parts(v: &Value) -> Vec<Part> {
let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0));
let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y));
let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0);
let r = (number(v, "diameter", 100.0) / 2.0).max(0.5);
let opacity = pct("opacity").min(1.0) as f32;
let brightness = pct("brightness").min(1.0) as f32;
let growth = pct("growth");
let fuzz = pct("fuzziness").min(1.0);
let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
let longest = pct("longest");
let ray_fuzz = pct("rayFuzziness").min(1.0);
let ray_turn = number(v, "rotation", 0.0).to_radians();
let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
let largest = pct("largest");
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
// along the path from a sequence of its own; their count and sizes and the other parts stay.
// Xorshift64. Both streams start from a nonzero state.
let random = |mut state: u64| {
move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
}
};
let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| {
// SplitMix64 initializes the ring-position stream.
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
random(z ^ (z >> 31))
});
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
Paint::Gradient(Box::new(g))
};
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
let mut parts: Vec<Part> = vec![];
// Halo: a soft ring just outside the centre.
let halo_r = r * (1.0 + growth) * 1.6;
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
// `rotation` turns them clockwise about the center.
if rays > 0 {
let mut bp = BezPath::new();
let mut reach: f64 = 0.0;
for i in 0..rays {
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
reach = reach.max(len);
let w = r * 0.035;
let dir = Vec2::new(a.cos(), a.sin());
let n = Vec2::new(-dir.y, dir.x) * w;
bp.move_to(c + n);
bp.line_to(c + dir * len);
bp.line_to(c - n);
bp.line_to(c - dir * (w * 4.0));
bp.close_path();
}
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
}
// Centre: bright core fading to transparent.
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
// Rings along the path to the end point (Largest = % of the average ring size).
for _ in 0..rings {
let t = rnd();
let t = ring_at.as_mut().map_or(t, |next| next());
let at = c + (end - c) * t;
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
let solid = rnd() < 0.5;
let stops = if solid {
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
} else {
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
};
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
}
parts
}
/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had
/// since it was drawn), with the pixel-aligned property when `aligned`.
pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node {
let (name, pd, paint, op) = part;
let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0));
n.name = Some(name.into());
n.blend = BlendMode::Screen;
n.opacity = op;
if aligned {
n.extras_mut().pixel_aligned = true;
}
if xf != Affine::IDENTITY {
n.transform(xf, false);
}
n
}
/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that
/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse
/// (transforms applied one by one and all at once can put the end on different axes of it).
fn ellipse(geom: &GradientGeom) -> [f64; 3] {
let u = geom.end - geom.start;
let w = Vec2::new(-u.y, u.x) * geom.aspect;
[u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y]
}
/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and
/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice
/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a
/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient
/// makes smaller than the tolerance.
fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) {
let [xx, xy, yy] = ellipse(geom);
let half_diff = (xx - yy) / 2.0;
let d = half_diff.hypot(xy);
let longer = (xx + yy) / 2.0 + d;
if longer.is_nan() || longer <= 0.0 {
return (0.0, [0.0; 3]);
}
// The product of the half-axes is the area factor of the map from the unit circle, `u` across
// `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation
// of `xx * yy - xy * xy` for a narrow ellipse.
let u = geom.end - geom.start;
let w = Vec2::new(-u.y, u.x) * geom.aspect;
let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0);
let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) };
(longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin])
}
/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its
/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its
/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned
/// part's snap allowance, which is a length).
fn comparable(n: &Node) -> Value {
fn strip(v: &mut Value) {
match v {
Value::Object(m) => {
for key in ["id", "bbox_angle"] {
m.remove(key);
}
if let Some(geom) = m.get_mut("geom")
&& let Ok(g) = serde_json::from_value::<GradientGeom>(geom.clone())
&& let Value::Object(geom) = geom
{
let (size, shape) = ellipse_size_and_shape(&g);
geom.remove("end");
geom.remove("aspect");
geom.insert("ellipse".into(), serde_json::json!(size));
m.insert("ellipseShape".into(), serde_json::json!(shape));
}
m.values_mut().for_each(strip);
}
Value::Array(a) => a.iter_mut().for_each(strip),
_ => {}
}
}
let mut v = serde_json::to_value(n).unwrap_or(Value::Null);
strip(&mut v);
v
}
/// How close, relative to its size, a number in an outline or a gradient's placement must be to the
/// one its transforms give: a few thousandths of a point near the edge of the canvas.
const GEOMETRY_TOL: f64 = 1e-9;
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each
/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`]
/// relative to its size (or `tol`, when smaller), and `snap` points as well.
fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
(Some(x), Some(y)) => {
let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) };
(x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs()))
}
_ => x == y,
},
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)),
(Value::Object(x), Value::Object(y)) => {
x.len() == y.len()
&& x.iter().all(|(k, v)| {
// A gradient's shape is ratios: compared as closely as geometry, without the snap.
let snap = if k == "ellipseShape" { 0.0 } else { snap };
y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape"))
})
}
_ => a == b,
}
}
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size.
pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool {
close(a, b, tol, 0.0, false)
}
/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to
/// the pixel grid moves each by up to a pixel.
const PIXEL_SNAP: f64 = 1.0;
/// The settings of a flare group ([`crate::NodeExtras::flare`]).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FlareSpec {
/// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and
/// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in.
pub params: serde_json::Value,
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections and
/// shears).
#[serde(default = "identity", skip_serializing_if = "is_identity")]
pub transform: Affine,
}
fn identity() -> Affine {
Affine::IDENTITY
}
fn is_identity(a: &Affine) -> bool {
*a == Affine::IDENTITY
}
impl FlareSpec {
/// The settings of a flare drawn with `params`, not transformed since.
pub fn new(params: serde_json::Value) -> Self {
Self { params, transform: Affine::IDENTITY }
}
/// The point `key_x`, `key_y` of the params, where it is in the document now.
fn point(&self, key_x: &str, key_y: &str) -> Option<Point> {
let x = self.params.get(key_x)?.as_f64()?;
let y = self.params.get(key_y)?.as_f64()?;
Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite())
}
/// The flare's center, where it is in the document now.
pub fn center(&self) -> Option<Point> {
self.point("cx", "cy")
}
/// The rings' end point, where it is in the document now.
pub fn end(&self) -> Option<Point> {
self.point("x2", "y2")
}
/// Its art transformed by `a`.
pub fn transform(&mut self, a: Affine) {
self.transform = a * self.transform;
}
/// Whether `group`'s parts are still the ones these settings draw, in place: none was edited,
/// distorted, removed or added, and the transform can be undone. The parts are compared where
/// they are in the document, at any scale.
pub fn draws(&self, group: &Node) -> bool {
let NodeKind::Group { children, .. } = &group.kind else { return false };
if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() {
return false;
}
let expected = parts(&self.params);
expected.len() == children.len()
&& expected.into_iter().zip(children).all(|(part, child)| {
let aligned = child.extras().pixel_aligned;
let snap = if aligned { PIXEL_SNAP } else { 0.0 };
close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// A flare's center and end point follow its art through a transform, and a save and reload
/// keeps its settings.
#[test]
fn a_flare_keeps_its_settings_through_a_transform_and_a_save() {
let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]);
g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 }))));
g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false);
let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
let c = spec.center().unwrap_or_else(|| panic!("no center"));
let e = spec.end().unwrap_or_else(|| panic!("no end"));
assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}");
assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}");
let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}"));
let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(back.extras().flare.as_deref(), Some(&spec));
// A flare that was not transformed writes no transform.
let plain = FlareSpec::new(json!({ "cx": 1.0 }));
assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } }));
}
/// A flare group draws its settings until a part's gradient, opacity or outline is edited; a
/// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its
/// outline and its gradient's placement.
#[test]
fn a_flare_with_an_edited_part_no_longer_draws_its_settings() {
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0,
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
"rotation": 0.0, "largest": 50.0 });
let flare = |aligned: bool| {
let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75);
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
let mut g = Node::group(NodeId(1), children.collect());
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
g
};
let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| {
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
// The center, drawn at half opacity.
f(std::sync::Arc::make_mut(&mut children[2]));
};
for aligned in [false, true] {
let g = flare(aligned);
assert!(spec(&g).draws(&g), "aligned {aligned}");
let mut moved = g.clone();
edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false));
assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}");
let mut faded = g.clone();
edit(&mut faded, &|n| n.opacity *= 0.8);
assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}");
let mut shifted = g.clone();
edit(&mut shifted, &|n| {
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
geom.start.x += 20.0;
}
});
assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}");
let mut squashed = g.clone();
edit(&mut squashed, &|n| {
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
geom.aspect *= 0.5;
}
});
assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}");
}
}
/// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow
/// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`].
#[test]
fn an_ellipse_shape_tells_narrow_gradients_apart() {
let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None };
let of = ellipse_size_and_shape;
let (size, shape) = of(&geom((11.0, 2.0), 0.5));
// The same ellipse with its end point on the other axis.
let (size2, shape2) = of(&geom((1.0, 7.0), 2.0));
assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}");
// A very narrow ellipse, given both ways, keeps its shape to within the tolerance.
let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1);
assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}");
let narrow = of(&geom((11.0, 2.0), 1e-4)).1;
for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] {
assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}");
}
assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3]));
}
/// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its
/// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare
/// does not draw its settings.
#[test]
fn a_flare_scaled_far_down_still_draws_its_settings() {
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 });
let flare_aligned = |xf: Affine, aligned: bool| {
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
let mut g = Node::group(NodeId(1), children.collect());
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
g
};
let flare = |xf: Affine| flare_aligned(xf, false);
// The center's gradient placement, to edit.
let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| {
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
f(geom);
} else {
panic!("the center has no gradient fill");
}
};
let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g));
assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%");
assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis");
assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas");
assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away");
assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened");
// At that size a part whose gradient's shape was edited no longer draws the settings.
let mut squashed = flare(Affine::scale(1e-6));
assert!(draws(&squashed), "scaled to 0.0001%");
center_geom(&mut squashed, &|geom| geom.aspect *= 0.5);
assert!(!draws(&squashed), "gradient shape at 0.0001%");
// A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change,
// even when the ellipse keeps its size.
let mut reshaped = flare_aligned(Affine::IDENTITY, true);
assert!(draws(&reshaped), "aligned");
center_geom(&mut reshaped, &|geom| {
let a = geom.aspect;
geom.aspect = a * 0.5;
geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt();
});
assert!(!draws(&reshaped), "gradient shape of the same size, aligned");
}
}
+89 -46
View File
@@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
/// touched where the live geometry effects of a clipping path in their art show it, or where the
/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except
/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
@@ -2104,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// the members of a group or layer with geometry effects of its own, are touched where the art those
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false, false)
marquee_with(doc, r, scope, leaves, false, false, false)
}
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
/// the clicks of [`HitOptions::outline`] do.
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false, outline)
/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides
/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the
/// top or inside a group, so a group is not taken for a guide in it (#8538).
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool, skip_guides: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false, outline, skip_guides)
}
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true, outline)
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool, skip_guides: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true, outline, skip_guides)
}
/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is
/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and
/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the
/// guides are hidden, [`HitOptions::skip_guides`] for the marquee).
#[derive(Clone, Copy)]
struct Rules {
whole_compounds: bool,
skip_guides: bool,
}
impl Rules {
/// Is `n` a path made into a guide that the marquee leaves out?
fn skips(self, n: &Node) -> bool {
self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
}
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
@@ -2125,8 +2146,17 @@ fn previews_off(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { preview: false, .. })
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
fn marquee_with(
doc: &Document,
r: Rect,
scope: Option<NodeId>,
leaves: bool,
whole_compounds: bool,
outline: bool,
skip_guides: bool,
) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let rules = Rules { whole_compounds, skip_guides };
let mut out = Vec::new();
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let locks = doc.locked_artboards_kept();
@@ -2140,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
Some(c) => {
// In an isolated clip group, its members by their own geometry, as clicks take
// them ([`edits_inside`]).
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) };
c.iter()
.enumerate()
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
@@ -2162,7 +2192,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
.layers
.iter()
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
.flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None))
.flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None))
.collect(),
};
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
@@ -2171,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
/// `l` has such effects.
fn layer_objects<'a>(
l: &'a Node,
s: &SymbolBoxes,
r: Rect,
outline: bool,
whole_compounds: bool,
drawn: Option<Rc<HashSet<NodeId>>>,
) -> Vec<Top<'a>> {
fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option<Rc<HashSet<NodeId>>>) -> Vec<Top<'a>> {
let mut out = vec![];
let outline = outline || previews_off(l);
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline));
let inner = marquee_in_parent(l, r, outline);
for (i, c) in l.children().into_iter().flatten().enumerate() {
if c.is_layer() {
@@ -2190,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
&& !c.locked
&& !c.is_template()
{
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone()));
}
} else if !c.is_ruler_guide() {
if drawn.is_some() {
@@ -2207,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
/// `None` in outline and when it has no such effects.
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
let art = drawn_art(s, n, outline)?;
let _off = DrawnOff::set();
let mut ids = vec![];
for a in art.iter().filter(|a| a.visible) {
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
collect_leaves(a, s, r, None, rules, false, &mut ids);
}
Some(Rc::new(ids.into_iter().collect()))
}
@@ -2265,14 +2288,20 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
/// compound paths, layers and groups are touched by their box, and an image or a symbol
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping
/// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region
/// ([`clip_edge_touches`]).
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool) -> bool {
// Locked or hidden guides are not touched ([`Rules::skips`]).
if rules.skips(n) {
return false;
}
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
let _off = DrawnOff::set();
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false));
}
match &n.kind {
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
@@ -2283,25 +2312,41 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
c.visible
&& !shaper_hides(n, i, scope)
&& if i == 0 && n.clips() {
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline)))
|| clip_edge_touches(c, r, outline)
} else {
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
inner.is_some_and(|r| touches(c, s, r, scope, rules, outline))
}
})
}
NodeKind::Compound { children, .. } if whole_compounds => {
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
NodeKind::Compound { children, .. } if rules.whole_compounds => {
// Guide contours left out ([`Rules::skips`]) don't make the compound a candidate.
children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
}
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)),
// A symbol instance is touched by its box, and outside it where the live geometry
// effects of a clipping path in its art show the art. In the art of another instance
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
// effects of a clipping path in its art show the art, or where the geometry effects of
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
// instance walked outside that instance's box, it is touched only by its own art
// ([`ArtOnly`]) and those shapes.
NodeKind::SymbolInstance { .. } => {
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r))
}
// An image is touched by its box, and outside it where its own fills and strokes paint.
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
_ => box_touches(n, s, r),
}
}
/// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol
/// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is
/// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when
/// `r` meets the reach of `n` ([`Node::reach_bounds_with`]).
fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
n.reach_bounds_with(s).is_some_and(meets)
&& image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r))
}
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
/// a symbol that draws a straight line) is touched where the marquee crosses it.
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
@@ -2315,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
@@ -2332,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let _art_only = ArtOnly::set();
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false))
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
let outline = outline || previews_off(n);
// The members that the art its own geometry effects draw touches, and a group whose
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
if let Some(drawn) = touched_in_art(n, s, r, rules, outline) {
if drawn.contains(&n.id) && !n.is_layer() {
out.push(n.id);
}
@@ -2355,18 +2400,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
if i == 0 && n.clips() {
let before = out.len();
if let Some(r) = mask_marquee(n, r) {
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
plain(true, || collect_leaves(c, s, r, scope, rules, outline, out));
}
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
out.push(c.id);
}
} else if let Some(r) = inner {
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
collect_leaves(c, s, r, scope, rules, outline, out);
}
}
}
_ => {
if touches(n, s, r, scope, whole_compounds, outline) {
if touches(n, s, r, scope, rules, outline) {
out.push(n.id);
}
}
@@ -2401,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
if leaves {
let before = out.len();
if let Some(r) = r {
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
collect_leaves(t, &symbols, r, scope, rules, outline, &mut out);
}
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
out.push(t.id);
}
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
{
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) {
out.push(t.id);
}
}
+67 -5
View File
@@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang
// So with a marquee across the art's left edge: in the view, only in Outline view. The
// clipping path's own left edge lies there too, and counts in both.
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]);
// `marquee_in` measures by the plain shapes, as its callers clip by them.
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
// Hidden, the effect no longer moves the region.
@@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
for leaves in [false, true] {
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art");
assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place");
}
}
@@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() {
assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None);
}
/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at
/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group,
/// with leaves or without. The group's other members still take it, and with the guides unlocked
/// the guide does.
#[test]
fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let guide = |d: &mut Document, r: Rect| {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
n
};
let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0));
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art());
let (top_id, inner_id, art_id) = (top.id, inner.id, art.id);
let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id());
let nested = Node::group(nested_id, vec![Arc::new(inner)]);
d.insert(Some(l), 0, top).unwrap();
d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap();
let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0));
for leaves in [false, true] {
let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip);
assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}");
assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}");
assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}");
assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}");
// Unlocked: the guides are touched.
assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}");
assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}");
}
// An enclosing loop's candidates leave them out alike.
assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty());
assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]);
}
/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all
/// locked or hidden guides, as the marquee does.
#[test]
fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let part = |d: &mut Document, r: Rect| {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
Arc::new(n)
};
let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0)));
let id = d.alloc_id();
let mut compound = Node::group(id, vec![]);
compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() };
d.insert(Some(l), 0, compound).unwrap();
let r = Rect::new(0.0, 0.0, 60.0, 60.0);
assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden");
assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked");
}
/// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only
/// while those shapes can be clicked (Construction mode, with them isolated), however deep it
/// lies in them.
@@ -2674,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
assert!(marquee(&d, past, None, false).is_empty());
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view");
}
// Preview off for the layer the instance is on.
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
+2 -1
View File
@@ -17,6 +17,7 @@ pub mod corners;
pub mod decode;
pub mod depth;
pub mod dimension;
pub mod flare;
pub mod graph;
mod halftone_radii;
pub mod hit;
@@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use stored_art::{StoredPlace, StoredRoot};
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Document {
+1
View File
@@ -271,6 +271,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
.as_deref()
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
+4
View File
@@ -41,6 +41,9 @@ pub struct NodeExtras {
/// Dimension object: the live measurement it draws; its ordinary group children hold its
/// exportable appearance (Object › Dimensions, the Dimension tool).
pub dimension: Option<Box<crate::dimension::Dimension>>,
/// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group
/// children hold its art.
pub flare: Option<Box<crate::flare::FlareSpec>>,
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
/// filled non-zero) where this object is drawn over the group's other members.
pub intertwine: Option<Box<PathData>>,
@@ -100,6 +103,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
slice: None,
perspective: None,
dimension: None,
flare: None,
intertwine: None,
intertwine_tiers: Vec::new(),
live_paint_gaps: None,
+42
View File
@@ -90,6 +90,42 @@ impl Node {
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
}
/// This object without the paths made into guides among the members of its groups, layers,
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
/// its structure. `None` when it holds no such guide.
pub fn without_guides(&self) -> Option<Node> {
let (NodeKind::Layer { children, .. }
| NodeKind::Group { children, .. }
| NodeKind::Intertwine { children }
| NodeKind::Compound { children, .. }) = &self.kind
else {
return None;
};
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
let mut changed = false;
let mut out = Vec::with_capacity(children.len());
for (i, c) in children.iter().enumerate() {
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
changed = true;
} else if let Some(stripped) = c.without_guides() {
changed = true;
out.push(Arc::new(stripped));
} else {
out.push(c.clone());
}
}
if !changed {
return None;
}
let mut n = self.clone();
if let Some(c) = n.children_mut() {
*c = out;
}
Some(n)
}
/// A template layer (Layer Options → Template).
pub fn is_template(&self) -> bool {
matches!(self.kind, NodeKind::Layer { template: true, .. })
@@ -484,6 +520,12 @@ impl Node {
{
dimension.transform(a);
}
// So does a flare's center and end point.
if let Some(e) = self.extras_if_any()
&& let Some(flare) = &mut e.flare
{
flare.transform(a);
}
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
if !self.is_layer() {
+5
View File
@@ -45,6 +45,7 @@ impl Serialize for Node {
is_default(&self.bbox_angle),
e.perspective.is_none(),
e.dimension.is_none(),
e.flare.is_none(),
e.intertwine.is_none(),
e.intertwine_tiers.is_empty(),
e.live_paint_gaps.is_none(),
@@ -91,6 +92,7 @@ impl Serialize for Node {
field!("bbox_angle", &self.bbox_angle);
field!("perspective", &e.perspective);
field!("dimension", &e.dimension);
field!("flare", &e.flare);
field!("intertwine", &e.intertwine);
field!("intertwine_tiers", &e.intertwine_tiers);
field!("live_paint_gaps", &e.live_paint_gaps);
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
#[serde(default)]
dimension: Option<Box<crate::dimension::Dimension>>,
#[serde(default)]
flare: Option<Box<crate::flare::FlareSpec>>,
#[serde(default)]
intertwine: Option<Box<PathData>>,
#[serde(default, deserialize_with = "counted_list")]
intertwine_tiers: Vec<PathData>,
@@ -271,6 +275,7 @@ impl From<NodeWire> for Node {
slice: w.slice,
perspective: w.perspective,
dimension: w.dimension,
flare: w.flare,
intertwine: w.intertwine,
intertwine_tiers: w.intertwine_tiers,
live_paint_gaps: w.live_paint_gaps,
+17
View File
@@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
}
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
/// as in an exported file. `None` for a language not in the list.
pub fn language_tag(language: &str) -> Option<&'static str> {
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
}
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
/// first entry); `Err` for a language not in the list.
@@ -404,6 +411,16 @@ impl DocSetup {
mod tests {
use super::*;
/// A document's language is written by its tag, the default's included (#3644).
#[test]
fn document_languages_have_their_tags() {
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
assert_eq!(language_tag("French"), Some("fr"));
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
}
/// Characters store a language of the list by its tag, the default as none.
#[test]
fn char_languages_are_stored_by_tag() {
+52
View File
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
}
}
/// Every node whose id is in `ids`, by walking the tree.
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
let mut out = vec![];
d.walk(|n| {
if ids.contains(&n.id) {
out.push(n as *const Node);
}
});
out
}
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
/// walk).
#[test]
fn nodes_in_order_match_a_walk() {
for seed in 1..40 {
let (d, ids) = tree(seed);
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
for cold in [true, false] {
if cold {
d.drop_lookup_cache();
} else {
d.node(ids[0]);
}
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
}
}
// An id that the tree repeats: every node with it.
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
// A second node given an id once held once, after the cache was built: the lookup finds the
// cached node, which has that id; with the cache built afresh, both.
let mut d = d;
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
let Some(once) = once else { continue };
d.node(once);
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
ch.insert(0, copy);
}
let found = d.nodes_in_order([once]);
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
d.drop_lookup_cache();
d.node(once);
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
}
}
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
/// node it is in, appears in the tree once.
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
+49 -1
View File
@@ -94,11 +94,59 @@ fn a_very_long_expression_reads_as_nothing() {
}
}
/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x`
/// right after a `p` stays the `px` unit.
#[test]
fn x_is_a_multiplication_sign() {
let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54);
for (u, s, want) in [
(Unit::Points, "10x2", 20.0),
(Unit::Points, "10 x 2", 20.0),
(Unit::Points, "10X2", 20.0),
(Unit::Points, "10×2", 20.0),
(Unit::Points, "10x-2", -20.0),
(Unit::Points, "10/2x5", 25.0),
(Unit::Points, "1+2x3", 7.0),
(Unit::Millimeters, "2x3 mm", 6.0 * mm),
(Unit::Points, "2x3mm", 6.0 * mm),
(Unit::Points, "3mm x 2", 6.0 * mm),
(Unit::Centimeters, "3cmx50%", 1.5 * cm),
(Unit::Points, "2p x 2", 48.0),
(Unit::Points, "10px", 10.0),
(Unit::Points, "2px x 3", 6.0),
(Unit::Points, "2pxx3", 6.0),
(Unit::Millimeters, "4x3 px", 12.0),
// Only a lowercase x after a p is the px suffix.
(Unit::Points, "2pX3", 72.0),
(Unit::Points, "2p×3", 72.0),
// Text that used to be refused now reads as a product.
(Unit::Points, "8.5x11 in", 93.5 * 72.0),
(Unit::Points, "0x10", 0.0),
] {
let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`"));
assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}");
}
for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] {
assert_eq!(Unit::Points.parse(s), None, "{s}");
}
assert_eq!(crate::parse_number("45x2"), Some(90.0));
assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0));
assert_eq!(crate::parse_number("45×2"), Some(90.0));
assert_eq!(crate::parse_number("90x-1"), Some(-90.0));
assert_eq!(crate::parse_number("x"), None);
// Each sign counts toward the 128-sign limit as a `*` would.
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0));
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None);
assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None);
assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7);
assert_eq!(crate::arithmetic_signs("2px x 3"), 1);
}
proptest! {
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
/// or as nothing and does not panic.
#[test]
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") {
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") {
for u in Unit::ALL {
if let Some(v) = u.parse(&s) {
prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}");
+51 -5
View File
@@ -157,12 +157,17 @@ impl Unit {
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
/// percentage on its own (`50%`) reads as nothing.
///
/// Text with more than 128 `+ - * /` signs reads as nothing.
/// `x`, `X` and `×` multiply as `*` does (`10x2` is 20, `2x3 mm` is 6 mm), except a lowercase
/// `x` right after a `p`, which is the `px` suffix (`2px x 3` is 6 px, and `2px3` reads as
/// nothing; write `2p x 3` for picas). `X` and `×` after a `p` multiply (`2pX3` is 6 picas).
///
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
/// as `*`) reads as nothing.
pub fn parse(self, s: &str) -> Option<f64> {
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
return None;
}
parse_measure(s, self).filter(|v| v.is_finite())
parse_measure(&times_as_asterisks(s), self).filter(|v| v.is_finite())
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
@@ -215,6 +220,46 @@ impl Unit {
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
const MAX_MEASURE_OPERATORS: usize = 128;
/// The number of `+ - * /` signs in `s`, each multiplication sign typed as `x`, `X` or `×`
/// ([`Unit::parse`]) counted as a `*`.
pub fn arithmetic_signs(s: &str) -> usize {
let mut prev = None;
s.chars()
.filter(|&c| {
let sign = matches!(c, '+' | '-' | '*' | '/') || is_times(c, prev);
prev = Some(c);
sign
})
.count()
}
/// Is `c`, after `prev`, a multiplication sign typed as `x`, `X` or `×`? A lowercase `x` right
/// after a `p` is the `px` suffix (`2px x 3`), also where a number follows it (`2px3`).
fn is_times(c: char, prev: Option<char>) -> bool {
matches!(c, 'X' | '×') || (c == 'x' && prev != Some('p'))
}
/// `s` with each multiplication sign ([`is_times`]) written as `*` (`10 x 2` is `10 * 2`); text
/// without one is not copied.
fn times_as_asterisks(s: &str) -> std::borrow::Cow<'_, str> {
let mut prev = None;
let any = s.chars().any(|c| {
let times = is_times(c, prev);
prev = Some(c);
times
});
if !any {
return s.into();
}
let mut out = String::with_capacity(s.len());
let mut prev = None;
for c in s.chars() {
out.push(if is_times(c, prev) { '*' } else { c });
prev = Some(c);
}
out.into()
}
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
let s = s.trim();
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
@@ -348,9 +393,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool {
}
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
/// nothing.
pub fn parse_number(s: &str) -> Option<f64> {
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) {
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
return None;
}
// A leading `+` is a sign (`+5`), as a plain number read it.
+30
View File
@@ -312,6 +312,36 @@ impl Carry {
}
}
/// Undo the actual maps of already placed gradients. Failure only changes this temporary
/// appearance; callers retain the stored row unchanged when a map cannot be inverted.
pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> {
for step in self.0.iter().rev() {
for item in &mut ap.items {
if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) {
continue;
}
let map = match *step {
CarryStep::Affine { m, .. } => m,
CarryStep::Boxes { from, to } => match item {
AppearanceItem::Fill(_) => crate::reshape::box_map(from, to),
AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)),
},
};
if vectorcraft_doc::node::flattens(map) {
return None;
}
let inverse = map.inverse();
if !inverse.is_finite() {
return None;
}
if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() {
g.transform(inverse);
}
}
}
Some(())
}
pub(crate) fn push(&mut self, more: Carry) {
self.0.extend(more.0);
self.1.extend(more.1);
+79 -25
View File
@@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
take_held_guides(n, held, out, false, false);
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
struct PreparedContainer {
m: Node,
guides: Vec<Arc<Node>>,
paint: bool,
carry: crate::Carry,
}
/// The existing container pass up to its own rows becoming art. Keep its carried appearance for
/// rendering, and retain the same Carry for freezing only missing stored placements separately.
fn prepare_container(doc: Option<&Document>, n: &Node) -> Option<PreparedContainer> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let pathfinder = has_pathfinder(n);
let fx = crate::reshape::geometry_effects(n);
let paint = has_own_paint(n);
@@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
return None;
}
let mut m = n.clone();
let mut carry = crate::Carry::default();
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
// that replace or copy the art, so do its guides among the art and those in its sublayers and
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
@@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut m);
}
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
@@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
Some(PreparedContainer { m, guides, paint, carry })
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
if paint {
// A clip group whose clipping type paints strokes is now a group of a clip group and those
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
@@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
Some(m)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
/// The exact pre-copy source shared by rendering and stored gradient placement.
fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec<Arc<Node>>, Node) {
let mut m = n.clone();
let mut guides = vec![];
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
@@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut source);
}
(m, guides, source)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let (mut m, guides, source) = copied_container_source(doc, n, t);
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
let mut p = source.clone();
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
@@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
m
}
/// Freeze representable fitted own paints to the box the container pass gives them, retaining
/// every live effect and already explicit placement. Hidden-only containers the pass does not
/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`.
pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option<Appearance> {
if !n.appearance.has_unplaced_gradient() {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
let (_, _, source) = copied_container_source(Some(doc), n, t);
let pinned = pinned_container_appearance(doc, &source)?;
let mut out = (*n.appearance).clone();
out.items = pinned.items;
return Some(out);
}
let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?;
let bounds = m.geometric_bounds()?;
let mut out = (*n.appearance).clone();
let mut changed = false;
for (item, original) in out.items.iter_mut().zip(&n.appearance.items) {
if paints(original)
&& matches!(original.paint(), Paint::Gradient(g) if !g.is_placed())
&& let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry])
{
*item = pinned;
changed = true;
}
}
changed.then_some(out)
}
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
+3 -1
View File
@@ -45,6 +45,7 @@ mod lighting_presets;
mod live;
mod marks;
pub mod pixel;
mod placement;
pub mod preview;
mod raster;
mod reshape;
@@ -75,12 +76,13 @@ pub use bake::{
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
};
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
+74
View File
@@ -0,0 +1,74 @@
//! Conservative stored placements for gradients fitted by the existing effects passes.
use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem};
use vectorcraft_geom::Rect;
use crate::Carry;
/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects.
/// `carries` are the actual object and item passes, in rendering order. Only missing placement
/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or
/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted.
pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option<AppearanceItem> {
if gradient(item)?.is_placed() {
return Some(item.clone());
}
if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) {
return None;
}
let resolved = resolve(item, bounds, carries);
if !finite_placement(resolved.items.first()?) {
return None;
}
let mut stored = resolved.clone();
for carry in carries.iter().rev() {
carry.unapply_placed(&mut stored)?;
}
if !finite_placement(stored.items.first()?) {
return None;
}
let candidate = missing_placement(item, stored.items.first()?)?;
let replayed = resolve(&candidate, bounds, carries);
(finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate)
}
fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> {
match item.paint() {
Paint::Gradient(g) => Some(g),
_ => None,
}
}
fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance {
let mut ap = Appearance { items: vec![item.clone()], ..Default::default() };
for carry in carries {
carry.apply(&mut ap);
}
ap.pin_gradients(bounds);
ap
}
fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option<AppearanceItem> {
let original = gradient(item)?;
let placed = gradient(placed)?;
let mut out = item.clone();
let Paint::Gradient(g) = out.paint_mut() else { return None };
if original.geom.is_none() {
g.geom = placed.geom;
}
if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() {
let freeform = placed.freeform.as_ref()?;
match &mut g.freeform {
Some(f) => f.points.clone_from(&freeform.points),
None => g.freeform = Some(freeform.clone()),
}
}
Some(out)
}
fn finite_placement(item: &AppearanceItem) -> bool {
let Some(g) = gradient(item) else { return false };
g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite()))
&& g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite()))
}
+1 -1
View File
@@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) {
/// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent
/// on, a move from its center to `to`'s).
fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
let axis = |a0: f64, a1: f64, b0: f64, b1: f64| {
if (a1 - a0).abs() > 1e-12 {
let s = (b1 - b0) / (a1 - a0);
+16 -2
View File
@@ -32,6 +32,7 @@ pub mod expand;
pub(crate) mod fileinfo;
pub mod fileio;
pub mod findfiles;
pub mod flare;
pub mod flatten;
pub mod fontfiles;
mod fonts;
@@ -74,6 +75,7 @@ pub mod perspgrid;
pub mod place;
pub mod plugin;
pub(crate) mod plugin_call;
mod preflight;
pub mod prefscmds;
pub mod print;
pub(crate) mod printadvanced;
@@ -98,12 +100,13 @@ pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
mod textedit;
mod xmlattrs;
pub use textedit::effective_kerning;
mod retype;
pub mod textstyles;
pub(crate) mod textwrap;
pub(crate) mod threads;
pub mod toast;
pub(crate) mod typecmd;
mod typemenu;
mod variablecmds;
@@ -321,6 +324,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(pathops::specs());
v.extend(compoundshape::specs());
v.extend(typecmd::specs());
v.extend(retype::specs());
v.extend(menucmds::specs());
v.extend(live::specs());
v.extend(colorcmds::specs());
@@ -333,6 +337,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(compositefonts::specs());
v.extend(fontfiles::specs());
v.extend(help::specs());
v.extend(toast::specs());
v.extend(threads::specs());
v.extend(textwrap::specs());
v.extend(graph::specs());
@@ -382,6 +387,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(package::specs());
v.extend(slices::specs());
v.extend(print::specs());
v.extend(preflight::specs());
v.extend(recovery::specs());
v.extend(fileio::dxfimport::specs());
v.extend(webexport::specs());
@@ -840,6 +846,8 @@ pub use docmenu::guide_indexes;
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
@@ -872,10 +880,14 @@ pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs,
/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs).
pub use compoundshape::selected_member_modes;
/// Make Compound Shape's warning when a member is an open path that encloses no area.
pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
/// Pathfinder Options (`Prefs::pathfinder`).
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
/// The Attributes panel's state ([`Session::attributes_info`]).
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
pub use attributes::RECENT_URLS;
pub use overprint::AttributesInfo;
/// Object → Flatten Transparency settings (`object.flattenTransparency`).
@@ -899,6 +911,8 @@ pub(crate) use buildcmds::TracePresetChanges;
/// The shapes a group selected alone gives the Pathfinder panel.
pub use pathops::shape_count;
/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them).
pub use menucmds::mosaic_counts;
/// The Shape Mode commands' warning when a selected open path encloses no area.
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
+110 -41
View File
@@ -1,5 +1,6 @@
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
//! circles, replacing the circles or added above them.
//! circles, or three or more each joined the same way to the others within reach and united where
//! the bridges connect, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
@@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge";
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
const RADIUS: f64 = 100.0;
const RADII: (f64, f64) = (1.0, 1000.0);
/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range.
const GAPS: (f64, f64) = (0.0, 1000.0);
/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between
/// them: by default, and the range.
const REACH: f64 = 10.0;
const REACHES: (f64, f64) = (0.0, 10000.0);
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
has_selection,
bridge
)]
}
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
let percent = given(p, "radius", Some(RADII), C)?;
let gap = given(p, "gap", Some(GAPS), C)?;
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
if percent.is_some() && gap.is_some() {
// As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check.
let (key, other) = ("radius", "gap");
return Err(bad(C, format!("give `{key}` or `{other}`, not both")));
}
let arc = match gap {
Some(gap) => pt::ArcRadius::Gap(gap),
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
};
let keep = switch_or(p, "keepOriginals", false, C)?;
let roots = checked_ids_or_selection(s, p, C)?;
let mut roots = checked_ids_or_selection(s, p, C)?;
// An id given twice is one circle.
roots.sort_unstable();
roots.dedup();
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
return Err(bad(C, "select at most 2000 circles to bridge"));
}
let circles: Vec<(NodeId, pt::Circle)> = {
let d = &s.doc()?.doc;
let editable = d.editable();
@@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
})
.collect()
};
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
return Err(bad(C, "select two circles to bridge"));
};
let (below, above) = (*below, *above);
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
let outline = match at(percent) {
Ok(sp) => PathData::single(sp),
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
if circles.len() != roots.len() || circles.len() < 2 {
return Err(bad(C, "select two or more circles to bridge"));
}
let only: Vec<pt::Circle> = circles.iter().map(|(_, c)| *c).collect();
// Each shape: the circles it joins, in paint order, and its outline.
let (shapes, alone): (Vec<(Vec<NodeId>, PathData)>, Vec<NodeId>) = match only.as_slice() {
[a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) {
Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]),
Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())),
},
_ => {
let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e {
pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"),
pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"),
pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"),
pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"),
// Under the many-circle rules: a pair the largest radius or gap bridges on its own
// can still have a neck too thin to unite among the others.
pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)),
pt::ManyError::Bad => bad(C, "select two or more circles to bridge"),
})?;
let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect();
(shapes, roots_of(&circles, &made.alone))
}
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
};
let id = s.edit(LABEL, |d, sel| {
let id = if keep {
// A copy of the upper circle (its appearance) with the outline as its path, right above
// it; the circles stay as they are, live shapes included.
// Fresh ids throughout, its opacity mask's art included.
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
let mut n = d.reid(&upper);
if let NodeKind::Path { path, live, .. } = &mut n.kind {
*path = outline;
*live = None;
let made = s.edit(LABEL, |d, sel| {
let mut made = Vec::with_capacity(shapes.len());
if keep {
// A copy of each shape's topmost circle (its appearance) with the outline as its path,
// right above it; the circles stay as they are, live shapes included. Fresh ids
// throughout, an opacity mask's art included.
let tops: Vec<NodeId> = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect();
let mut beside = Beside::above(d, &tops);
for ((_, outline), top) in shapes.into_iter().zip(tops) {
let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?;
let mut n = d.reid(&upper);
if let NodeKind::Path { path, live, .. } = &mut n.kind {
*path = outline;
*live = None;
}
made.push(n.id);
beside.put(d, top, vec![n])?;
}
let id = n.id;
let mut beside = Beside::above(d, &[above]);
beside.put(d, above, vec![n])?;
beside.finish(d)?;
id
} else {
// The upper circle becomes the outline (a plain path now) and the lower one goes.
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
*path = outline;
*live = None;
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
let mut gone = vec![];
for (members, outline) in shapes {
let Some((&top, rest)) = members.split_last() else { continue };
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) {
*path = outline;
*live = None;
}
made.push(top);
gone.extend_from_slice(rest);
}
remove_each(d, &[below])?;
above
};
sel.set([id]);
Ok(id)
remove_each(d, &gone)?;
}
sel.set(made.iter().chain(&alone).copied());
Ok(made)
})?;
Ok(json!({ "id": id.0 }))
let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::<Vec<_>>(), "alone": alone.iter().map(|id| id.0).collect::<Vec<_>>() });
if let ([id], 2) = (made.as_slice(), only.len()) {
out["id"] = json!(id.0);
}
Ok(out)
}
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
}
/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a
/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would.
fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError {
let largest = match arc {
pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0),
pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1),
};
let would = e == pt::BridgeError::TooFar && bridges(largest);
match (e, arc, would) {
(pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"),
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"),
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"),
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"),
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"),
(pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"),
}
}
@@ -1,5 +1,5 @@
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
//! and what it refuses.
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or
//! gap, many circles joined to their neighbors within reach, and what it refuses.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
@@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() {
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute(BRIDGE, &json!({})).unwrap();
assert_eq!(r["id"], json!(b.0));
assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles");
assert_eq!(r["alone"], json!([]));
assert_eq!(top_level(&s), [b]);
let d = &s.doc().unwrap().doc;
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
@@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() {
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
}
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] {
assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}");
}
// Three circles: each two within reach are bridged, and one inside another is refused there too.
assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
@@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
fn grid(s: &mut Session) -> Vec<NodeId> {
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
}
fn ids(v: &Value) -> Vec<NodeId> {
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
}
#[test]
fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() {
let mut s = session();
let g = grid(&mut s);
select(&mut s, &g);
let steps = s.doc().unwrap().history.undo.len();
// Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not.
let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap();
assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place");
assert_eq!(ids(&r["alone"]), []);
assert_eq!(top_level(&s), [g[8]]);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
// Its outline and a hole in each square of four circles, which no diagonal bridge fills.
let outline = path(&s, g[8]);
assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len());
let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0;
assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(top_level(&s), g);
// Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square.
select(&mut s, &g);
s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap();
let outline = path(&s, g[8]);
assert_eq!(outline.subpaths.len(), 1);
assert!(inside(&outline, 112.0, 112.0));
}
#[test]
fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() {
let mut s = session();
let g = grid(&mut s);
let far = circle(&mut s, 300.0, 250.0, 10.0);
let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)];
let mut all = g.clone();
all.extend([far, pair[0], pair[1]]);
let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::<Vec<_>>(), "reach": 5})).unwrap();
assert_eq!(ids(&r["ids"]), [g[8], pair[1]]);
assert_eq!(ids(&r["alone"]), [far]);
assert_eq!(top_level(&s), [g[8], far, pair[1]]);
assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched");
let mut selected = s.doc().unwrap().selection.objects.to_vec();
selected.sort();
let mut want = vec![g[8], pair[1], far];
want.sort();
assert_eq!(selected, want, "the shapes and the circle left alone");
}
#[test]
fn keep_originals_adds_each_shape_above_its_topmost_circle() {
let mut s = session();
let row: Vec<NodeId> = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect();
let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)];
s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap();
let all: Vec<u64> = row.iter().chain(&other).map(|i| i.0).collect();
let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap();
let made = ids(&r["ids"]);
assert_eq!(made.len(), 2);
assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]);
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle");
let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap();
assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}");
}
#[test]
fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() {
let area_with = |p: Value| {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 10.0);
let b = circle(&mut s, 124.0, 100.0, 10.0);
let mut p = p;
p["ids"] = json!([a.0, b.0]);
let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap());
area(&s, id)
};
// Radius 10 plus a gap of 4 is 140% of 10.
let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140})));
assert!((gap - percent).abs() < 1e-9, "{gap} {percent}");
assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20})));
}
#[test]
fn many_circle_and_gap_refusals() {
let mut s = session();
let a = circle(&mut s, 50.0, 100.0, 10.0);
let b = circle(&mut s, 250.0, 100.0, 10.0);
let c = circle(&mut s, 330.0, 100.0, 10.0);
let far = circle(&mut s, 380.0, 100.0, 10.0);
let before = top_level(&s);
let steps = s.doc().unwrap().history.undo.len();
assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both"));
// Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers
// 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010)
// ≈ 285.
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap"));
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach"));
// b and c are 60 apart: within a reach of 100, but too far for the default radius.
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius"));
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000"));
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000"));
assert_eq!(top_level(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
#[test]
fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() {
let mut s = session();
// Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but
// with a neck about 0.0007 pt wide, too thin to unite among three or more circles.
let a = circle(&mut s, 20.0, 100.0, 10.0);
let b = circle(&mut s, 111.65, 100.0, 10.0);
let far = circle(&mut s, 380.0, 100.0, 10.0);
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok());
s.execute("edit.undo", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius"));
for radius in [100, 1000] {
let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100}));
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
}
}
#[test]
fn too_many_circles_or_bridges_are_refused() {
let mut s = session();
// 130 overlapping circles in a row: 8,385 pairs within reach.
let row: Vec<u64> = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect();
assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach"));
let many: Vec<u64> = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect();
assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge"));
}
#[test]
fn an_id_given_twice_is_one_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap();
assert_eq!(r["id"], json!(b.0), "two circles, bridged");
assert_eq!(top_level(&s), [b]);
}
#[test]
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
let mut s = session();
// Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b,
// within the default reach of 10).
let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0));
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
assert_eq!(ids(&r["ids"]), [b]);
assert_eq!(ids(&r["alone"]), [c]);
assert_eq!(top_level(&s), [b, c]);
}
#[test]
fn locked_and_hidden_circles_are_not_bridged() {
let mut s = session();
@@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() {
let b = circle(&mut s, 150.0, 100.0, 20.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
s.execute("object.unlockAll", &json!({})).unwrap();
select(&mut s, &[a]);
s.execute("object.hide", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
}
@@ -1,7 +1,8 @@
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
//! crossing into either, added as separate open paths, with the line joining their centers if
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
#[cfg(test)]
mod tests;
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Common Tangents",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
has_selection,
common_tangents
)]
}
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
/// else the path's one closed convex subpath.
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
const C: &str = COMMON_TANGENTS;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
if sp.anchors.len() == 1
&& let Some(only) = sp.anchors.first()
{
return pt::Outline::point(only.p).map_err(refusal);
}
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
let span = (pie.1 - pie.0).rem_euclid(360.0);
if span < 1e-9 || 360.0 - span < 1e-9 {
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
let ordered = d.paint_order(roots.iter().copied());
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
if a.is_point() && b.is_point() {
return Err(bad(C, "select two closed paths"));
}
// A point goes first, so that each line runs from it to where it touches the path.
let point = a.is_point() || b.is_point();
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
let keep = |t: &&pt::Tangent| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
// A point's external and internal tangents are the same lines: every kind keeps them.
let keep = |t: &&pt::Tangent| {
point
|| match kinds {
"external" => t.kind == pt::TangentKind::External,
"internal" => t.kind == pt::TangentKind::Internal,
_ => true,
}
};
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
let (external_kept, internal_kept) = match (point, kinds) {
(true, "internal") => (0, kept.len()),
(true, _) => (kept.len(), 0),
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
};
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
if lines.is_empty() && point {
// Written as `EngineError::Other` so that the i18n message scan finds it.
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
if lines.is_empty() {
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
// external tangent means one path lies inside the other and touches it there; paths that
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
}
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
}
#[test]
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
let mut s = session();
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
let dot = point(&mut s, 100.0, 200.0);
select(&mut s, &[oval, dot]);
let before = steps(&s);
let r = s.execute(C, &json!({"centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
assert_eq!(steps(&s), before + 1);
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
for sy in [1.0, -1.0] {
let touch = c + Vec2::new(-8.0, sy * y);
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
}
assert_eq!(r["centerline"], r["ids"][2]);
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
// Every `tangents` value gives the same two lines.
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
}
}
#[test]
fn a_point_below_the_path_still_starts_the_lines() {
let mut s = session();
// The point is drawn first, so it is the lower object and needs no swap.
let dot = point(&mut s, 100.0, 200.0);
let round = circle(&mut s, 300.0, 200.0, 50.0);
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
let found = lines(&s, &r);
assert_eq!(found.len(), 3, "two tangents and the centerline");
let p = Point::new(100.0, 200.0);
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
}
#[test]
fn a_point_on_or_inside_a_path_and_two_points() {
let mut s = session();
let round = circle(&mut s, 200.0, 200.0, 50.0);
// On the circle: one line, centered on the point and as long as the circle is wide.
let on = point(&mut s, 250.0, 200.0);
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
let (p, q) = lines(&s, &r)[0];
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
// Inside: nothing changes, and the warning says why.
let inside = point(&mut s, 210.0, 190.0);
let before = (steps(&s), s.doc().unwrap().doc.node_count());
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
assert_eq!(r["ids"], json!([]));
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
// Two points, or a point and an open path, are refused.
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
}
#[test]
fn bad_selections_and_params_are_refused() {
let mut s = session();
+6 -6
View File
@@ -10,7 +10,7 @@
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
use vectorcraft_render::effects;
use super::super::{CommandSpec, always, bad, cmd, has_selection};
@@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize";
const SHOWN_CHARS: usize = 64;
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
const MAX_TEXT_LEN: usize = 1024;
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
/// level of recursion per sign.
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign
/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign.
const MAX_OPERATORS: usize = 128;
pub fn specs() -> Vec<CommandSpec> {
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Units",
[],
None,
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
always,
convert
),
@@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
}
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
/// signs?
/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])?
fn readable(s: &str) -> bool {
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS
}
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
@@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() {
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
// A sum of 128 signs still reads.
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
// x, X and × multiply as * does, and each counts toward the 128 signs.
assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4));
assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0));
assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0));
assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0));
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
}
#[test]
+4 -3
View File
@@ -12,8 +12,9 @@ use super::overprint::{AttributesInfo, apply_overprint, edit_counted, overprint_
use super::path::paths_in;
use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, str_param, targets};
/// How many URLs the Attributes panel's recent list keeps.
const RECENT_URLS: usize = 10;
/// How many URLs the Attributes panel's recent list keeps: the most its Panel Options lets the
/// URL menu list.
pub const RECENT_URLS: usize = 30;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -22,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attributes",
[],
None,
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info, newest first, at most 30) → {changed: objects}",
has_doc,
set
),
+93 -1
View File
@@ -12,7 +12,8 @@ use std::sync::{Arc, LazyLock};
use serde_json::{Value, json};
use vectorcraft_brush::{
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
self as brush, ArtBrush, ArtScale, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter,
Variation,
};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
@@ -172,6 +173,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
@@ -179,6 +181,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
];
/// Built-in library `id`, made once.
@@ -232,6 +235,54 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush {
art,
scale: ArtScale::BetweenGuides { start, end },
colorization: Colorization::Tints,
..Default::default()
}),
}
}
/// Arrows: original art brushes whose stems stretch while their heads keep their proportions.
fn arrows() -> BrushLibrary {
let shaft = || black(shapes::rectangle(Rect::new(0.0, -1.0, 82.0, 1.0)));
let head = || black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (82.0, 0.0)]));
let solid = group(vec![shaft(), head()]);
let outline = group(vec![shaft(), black(polygon(&[(76.0, -7.0), (100.0, 0.0), (76.0, 7.0), (78.0, 4.0), (91.0, 0.0), (78.0, -4.0)]))]);
let double = group(vec![
black(shapes::rectangle(Rect::new(18.0, -1.0, 82.0, 1.0))),
head(),
black(polygon(&[(24.0, -7.0), (0.0, 0.0), (24.0, 7.0), (18.0, 0.0)])),
]);
let chevrons = group(vec![shaft(), head(), black(polygon(&[(53.0, -5.0), (66.0, 0.0), (53.0, 5.0), (56.0, 0.0)]))]);
let dashed = group(
(0..5)
.map(|i| {
let x = f64::from(i) * 16.0;
black(shapes::rectangle(Rect::new(x, -1.0, x + 10.0, 1.0)))
})
.chain(std::iter::once(head()))
.collect(),
);
built(
"Arrows",
Document::new(100.0, 100.0),
vec![
arrow_art("Solid Arrow", solid, 0.0, 0.76),
arrow_art("Open Arrow", outline, 0.0, 0.76),
arrow_art("Double Arrow", double, 0.24, 0.76),
// The second chevron starts at 53 pt, so only the shaft before it stretches.
arrow_art("Chevron Arrow", chevrons, 0.0, 0.53),
arrow_art("Dashed Arrow", dashed, 0.0, 0.76),
],
)
}
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
/// own pattern, Pinstripes.
fn art_ribbons() -> BrushLibrary {
@@ -374,6 +425,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
}
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
fn pressure_sensitive() -> BrushLibrary {
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
let pulse = group(vec![
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
]);
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush {
art,
width: light,
width_mode: Some(Variation::Pressure),
width_max: Some(heavy),
colorization: Colorization::Tints,
..Default::default()
}),
};
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
name: name.into(),
kind: BrushKind::Calligraphic(Calligraphic {
angle,
roundness,
size,
variation: [0.0, 0.0, variation],
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
}),
};
built(
"Pressure Sensitive",
Document::new(100.0, 100.0),
vec![
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
],
)
}
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
/// blending and texture.
fn bristle_brushes() -> BrushLibrary {
+1 -1
View File
@@ -211,7 +211,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
+12 -2
View File
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
let iso = s.doc()?.isolation;
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
if keep_art {
// The art stays where it is and stays selected, apart from art that is hidden or
// locked, in a hidden or locked group or layer, or on a locked artboard.
let locks = d.locked_artboards();
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
return Ok(None);
}
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
Ok(json!({
"name": name,
"id": id.0,
"id": id.map(|i| i.0),
"registration": reg.0,
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
+1 -1
View File
@@ -38,7 +38,7 @@ mod shape_builder;
mod trace;
pub use live_paint::live_paint_gaps;
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
+241 -12
View File
@@ -1,8 +1,8 @@
use super::{
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
switch_or,
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
source_nodes, source_shapes, switch_or,
};
/// `options` as stored on a Live Paint group: none for the defaults.
@@ -74,6 +74,44 @@ fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
}
}
/// Whether a path named `name` directly in a Live Paint group is one of its faces or edges: the
/// name is [`FACE_NAME`] or [`EDGE_NAME`].
fn part_name(name: Option<&str>) -> bool {
matches!(name, Some(FACE_NAME | EDGE_NAME))
}
/// Whether `n` is a path whose parent `parent` is a Live Paint group.
fn path_in_live_paint(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
n.path_data().is_some() && parent.and_then(|p| d.node(p)).is_some_and(is_live_paint)
}
/// Clear the name of `n`, put directly in `parent`, when it is a path named like a face or an edge
/// ([`part_name`]) and `parent` is a Live Paint group, so that the group's other children
/// ([`others_in`]) keep it when its faces and edges are made again. Paste uses it.
pub(crate) fn clear_part_name(d: &Document, parent: Option<NodeId>, n: &mut Node) {
if part_name(n.name.as_deref()) && path_in_live_paint(d, parent, n) {
n.name = None;
}
}
/// Refuse naming rows `ids` `name` when it is the name of a face or an edge ([`part_name`]) and one
/// of them is a path directly in a Live Paint group that is not named `name` already. Checked
/// before anything changes.
pub(crate) fn check_part_name(d: &Document, ids: &[NodeId], name: &str) -> Result<()> {
if !part_name(Some(name)) {
return Ok(());
}
for id in ids {
if let Some(n) = d.node(*id)
&& n.name.as_deref() != Some(name)
&& path_in_live_paint(d, d.parent_of(*id), n)
{
return Err(EngineError::Other("`Face` and `Edge` name the faces and edges of a Live Paint group: give the path another name".into()));
}
}
Ok(())
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
@@ -149,11 +187,16 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
check_live_paint_takes(d, roots)?;
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
// The rows that join are children of the group already when Merge runs after a drag, and a joining
// path named like a face or an edge is not one of the group's parts.
let mut old_parts = old.clone();
if let Some(ch) = old_parts.children_mut() {
ch.retain(|c| !roots.contains(&c.id));
}
// Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the
// old edges below.
let keep_faces: Vec<(Point, Carried)> =
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
let old_parts = old.clone();
b::faces(&old_parts).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
let mut sources = source_nodes(&old);
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
let mut others = vec![];
@@ -227,19 +270,22 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
/// The Live Paint groups whose drawn art can be added when isolation mode leaves `isolated`, innermost
/// first: every Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated
/// Live Paint group and then isolated itself, and the group it was drawn in. Empty when `isolated` is
/// not in a Live Paint group.
pub(crate) fn isolated_live_paints(d: &Document, isolated: NodeId) -> Vec<NodeId> {
d.ancestry(isolated).unwrap_or_default().into_iter().rev().filter(|id| d.node(*id).is_some_and(is_live_paint)).collect()
}
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
/// front: the paths drawn in it in isolation mode.
/// front: the paths drawn in it in isolation mode. A Live Paint group's sources group, which is
/// always hidden, does not count.
fn drawn_in(g: &Node) -> Vec<NodeId> {
fn open(n: &Node) -> bool {
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
let src = b::sources(n).filter(|_| is_live_paint(n)).map(|s| s.id);
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().filter(|c| Some(c.id) != src).all(|c| open(c)))
}
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
}
@@ -259,6 +305,189 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<boo
Ok(true)
}
/// Where a row sits for Live Paint: among the paths of a Live Paint group (in its sources group,
/// at any depth), directly in a Live Paint group, or neither.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Spot {
Source(NodeId),
In(NodeId),
Outside,
}
/// The [`Spot`] of a row whose parent is `parent` (None: the top level).
fn spot_in(d: &Document, parent: Option<NodeId>) -> Spot {
let Some(p) = parent else { return Spot::Outside };
for x in d.ancestry(p).unwrap_or_default().into_iter().rev() {
let n = d.node(x);
if n.is_some_and(is_live_paint) {
return if x == p { Spot::In(x) } else { Spot::Outside };
}
if let Some(g) = d.parent_of(x)
&& d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == x)
{
return Spot::Source(g);
}
}
Spot::Outside
}
/// The Live Paint groups that hold Live Paint group `g` among their paths (in their sources group,
/// at any depth), innermost first.
fn enclosing_live_paints(d: &Document, g: NodeId) -> Vec<NodeId> {
let mut out = vec![];
let mut at = g;
while let Spot::Source(o) = spot_in(d, d.parent_of(at)) {
if out.contains(&o) {
break;
}
out.push(o);
at = o;
}
out
}
/// What moving rows in the Layers panel (`layer.move`, `node.move`) does to Live Paint groups.
/// Rows that go into a Live Paint group from elsewhere are added to it as `livePaint.merge` adds
/// paths. Rows that go into or leave a group's paths (its sources group) change those paths, and
/// the group's faces and edges are made again from them, keeping the paint of the faces and edges
/// that stay, and so are those of every Live Paint group that holds a changed group among its
/// paths. Rows moved within one group's paths, or among a group's own children, change no faces.
pub(crate) struct LivePaintMove {
/// The Live Paint group the rows go into, and for each row whether it joins the group's paths.
join: Option<(NodeId, Vec<bool>)>,
/// The Live Paint group the rows go among the children of, with its sources group as it is
/// before the move.
keep_sources: Option<(NodeId, NodeId)>,
/// The Live Paint groups whose paths change.
rebuild: Vec<NodeId>,
}
impl LivePaintMove {
/// Plan moving `rows` (with `copy`, copies of them) into `parent`, before anything changes.
/// Refuses rows Live Paint can't take ([`b::live_paint_takes`]) that would go among a group's
/// paths, with the message Make and Merge give.
pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option<NodeId>, copy: bool) -> Result<Self> {
let to = spot_in(d, parent);
let from: Vec<Spot> = rows.iter().map(|r| if copy { Spot::Outside } else { spot_in(d, d.parent_of(*r)) }).collect();
let mut rebuild = vec![];
for f in &from {
if let Spot::Source(g) = *f
&& *f != to
&& !rebuild.contains(&g)
{
rebuild.push(g);
}
}
if let Spot::Source(g) = to
&& from.iter().any(|f| *f != to)
&& !rebuild.contains(&g)
{
rebuild.push(g);
}
let entering: Vec<NodeId> = rows.iter().zip(&from).filter(|(_, f)| **f != to).map(|(r, _)| *r).collect();
let join = match to {
Spot::In(g) if !entering.is_empty() => Some((g, from.iter().map(|f| *f != to).collect())),
_ => None,
};
if to != Spot::Outside {
check_live_paint_takes(d, &entering)?;
}
let keep_sources = match to {
Spot::In(g) => d.node(g).and_then(b::sources).map(|s| (g, s.id)),
_ => None,
};
Ok(Self { join, keep_sources, rebuild })
}
/// Whether rows join a Live Paint group, which makes the move a "Merge Live Paint" step.
pub(crate) fn joins(&self) -> bool {
self.join.is_some()
}
/// After the rows were moved, now `moved` (in the order [`LivePaintMove::plan`] took them),
/// make the faces and edges of the groups whose paths changed again, and add the rows that
/// joined a group to it. → `moved` with the joined rows replaced by their group, once, and
/// without the faces and edges that were made again.
pub(crate) fn finish(self, d: &mut Document, sel: &mut Selection, moved: &[NodeId]) -> Result<Vec<NodeId>> {
// A moved object named like the sources group may now sit before it, where a lookup by name
// finds the object first. The group's own sources group goes back in front.
if let Some((g, src)) = self.keep_sources {
let ch = d.children_mut(Some(g))?;
if let Some(at) = ch.iter().position(|c| c.id == src)
&& ch[..at].iter().any(|c| c.name.as_deref() == Some(SOURCES_NAME))
{
let s = ch.remove(at);
ch.insert(0, s);
}
}
if self.join.is_none() && self.rebuild.is_empty() {
return Ok(moved.to_vec());
}
// The group the rows join is made again by the merge below, from its paths as they are now
// and with the paint of its faces and edges as they were before the move.
let join_group = self.join.as_ref().map(|(g, _)| *g);
// A Live Paint group among another group's paths gives that group its faces and edges, so
// the groups holding a changed group among their paths are made again too, innermost first.
let mut groups: Vec<NodeId> = vec![];
for g in self.rebuild.iter().copied().chain(join_group) {
for x in std::iter::once(g).chain(enclosing_live_paints(d, g)) {
if !groups.contains(&x) {
groups.push(x);
}
}
}
groups.sort_by_cached_key(|g| std::cmp::Reverse(d.ancestry(*g).map_or(0, |a| a.len())));
let joined: Vec<NodeId> = match &self.join {
Some((_, mask)) => moved.iter().zip(mask).filter(|(_, j)| **j).map(|(r, _)| *r).collect(),
None => vec![],
};
for g in groups {
if Some(g) == join_group {
let roots: Vec<NodeId> = std::iter::once(g).chain(joined.iter().copied()).collect();
merge_live(d, sel, &roots)?;
} else if d.node(g).is_some() {
rebuild_paths(d, g)?;
}
}
let Some((g, mask)) = self.join else { return Ok(moved.iter().copied().filter(|r| d.node(*r).is_some()).collect()) };
// `moved` holds each row once, so only the group can come twice. Faces and edges of the
// group moved along with the joining rows were made again, so they are left out.
let mut out = vec![];
let mut listed = false;
for (r, j) in moved.iter().zip(&mask) {
if *j {
if !listed {
out.push(g);
listed = true;
}
} else if d.node(*r).is_some() {
out.push(*r);
}
}
Ok(out)
}
}
/// Make Live Paint group `g`'s faces and edges again from the paths its sources group holds now,
/// with its Gap Options, carrying over the paint of the faces and edges that stay. With no path
/// left, the group keeps its sources group and its other children, and has no faces or edges.
fn rebuild_paths(d: &mut Document, g: NodeId) -> Result<()> {
let old = d.node(g).cloned().ok_or(EngineError::NoNode(g))?;
let sources = source_nodes(&old);
let mut n = old.clone();
if source_shapes(&sources).0.is_empty() {
let src = b::sources(&old).cloned().ok_or(EngineError::NoNode(g))?;
set_parts(&mut n, vec![src], &[]);
} else {
let (children, _, _) = build_children(d, sources, old.gap_options().max_gap())?;
set_parts(&mut n, children, &[]);
repaint_from(&mut n, &old);
}
let mut changed = Beside::replacing(d, &[g]);
changed.put(d, g, vec![n])?;
changed.finish(d)
}
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids = root_ids(s, p)?;
+46 -2
View File
@@ -8,6 +8,8 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_render::effects;
use super::edit::{roots_of, selected_roots};
@@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi};
const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"];
/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another
/// open path that encloses no area once closed, and so contributes no area to the shape.
pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -23,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Compound Shape",
["Window", "Pathfinder"],
None,
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}",
has_multi,
make
),
@@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
// all have `mode`, the topmost, or the backmost when they all subtract.
let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() };
let hook = |c: &Node| effects::outline_object(Some(d), c);
let no_area = order.iter().any(|n| adds_no_area(d, n, &hook));
let style = order.into_iter().find_map(|n| top_style(d, n, &hook));
let id = s.edit("Make Compound Shape", |d, sel| {
let gid = d.alloc_id();
@@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
let mut out = json!({ "id": id.0 });
if no_area {
out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA);
}
Ok(out)
}
/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes
/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath
/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it
/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd
/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule
/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the
/// warning, as Divide measures it. An area that can't be measured gives no warning.
fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool {
effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| {
let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind {
NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule),
NodeKind::Path { path, rule, .. } => (vec![path], *rule),
_ => return false,
};
let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect();
if subpaths.iter().all(|sp| sp.closed) {
return false;
}
let closed = |sp: &SubPath| {
let mut sp = sp.clone();
sp.closed = true;
sp
};
// An area that can't be measured counts as an area, so a failed measurement gives no warning.
let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0);
subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where
// the signed area is not zero (a contour traced twice).
!(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp)))
}) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect())))
})
}
/// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the
+10 -144
View File
@@ -55,7 +55,16 @@ pub fn specs() -> Vec<CommandSpec> {
None,
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
has_doc,
flare
super::flare::flare
),
cmd!(
"shape.editFlare",
"Edit Flare",
[],
None,
"{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}",
has_doc,
super::flare::edit_flare
),
cmd!(
"shape.circleThroughPoints",
@@ -515,149 +524,6 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
}
/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo
/// ring, rays of varying length and rings along the path to the end point.
fn flare(s: &mut Session, p: &Value) -> Result<Value> {
use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?);
let numbers = [
"diameter",
"opacity",
"brightness",
"growth",
"fuzziness",
"rays",
"longest",
"rayFuzziness",
"rotation",
"rings",
"largest",
"x2",
"y2",
"direction",
"pathLength",
"seed",
"ringSeed",
];
check_numbers(p, &numbers, "shape.flare")?;
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5);
let opacity = pct("opacity", 50.0).min(1.0) as f32;
let brightness = pct("brightness", 30.0).min(1.0) as f32;
let growth = pct("growth", 20.0);
let fuzz = pct("fuzziness", 50.0).min(1.0);
let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize;
let longest = pct("longest", 300.0);
let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0);
let ray_turn = f64_or(p, "rotation", 0.0).to_radians();
let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize;
let largest = pct("largest", 50.0);
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
(Some(x), Some(y)) => Point::new(x, y),
_ => {
let a = f64_or(p, "direction", 45.0).to_radians();
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
}
};
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
// along the path from a sequence of its own; their count and sizes and the other parts stay.
let seed_of = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
};
// Xorshift64. Both streams start from a nonzero state.
let random = |mut state: u64| {
move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
}
};
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
let ring_seed = match seed_of("ringSeed")? {
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
r => r,
};
let mut ring_at = ring_seed.map(|r| {
// SplitMix64 initializes the ring-position stream.
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
random(z ^ (z >> 31))
});
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
Paint::Gradient(Box::new(g))
};
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![];
// Halo: a soft ring just outside the centre.
let halo_r = r * (1.0 + growth) * 1.6;
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
// `rotation` turns them clockwise about the center.
if rays > 0 {
let mut bp = vectorcraft_geom::BezPath::new();
let mut reach: f64 = 0.0;
for i in 0..rays {
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
reach = reach.max(len);
let w = r * 0.035;
let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin());
let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w;
bp.move_to(c + n);
bp.line_to(c + dir * len);
bp.line_to(c - n);
bp.line_to(c - dir * (w * 4.0));
bp.close_path();
}
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
}
// Centre: bright core fading to transparent.
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
// Rings along the path to the end point (Largest = % of the average ring size).
for _ in 0..rings {
let t = rnd();
let t = ring_at.as_mut().map_or(t, |next| next());
let at = c + (end - c) * t;
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
let solid = rnd() < 0.5;
let stops = if solid {
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
} else {
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
};
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
}
let parent = s.doc()?.target_parent()?;
let id = s.edit("Flare", |d, sel| {
let children = parts
.into_iter()
.map(|(name, pd, paint, op)| {
let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0));
n.name = Some(name.into());
n.blend = BlendMode::Screen;
n.opacity = op;
super::object::align_new_object(d, &mut n);
std::sync::Arc::new(n)
})
.collect();
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = Some("Flare".into());
d.insert(parent, usize::MAX, g)?;
sel.set([gid]);
Ok(gid)
})?;
Ok(json!({ "id": id.0 }))
}
fn line(s: &mut Session, p: &Value) -> Result<Value> {
let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?);
let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?);
+3 -10
View File
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
use serde_json::{Value, json};
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::dimension::{
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
};
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
pub fn specs() -> Vec<CommandSpec> {
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
LineType::Solid => None,
};
if arrows {
let head = match o.arrow_style {
ArrowStyle::Filled => Some(Arrowhead::Triangle),
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
let head = o.arrow_style.arrowhead();
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
+32 -4
View File
@@ -345,18 +345,46 @@ pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec<N
out
}
/// Any visible non-None fill, including one below a topmost None.
pub(super) fn has_fill(n: &Node) -> bool {
n.appearance.items.iter().any(|item| item.is_fill() && item.visible() && !item.paint().is_none())
}
/// A visible painted stroke keeps open paths on the existing outline-erasure route.
pub(super) fn has_painted_stroke(n: &Node) -> bool {
n.appearance.items.iter().any(
|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(stroke) if stroke.visible && !stroke.paint.is_none() && stroke.width > 0.0),
)
}
/// A container stroke that paints this target's open geometry. A clipping container's own
/// paint follows its clipping outline, and a compound shape paints its combined area instead.
/// Neither makes its descendants' implicit fill-closing edges into new stroked edges.
pub(super) fn has_painted_ancestor_stroke(doc: &Document, id: NodeId) -> bool {
doc.ancestry(id)
.unwrap_or_default()
.into_iter()
.rev()
.skip(1)
.filter_map(|id| doc.node(id))
.take_while(|node| !node.clips() && !node.is_compound_shape())
.any(|node| matches!(node.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && has_painted_stroke(node))
}
/// [`target_paths`] for the tools that cut fills, with each target's geometry and fill rule: the
/// members of a compound path whose members are all closed paths give the compound path itself,
/// once, so its fill (holes included) is cut as one shape under its own fill rule.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let closed_compound = |n: &Node| {
/// With `open_fills`, an open compound with a visible fill and no painted visible stroke does too.
pub(super) fn fill_targets(doc: &Document, sel: &Selection, area: Rect, open_fills: bool) -> Result<Vec<(NodeId, PathData, FillRule)>> {
let area_compound = |n: &Node| {
let filled = open_fills && has_fill(n) && !has_painted_stroke(n) && !has_painted_ancestor_stroke(doc, n.id);
matches!(&n.kind, NodeKind::Compound { children, .. }
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed())))
if children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, .. } if path.is_closed() || filled)))
};
let editable = doc.editable();
let mut out: Vec<(NodeId, PathData, FillRule)> = vec![];
for id in target_paths(doc, sel, area) {
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| closed_compound(p) && editable(p.id));
let compound = doc.parent_of(id).and_then(|p| doc.node(p)).filter(|p| area_compound(p) && editable(p.id));
let target = compound.map_or(id, |c| c.id);
if out.iter().any(|t| t.0 == target) {
continue;
+71 -13
View File
@@ -1,10 +1,11 @@
use super::common::{
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param,
poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt,
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke,
has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param,
set_geometry, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point,
Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
@@ -266,7 +267,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0);
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0))? {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, 1.0), false)? {
if !pd.is_closed() {
continue;
}
@@ -340,8 +341,9 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
None => dist_to_polyline(&round, squash * q) <= r,
};
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -353,6 +355,34 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// Whether the target is erased as filled area rather than as an open outline.
fn erase_as_area(doc: &Document, id: NodeId, pd: &PathData) -> bool {
// An unaggregated compound member keeps the outline route: its own appearance does not
// paint it. Eligible fill-only compounds were collected as one parent target above.
let compound_member =
doc.parent_of(id).and_then(|parent| doc.node(parent)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. }));
let filled_open =
!compound_member && !has_painted_ancestor_stroke(doc, id) && doc.node(id).is_some_and(|node| has_fill(node) && !has_painted_stroke(node));
pd.is_closed() || filled_open
}
/// Close only Eraser's temporary fill operand, preserving an open path's straight closing edge.
fn eraser_fill_operand(mut pd: PathData) -> PathData {
for sp in &mut pd.subpaths {
if !sp.closed {
// These endpoint handles are unused by an open path. Closing it must not activate them.
if let Some(first) = sp.anchors.first_mut() {
first.h_in = first.p;
}
if let Some(last) = sp.anchors.last_mut() {
last.h_out = last.p;
}
sp.closed = true;
}
}
pd
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
@@ -369,7 +399,7 @@ fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
/// all). Closed paths and fill-only open paths lose the rectangle's area; other open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
@@ -392,8 +422,9 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r, true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -492,8 +523,9 @@ fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Vari
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
let reach = (size + sv) / 2.0;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
if pd.is_closed() {
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach), true)? {
if erase_as_area(&st.doc, id, &pd) {
let pd = eraser_fill_operand(pd);
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
@@ -510,10 +542,36 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
return Ok(json!({ "ids": [] }));
}
let ids = s.edit(label, |d, sel| {
// Measure every original painting owner before any geometry or appearance changes.
// This includes a Compound above a Path Eraser target and containers above live art.
let owners: std::collections::BTreeSet<_> = plan.iter().flat_map(|(id, _)| d.ancestry(*id).unwrap_or_default()).collect();
let pinned: Vec<_> = owners
.into_iter()
.filter_map(|id| {
let node = d.node(id)?;
if !node.appearance.has_unplaced_gradient() {
return None;
}
vectorcraft_render::pinned_appearance_for_geometry_edit(d, node).map(|appearance| (id, appearance))
})
.collect();
for (id, appearance) in pinned {
if let Some(node) = d.node_mut(id) {
node.appearance = appearance.into();
}
}
let mut all = vec![];
let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::<Vec<_>>());
for (id, pieces) in plan {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
let clipping_path = d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(|p| p.clips()));
if clipping_path {
// Keep every clipping contour in its original first child slot. An empty mask
// must also stay there so the clipped artwork cannot become the new mask.
set_geometry(d, id, PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect()))?;
all.push(id);
} else {
all.extend(replace_with_pieces(d, &mut cut, id, pieces)?);
}
}
cut.finish(d)?;
sel.set(all.iter().copied());
+1
View File
@@ -1611,6 +1611,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}
} else {
super::object::keep_pixel_aligned(&mut c, sc);
super::buildcmds::clear_part_name(d, par, &mut c);
new_ids.push(d.insert(par, idx, c)?);
}
}
+5 -1
View File
@@ -182,7 +182,7 @@ impl Expandable {
n.walk(&mut |c| {
let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
e.text |= matches!(c.kind, NodeKind::Text(_));
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. });
e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some();
e.effects |= !c.appearance.effects.is_empty();
e.envelope |= matches!(c.kind, NodeKind::Envelope { .. });
e.blends |= matches!(c.kind, NodeKind::Blend { .. });
@@ -503,10 +503,14 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec<EndedLink>) -> Result<()
Ok(())
}
/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts.
fn drop_live(n: &mut Node) {
if let NodeKind::Path { live, .. } = &mut n.kind {
*live = None;
}
if n.extras().flare.is_some() {
n.extras_mut().flare = None;
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
drop_live(Arc::make_mut(c));
+22 -7
View File
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
}
/// Does a file of a document with `artboards` artboards, written in format `format` with options
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
match format {
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
"ai" | "ait" => {
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
!legacy && !(format == "ai" && art_page()) && every_artboard()
@@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
/// always, unless read roots are in force, the file carries the native document (a native file or
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
/// plug-in's file, as
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
@@ -294,7 +297,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
vectorcraft_doc::cancel::check()?;
may_write(path)?;
// Never a half-written file: see [`write_atomic`].
write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
}
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason.
#[cfg(not(target_arch = "wasm32"))]
fn write_error(path: &str, error: std::io::Error) -> EngineError {
if error.get_ref().is_some_and(|e| e.is::<vectorcraft_doc::cancel::Cancelled>()) {
return EngineError::Cancelled;
}
EngineError::Other(format!("{path}: {error}"))
}
/// [`write_file`] with what `fill` writes into the file (a save streamed into it).
@@ -302,7 +315,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
vectorcraft_doc::cancel::check()?;
may_write(path)?;
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
}
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
@@ -321,8 +334,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError {
let reason = format!("{path}: {error}");
if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) }
if !vectorcraft_format::read_only_location(&error) {
return write_error(path, error);
}
EngineError::ReadOnlyLocation(format!("{path}: {error}"))
}
#[cfg(target_arch = "wasm32")]
+6 -4
View File
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
/// one named after the document) with that path's extension when the plug-in lists it, else its
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
/// names (else one named after the document) with that path's extension when the plug-in lists it,
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
use vectorcraft_plugins::{Error, export};
let doc = &*doc.without_edit_modes();
let doc = doc.without_edit_modes();
let doc = &*super::access::with_readable_settings_folder(&doc);
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
let path = p.get("path").and_then(Value::as_str);
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
+6 -3
View File
@@ -962,7 +962,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
/// clipping path ([`image_clip`]).
/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes
/// it) is read with that path.
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
@@ -1139,13 +1140,15 @@ pub fn texture_image(bytes: &[u8]) -> Result<String> {
texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture"))
}
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed.
/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a
/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]).
fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result<RasterImage> {
if width == 0 || height == 0 {
return Err(err("the image is empty"));
}
let blob = ImageBlob::new(mime, bytes);
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd));
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip })
}
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
+17 -1
View File
@@ -19,6 +19,18 @@ pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS,
/// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one
/// picture per chosen artboard (default all).
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kind: Kind) -> Result<Encoded> {
encode_flattening(doc, p, use_artboards, kind, crate::flatten_raster_effects)
}
/// [`encode`] with `flatten` turning raster effects into images. The chosen artboards are checked
/// first, so an export that is refused does not call `flatten`.
pub(super) fn encode_flattening(
doc: &Document,
p: &Value,
use_artboards: Option<bool>,
kind: Kind,
flatten: impl FnOnce(&Document) -> Option<Document>,
) -> Result<Encoded> {
let f = super::format(kind.id()).ok_or_else(|| bad(C, "no metafile format"))?;
let pick: ArtboardPick = super::encode::options(f, p)?;
let n = doc.artboards.len();
@@ -26,12 +38,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
};
if boards.is_empty() {
return Err(bad(C, "the document has no artboard"));
}
let rects = boards
.iter()
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
.collect::<Result<Vec<_>>>()?;
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
let flat = crate::flatten_raster_effects(doc);
let flat = flatten(doc);
let src = flat.as_ref().unwrap_or(doc);
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
+202 -6
View File
@@ -69,7 +69,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "bleed",
ty: "object",
default: "null",
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning",
description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so do objects that reach the trim edge on a side with a bleed but stop short of the bleed edge",
},
FormatOption {
name: "output",
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
has_doc,
export_pdf
),
@@ -295,6 +295,8 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Op
o.insert("preserveEditing".into(), json!(false));
}
let (bytes, mut notes) = encode(cmd, &art, &q)?;
// The page is the art's bounds, so every object at its edge would count.
notes.retain(|n| !is_short_of_bleed(&n.text));
if left_out {
notes.push(Note::setting(EDITING_NEEDS_THE_ARTBOARDS));
}
@@ -317,6 +319,191 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
/// and still count as reaching it in [`short_of_bleed`]. A side whose bleed is no larger has none.
const EDGE_TOLERANCE: f64 = 0.5;
/// How many objects of `doc` reach the trim edge (an artboard's edge, within [`EDGE_TOLERANCE`]) of
/// one of `artboards` (`None`: all of them) on a side where `bleed` (`[top, bottom, left, right]`
/// in points) is set, but end before that side's bleed edge. The objects are the members of the
/// visible layers and sublayers, a group counted as one, measured as [`drawn_bounds`] measures them
/// and cut to the clipping paths of the layers they are on. Template layers, layers with an opacity
/// mask and, unless `non_printing`, layers whose Print option is off are left out. A side whose
/// bleed is [`EDGE_TOLERANCE`] or less counts as having none. Each object counts once.
pub fn short_of_bleed(doc: &Document, bleed: [f64; 4], artboards: Option<&[usize]>, non_printing: bool) -> usize {
let bleed = bleed.map(|b| if b.is_finite() && b > EDGE_TOLERANCE { b } else { 0.0 });
if bleed.iter().all(|b| *b == 0.0) {
return 0;
}
let trims: Vec<vectorcraft_geom::Rect> = match artboards {
Some(picked) => picked.iter().filter_map(|&i| doc.artboards.get(i)).map(|a| a.rect).collect(),
None => doc.artboards.iter().map(|a| a.rect).collect(),
};
let symbols = doc.symbol_boxes();
let mut count = 0;
// Each object with the clipping path of the layers above it.
let mut stack: Vec<(&Node, Option<vectorcraft_geom::Rect>)> = doc.layers.iter().map(|l| (&**l, None)).collect();
while let Some((n, clip)) = stack.pop() {
if let NodeKind::Layer { template, printable, children, clip: clipping, .. } = &n.kind {
// An opacity mask decides what shows, so a masked layer's art is not measured.
if !n.visible || *template || !(*printable || non_printing) || n.opacity <= 0.0 || n.extras().mask.is_some() {
continue;
}
// A clipping layer's first child clips the others, and its fills and strokes are an
// object of their own.
let (inner, members) = if *clipping {
let Some(own) = clip_region(children, &symbols) else { continue };
let inner = clip.map_or(own, |c| c.intersect(own));
if let Some(first) = children.first()
&& let Drawn::Bounds(b) = clip_paint_drawn(first, inner, &symbols)
{
let b = clip.map_or(b, |c| c.intersect(b));
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
count += 1;
}
}
(Some(inner), children.get(1..).unwrap_or_default())
} else {
(clip, &children[..])
};
stack.extend(members.iter().map(|c| (&**c, inner)));
continue;
}
let Drawn::Bounds(b) = drawn_bounds(n, &symbols) else { continue };
let b = clip.map_or(b, |c| c.intersect(b));
if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) {
count += 1;
}
}
count
}
/// What [`drawn_bounds`] finds an object draws.
enum Drawn {
/// Nothing: it is hidden, a guide, at 0% opacity, or a path that paints nothing.
Nothing,
/// Art within these bounds.
Bounds(vectorcraft_geom::Rect),
/// Art whose bounds aren't known, which is not measured: brush art paints past the visual
/// bounds by an amount they don't give, an opacity mask hides part of what they hold, and area
/// type and type on a path are bounded by their frame or path.
Unknown,
}
/// Whether path or compound path `n` paints: one of its fills and strokes is visible, has a paint
/// and an opacity above 0 and, a stroke, a width above 0. Other objects count as painting.
fn paints(n: &Node) -> bool {
!matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|| n.appearance.items.iter().any(|i| {
i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
})
}
/// What `n` draws on a page, by its visual bounds (strokes included): a group without a clipping
/// path by the members that draw, and a clip group by the part of them inside its clipping path
/// together with what the clipping path paints itself ([`clip_paint_drawn`]).
/// Hidden objects, guides, objects at 0% opacity and paths that paint nothing draw nothing. Art
/// with a brushed stroke that draws, in `n` or (outside groups) in the objects it holds, art with
/// an opacity mask, and area type and type on a path are [`Drawn::Unknown`].
fn drawn_bounds(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
if !n.visible || n.is_guide() || n.opacity <= 0.0 || !paints(n) {
return Drawn::Nothing;
}
// An opacity mask decides what shows of the object, and the bounds of area type and type on a
// path are its frame or path, not its glyphs.
let frame_bounds = matches!(&n.kind, NodeKind::Text(t) if !matches!(t.kind, vectorcraft_doc::TextKind::Point));
if vectorcraft_brush::reach(n) > 0.0 || n.extras().mask.is_some() || frame_bounds {
return Drawn::Unknown;
}
let members = |children: &[Arc<Node>]| {
let mut out = Some(None);
for c in children {
out = match (out, drawn_bounds(c, symbols)) {
(None, _) | (_, Drawn::Unknown) => None,
(Some(acc), Drawn::Bounds(b)) => Some(vectorcraft_geom::union_opt(acc, Some(b))),
(keep, Drawn::Nothing) => keep,
};
}
out
};
let measured = match &n.kind {
NodeKind::Group { clip: false, .. } => match members(n.editing_children()) {
Some(art) => art.and_then(|_| n.visual_of_members(std::iter::once(art))),
None => return Drawn::Unknown,
},
NodeKind::Group { clip: true, children } => {
let Some(region) = clip_region(children, symbols) else { return Drawn::Nothing };
let Some(art) = members(children.get(1..).unwrap_or_default()) else { return Drawn::Unknown };
let art = art.map(|a| region.intersect(a)).filter(|b| b.area() > 0.0);
match children.first().map_or(Drawn::Nothing, |first| clip_paint_drawn(first, region, symbols)) {
Drawn::Unknown => return Drawn::Unknown,
Drawn::Bounds(b) => vectorcraft_geom::union_opt(art, Some(b)),
Drawn::Nothing => art,
}
}
_ if vectorcraft_brush::reach_within(n) > 0.0 => return Drawn::Unknown,
_ => n.visual_bounds_with(symbols),
};
measured.map_or(Drawn::Nothing, Drawn::Bounds)
}
/// The region the clipping path of a clip group or clipping layer with `children` clips to: its
/// geometric bounds, without its strokes.
fn clip_region(children: &[Arc<Node>], symbols: &vectorcraft_doc::SymbolBoxes) -> Option<vectorcraft_geom::Rect> {
children.first()?.geometric_bounds_with(symbols)
}
/// What clipping path `clip` paints itself ([`Node::clip_paint`]): its fills inside `region`, the
/// region it clips to, and its strokes over the clipped art, unclipped.
fn clip_paint_drawn(clip: &Node, region: vectorcraft_geom::Rect, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn {
let paint = clip.clip_paint();
let mut out = None;
for (part, clipped) in [(paint.fill, true), (paint.stroke, false)] {
let Some(part) = part else { continue };
match drawn_bounds(&part, symbols) {
Drawn::Unknown => return Drawn::Unknown,
Drawn::Nothing => {}
Drawn::Bounds(b) => {
let b = if clipped { region.intersect(b) } else { b };
out = vectorcraft_geom::union_opt(out, Some(b).filter(|b| b.area() > 0.0));
}
}
}
out.map_or(Drawn::Nothing, Drawn::Bounds)
}
/// Whether bounds `b` reach the trim edge `t` (within [`EDGE_TOLERANCE`] on either side of it) on a
/// side where `bleed` (`[top, bottom, left, right]`) is above 0 and end before the bleed edge there.
/// Document space has y down.
fn stops_short(b: vectorcraft_geom::Rect, t: vectorcraft_geom::Rect, [top, bottom, left, right]: [f64; 4]) -> bool {
let tol = EDGE_TOLERANCE;
let across = b.x0 < t.x1 && b.x1 > t.x0;
let down = b.y0 < t.y1 && b.y1 > t.y0;
let reaches = |near: f64, far: f64, edge: f64| near <= edge + tol && far >= edge - tol;
(across && top > 0.0 && reaches(b.y0, b.y1, t.y0) && b.y0 > t.y0 - top + tol)
|| (across && bottom > 0.0 && reaches(-b.y1, -b.y0, -t.y1) && b.y1 < t.y1 + bottom - tol)
|| (down && left > 0.0 && reaches(b.x0, b.x1, t.x0) && b.x0 > t.x0 - left + tol)
|| (down && right > 0.0 && reaches(-b.x1, -b.x0, -t.x1) && b.x1 < t.x1 + right - tol)
}
/// The warning for `n` objects that [`short_of_bleed`] finds; `None` for none.
pub fn short_of_bleed_warning(n: usize) -> Option<String> {
match n {
0 => None,
1 => Some(format!("1 object {SHORT_OF_BLEED_ONE}")),
_ => Some(format!("{n} objects {SHORT_OF_BLEED_OTHER}")),
}
}
/// The end of [`short_of_bleed_warning`] for one object and for more.
const SHORT_OF_BLEED_ONE: &str = "reaches the trim edge but stops short of the bleed";
const SHORT_OF_BLEED_OTHER: &str = "reach the trim edge but stop short of the bleed";
/// Whether `text` is a warning [`short_of_bleed_warning`] gives.
pub fn is_short_of_bleed(text: &str) -> bool {
text.ends_with(SHORT_OF_BLEED_ONE) || text.ends_with(SHORT_OF_BLEED_OTHER)
}
/// The end of the writer's warning for a page longer than 14,400 pt written with a `UserUnit`
/// above 1.
const SHOWN_SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller";
@@ -340,7 +527,7 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
// The editing data leaves out an Export for Screens folder outside the read roots.
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?;
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?;
notes.extend(drawn);
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) {
@@ -364,7 +551,8 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result<Option<Strin
/// [`encode`] the pages of `doc`, carrying `native()` as the editing data (a `.ai` file: the
/// native document with its save options, whose pages may be left blank), and `private()`, the
/// editing copy of the art for other apps with what it couldn't hold, on every page.
/// editing copy of the art for other apps with what it couldn't hold, on every page. It doesn't
/// warn about art that stops short of the bleed ([`short_of_bleed`]), which PDF export does.
pub(super) fn encode_carrying(
cmd: &str,
doc: &Document,
@@ -372,20 +560,26 @@ pub(super) fn encode_carrying(
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<Note>)> {
encode_carrying_at(cmd, doc, p, None, native, private)
encode_carrying_at(cmd, doc, p, None, false, native, private)
}
/// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of
/// writing.
/// writing, warning about art that stops short of the bleed when `bleed_check` is true.
fn encode_carrying_at(
cmd: &str,
doc: &Document,
p: &Value,
modified: Option<i64>,
bleed_check: bool,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<Note>)> {
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
// Measured before the pages' background colors join the art. Only art that prints counts:
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
// includeNonPrinting, which writes them as printing art.
let set = &opts.settings;
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
@@ -401,6 +595,8 @@ fn encode_carrying_at(
if opts.settings.leaves_out_bleed(doc) {
notes.push(Note::loss(BLEED_LEFT_OUT));
}
// Art that reaches the trim edge but leaves part of the page's bleed empty.
notes.extend(short_of_bleed_warning(short).map(Note::loss));
if opts.settings.preserve_editing {
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
opts.native = Some(native()?);
+44 -6
View File
@@ -629,6 +629,24 @@ impl<W: std::io::Write> std::io::Write for Counted<W> {
}
}
/// A writer that fails once the work running on this thread is canceled
/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file.
/// It sits under the stream's buffer: it is checked once per buffer written, not per write.
struct StopsWhenCancelled<W>(W);
impl<W: std::io::Write> std::io::Write for StopsWhenCancelled<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if crate::cancel::is_cancelled() {
return Err(std::io::Error::other(crate::cancel::Cancelled));
}
self.0.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.0.flush()
}
}
/// The artboards a native or `.ai` save also writes to files of their own: with
/// `separateArtboards`, those `range` names (default all).
fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Vec<usize>> {
@@ -1026,10 +1044,15 @@ impl SaveJob {
}
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
/// order: when `stop` returns a value, nothing is written and that value is returned.
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
/// canceled ([`crate::cancel`]) before the first file is written returns
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
/// others are written too.
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let (plan, doc) = (&self.plan, &*self.doc);
crate::cancel::check()?;
let enc = self.encode()?;
crate::cancel::check()?;
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
let Some(path) = &plan.path else {
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
@@ -1046,8 +1069,13 @@ impl SaveJob {
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
return Ok(stopped);
}
for (p, bytes) in &files {
write(p, bytes)?;
for (i, (p, bytes)) in files.iter().enumerate() {
if i == 0 {
write(p, bytes)?;
} else {
// Once a file is in place, a Cancel no longer stops the save: the set is written whole.
crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?;
}
}
let bytes = files.first().map_or(0, |f| f.1.len());
let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra);
@@ -1070,11 +1098,15 @@ impl SaveJob {
/// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler
/// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native
/// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory;
/// other files are encoded first, then written into it.
/// other files are encoded first, then written into it. Work canceled ([`crate::cancel`])
/// while the native file is encoded, or before its filler returns, returns
/// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was
/// (the atomic writer checks once more before it puts the file in place).
pub fn write_streamed(&self, stream: StreamWrite) -> Result<Value> {
let (Some(path), true) = (&self.plan.path, self.streams()) else {
return self.write(|p, b| stream(p, &mut |w| w.write_all(b)));
};
crate::cancel::check()?;
let (cmd, f) = (self.plan.mode.command(), self.plan.format);
let doc = self.doc.without_edit_modes();
let doc = match f.id {
@@ -1091,16 +1123,22 @@ impl SaveJob {
let mut failed = None;
let mut written = 0u64;
let mut fill = |w: &mut dyn std::io::Write| {
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 };
let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 };
let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out);
written = out.n;
match r {
let r = match r {
Ok(()) => out.inner.flush(),
Err(e) => {
failed = Some(e);
Err(std::io::Error::other("the file couldn't be encoded"))
}
};
// The last check before the file is replaced: a canceled save leaves it as it was.
if crate::cancel::is_cancelled() {
failed = Some(crate::EngineError::Cancelled);
return Err(std::io::Error::other(crate::cancel::Cancelled));
}
r
};
let r = stream(path, &mut fill);
r.map_err(|e| failed.take().unwrap_or(e))?;
+5 -1
View File
@@ -1349,10 +1349,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
// The document a PDF row writes: with Include Bleed, the artboards as they are.
let pdf_doc = ungrown.as_deref();
// A PDF page of an artboard has the artboard as its trim, with or without Include Bleed. A
// page of its art's bounds has every object at its edge: it doesn't say whether art stops
// short of the bleed.
let artboard_page = o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given {
for n in given.into_iter().filter(|n| artboard_page || !super::pdf::is_short_of_bleed(&n.text)) {
add_note(&mut notes, n);
}
Ok(bytes)
+103
View File
@@ -935,6 +935,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() {
let _ = std::fs::remove_dir_all(&d);
}
/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into
/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the
/// file as it was, with no temporary file behind. A file encoded first is never written.
#[test]
fn a_canceled_save_leaves_the_file_as_it_was() {
/// Passes every write on, and cancels the save after the first one.
struct CancelAfterFirst<'a> {
inner: &'a mut dyn std::io::Write,
token: crate::cancel::CancelToken,
}
impl std::io::Write for CancelAfterFirst<'_> {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
let n = self.inner.write(b)?;
self.token.cancel();
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
let d = tmp_dir("stream-cancel");
// A small document's file goes in one piece; a large one's in several.
for count in [1, 1500] {
let mut s = session(2000.0, 2000.0, 1);
for i in 0..count {
s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap();
}
let path = d.join("a.vectorcraft").to_string_lossy().to_string();
s.execute("file.saveCopy", &json!({"path": path})).unwrap();
let before = std::fs::read(&path).unwrap();
s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap();
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap();
let job = save_job(&mut s, plan).unwrap();
assert!(job.streams());
let token = crate::cancel::CancelToken::new();
let r = crate::cancel::scope(&token, None, || {
job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() })))
});
assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}");
assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects");
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left");
// Canceled before it starts: the file isn't opened.
let mut opened = false;
let r = crate::cancel::scope(&token, None, || {
job.write_streamed(&mut |_, _| {
opened = true;
Ok(())
})
});
assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}");
}
// A file encoded first (SVG): nothing reaches the writer.
let mut s = session(200.0, 100.0, 1);
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap();
let job = save_job(&mut s, plan).unwrap();
let token = crate::cancel::CancelToken::new();
token.cancel();
let mut writes = 0;
let r = crate::cancel::scope(&token, None, || {
job.write_streamed(&mut |_, _| {
writes += 1;
Ok(())
})
});
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
let r = crate::cancel::scope(&token, None, || {
job.write(|_, _| {
writes += 1;
Ok(())
})
});
assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}");
assert!(!d.join("a.svg").exists());
let _ = std::fs::remove_dir_all(&d);
}
/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is
/// in place writes the others too and succeeds: the set is never left half written.
#[test]
fn a_save_canceled_after_its_first_file_writes_them_all() {
let d = tmp_dir("cancel-files");
let mut s = session(100.0, 100.0, 2);
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
let path = d.join("logo.eps").to_string_lossy().to_string();
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap();
let job = save_job(&mut s, plan).unwrap();
let token = crate::cancel::CancelToken::new();
let mut written = vec![];
let r = crate::cancel::scope(&token, None, || {
job.write(|p, b| {
super::write_save_file(p, b)?;
written.push(p.to_string());
token.cancel();
Ok(())
})
});
assert!(r.is_ok(), "{r:?}");
assert_eq!(written.len(), 3, "{written:?}");
assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}");
let _ = std::fs::remove_dir_all(&d);
}
/// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them.
#[test]
fn a_failed_save_does_not_stamp_the_documents_dates() {
@@ -95,6 +95,65 @@ fn raster_effects_are_written_as_images() {
assert!(kinds.contains(&114), "the shadow is an image with transparency");
}
/// An export refused for an empty or non-finite artboard among the chosen ones, or for no
/// artboard, gives the same error as before and turns no raster effect into an image; an export
/// that goes ahead does so once, and writes what `document.export` writes.
#[test]
fn a_refused_export_turns_no_raster_effects_into_images() {
use vectorcraft_geom::Rect;
use vectorcraft_metafile::Kind;
let mut s = two_boards();
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 30, "height": 30})).unwrap()["id"].clone();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
let doc = s.doc().unwrap().doc.as_ref().clone();
let run = |doc: &vectorcraft_doc::Document, p: Value, kind: Kind| {
let mut calls = 0;
let r = super::metafile::encode_flattening(doc, &p, Some(true), kind, |d| {
calls += 1;
crate::flatten_raster_effects(d)
});
(r.map(|e| e.files).map_err(|e| e.to_string()), calls)
};
for kind in [Kind::Emf, Kind::Wmf] {
let (files, calls) = run(&doc, json!({}), kind);
assert_eq!(calls, 1, "{kind:?}");
let files = files.unwrap();
assert_eq!(files.len(), 2, "{kind:?}");
let r = s.execute("document.export", &json!({"format": kind.id(), "useArtboards": true})).unwrap();
let written: Vec<Vec<u8>> = r["files"].as_array().unwrap().iter().map(b64).collect();
assert_eq!(files.into_iter().map(|(_, b)| b).collect::<Vec<_>>(), written, "{kind:?}");
// The first artboard is fine; the second is empty, or has a corner that isn't finite.
let x = doc.artboards[0].rect.x1 + 10.0;
for empty in [Rect::new(x, 0.0, x, 100.0), Rect::new(0.0, 0.0, f64::NAN, 100.0), Rect::new(0.0, 0.0, 100.0, f64::INFINITY)] {
let mut bad_doc = doc.clone();
bad_doc.artboards[1].rect = empty;
for p in [json!({}), json!({"artboards": [0, 1]}), json!({"artboards": [1]})] {
let (files, calls) = run(&bad_doc, p.clone(), kind);
let e = files.err().unwrap_or_default();
assert!(e.contains("the export region is empty"), "{kind:?} {p}: {e}");
assert_eq!(calls, 0, "{kind:?} {p}");
}
}
// Reversed corners are an artboard like any other.
let mut flipped = doc.clone();
let r1 = flipped.artboards[1].rect;
flipped.artboards[1].rect = Rect::new(r1.x1, r1.y1, r1.x0, r1.y0);
let (files, calls) = run(&flipped, json!({}), kind);
assert_eq!((files.map(|f| f.len()), calls), (Ok(2), 1), "{kind:?}");
// No artboard to write.
let mut none = doc.clone();
none.artboards.clear();
let (files, calls) = run(&none, json!({}), kind);
let e = files.err().unwrap_or_default();
assert!(e.contains("the document has no artboard"), "{kind:?}: {e}");
assert_eq!(calls, 0, "{kind:?}");
}
// Through the command, the refusal reads as it did.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[1].rect = Rect::new(0.0, 0.0, 0.0, 100.0);
let e = s.execute("document.export", &json!({"format": "emf", "useArtboards": true})).unwrap_err().to_string();
assert!(e.contains("the export region is empty"), "{e}");
}
/// Two placed images whose pixel data can't be decoded are left out of an EMF or WMF, and
/// `warnings` holds the note raster exports give, once, without naming either image's key.
#[test]
+220
View File
@@ -171,6 +171,226 @@ fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() {
assert!(!left_out(&warnings), "{warnings:?}");
}
/// A 200 × 100 pt document with no art, bleed `bleed` (pt).
fn bleed_session(bleed: Value) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("document.setup", &json!({ "bleed": bleed })).unwrap();
s
}
/// A rectangle from (x0, y0) to (x1, y1) without a stroke, on the current layer.
fn plain_rect(s: &mut Session, [x0, y0, x1, y1]: [f64; 4]) -> Value {
let id = s.execute("shape.rectangle", &json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap()["id"].clone();
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
id
}
/// The warnings of a PDF that carries the document's bleed that say art stops short of it.
fn short_of_bleed(s: &mut Session) -> Vec<String> {
let (_, warnings) = pdf(s, json!({"bleed": {"useDocument": true}}));
warnings.into_iter().filter(|w| super::pdf::is_short_of_bleed(w)).collect()
}
const MM: f64 = 72.0 / 25.4;
/// A bleed raised from 2 mm to 5 mm leaves a background that filled the old bleed, and a band
/// placed against the trim edge, short of the new one: the export warns once, counting both.
#[test]
fn art_that_reaches_the_trim_edge_but_stops_short_of_the_bleed_warns() {
let mut s = bleed_session(json!(2.0 * MM));
let (b, w, h) = (2.0 * MM, 200.0, 100.0);
plain_rect(&mut s, [-b, -b, w + b, h + b]);
plain_rect(&mut s, [0.0, 0.0, w, 20.0]);
// At 2 mm the background reaches the bleed; the band stops at the trim edge.
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
s.execute("document.setup", &json!({"bleed": 5.0 * MM})).unwrap();
assert_eq!(short_of_bleed(&mut s), ["2 objects reach the trim edge but stop short of the bleed"]);
// The PDF/X presets carry the document's bleed.
let (_, warnings) = pdf(&mut s, json!({"preset": "PDF/X-4:2010"}));
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
// A PDF/X file with a bleed on the top alone leaves out the rest of the document's bleed, and
// the background and the band stop short at the top: the warning comes right after
// BLEED_LEFT_OUT.
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 9}}));
assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{warnings:?}");
assert_eq!(warnings.get(1).map(String::as_str), Some("2 objects reach the trim edge but stop short of the bleed"), "{warnings:?}");
// A page without the bleed (the default preset) doesn't warn, and neither does a page of the art's bounds.
let (_, warnings) = pdf(&mut s, json!({}));
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
let (_, warnings) = pdf(&mut s, json!({"bleed": {"useDocument": true}, "useArtboards": false}));
assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
// An explicit bleed counts too, and the Summary lists the warning.
let (_, warnings) = pdf(&mut s, json!({"bleed": {"top": 9, "bottom": 9, "left": 9, "right": 9}}));
assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}");
let v = s.execute("document.pdfSettings", &json!({"bleed": {"useDocument": true}, "includeDocument": true})).unwrap();
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
// A group counts once, measured by its visible members: a hidden member that fills the bleed
// doesn't hide a visible one at the trim edge.
let mut s = bleed_session(json!(9));
let fill = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let side = plain_rect(&mut s, [0.0, 40.0, 20.0, 60.0]);
s.execute("object.group", &json!({"ids": [fill, band, side]})).unwrap();
s.execute("object.hide", &json!({"ids": [fill]})).unwrap();
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
// A clip group is measured by the art inside its clipping path, not by a clipping path that
// reaches the bleed edge.
let mut s = bleed_session(json!(9));
let art = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let clip = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
assert_eq!(short_of_bleed(&mut s).len(), 1);
// A clipping path that paints a fill reaching the trim edge counts, though the art it clips is
// inside: in a clip group, and as an object of its own in a clipping layer.
let mut s = bleed_session(json!(9));
let art = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
assert_eq!(short_of_bleed(&mut s).len(), 1);
let mut s = bleed_session(json!(9));
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]);
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
assert_eq!(short_of_bleed(&mut s).len(), 1);
// A hidden brushed member doesn't keep a group's visible art at the trim edge from counting.
let mut s = bleed_session(json!(9));
let brushed = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap();
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("object.group", &json!({"ids": [brushed, band]})).unwrap();
s.execute("object.hide", &json!({"ids": [brushed]})).unwrap();
assert_eq!(short_of_bleed(&mut s).len(), 1);
// A clipping layer clips its art to the clipping path's geometry, not to the stroke around it:
// the stroke reaches the trim edge, but the art it clips stops 5 pt inside.
let mut s = bleed_session(json!(9));
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
let clip = plain_rect(&mut s, [5.0, 5.0, 195.0, 95.0]);
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [clip], "color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"ids": [clip], "weight": 10})).unwrap();
assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]);
}
/// No warning for art that already fills the bleed, art inside the trim, a document without a
/// bleed, art on hidden, non-printing or template layers, a side without a bleed, area type, a
/// masked object, or a `.ai` save.
#[test]
fn art_that_fills_the_bleed_or_stays_inside_does_not_warn() {
let mut s = bleed_session(json!(9));
plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]);
plain_rect(&mut s, [-20.0, 40.0, 50.0, 60.0]);
plain_rect(&mut s, [10.0, 10.0, 190.0, 90.0]);
assert!(short_of_bleed(&mut s).is_empty());
// A document without a bleed has nothing to fall short of.
let mut s = bleed_session(json!(0));
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
assert!(short_of_bleed(&mut s).is_empty());
// Layers that don't print.
for props in [json!({"visible": false}), json!({"printable": false}), json!({"template": true})] {
let mut s = bleed_session(json!(9));
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let mut p = props.clone();
p["id"] = layer;
s.execute("layer.setProps", &p).unwrap();
assert!(short_of_bleed(&mut s).is_empty(), "{props}");
}
// A hidden object, and a group whose hidden member is the one at the trim edge.
let mut s = bleed_session(json!(9));
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("object.hide", &json!({"ids": [id]})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
let mut s = bleed_session(json!(9));
let edge = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
s.execute("object.group", &json!({"ids": [edge, inside]})).unwrap();
s.execute("object.hide", &json!({"ids": [edge]})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// Art that lies in the bleed alone, away from the trim edge.
let mut s = bleed_session(json!(9));
plain_rect(&mut s, [20.0, -5.0, 60.0, -3.0]);
assert!(short_of_bleed(&mut s).is_empty());
// A guide in a group at the trim edge.
let mut s = bleed_session(json!(9));
let guide = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("view.guides.make", &json!({})).unwrap();
let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]);
s.execute("object.group", &json!({"ids": [guide, inside]})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// A brushed stroke, whose brush art can paint past its visual bounds, is not measured.
let mut s = bleed_session(json!(9));
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("brush.apply", &json!({"ids": [id], "name": "Charcoal"})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// A path with no fill and no stroke paints nothing.
let mut s = bleed_session(json!(9));
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("paint.setFill", &json!({"ids": [id], "none": true})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// An object at 0% opacity draws nothing.
let mut s = bleed_session(json!(9));
let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// A clipping layer whose clipping path lies inside the trim draws none of its art at the edge.
let mut s = bleed_session(json!(9));
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
plain_rect(&mut s, [10.0, 10.0, 60.0, 60.0]);
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// A bleed on the top alone: art short at the left doesn't count, art short at the top does.
let mut s = bleed_session(json!([9, 0, 0, 0]));
plain_rect(&mut s, [0.0, 30.0, 40.0, 60.0]);
assert!(short_of_bleed(&mut s).is_empty());
plain_rect(&mut s, [60.0, 0.0, 100.0, 40.0]);
assert_eq!(short_of_bleed(&mut s).len(), 1);
// Area type is bounded by its frame, not its glyphs: a frame at the trim edge is not measured.
let mut s = bleed_session(json!(9));
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "Title", "size": 12, "area": {"width": 200, "height": 40}})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// An opacity mask decides what shows of the object, so a masked object is not measured.
let mut s = bleed_session(json!(9));
let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let mask = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]);
s.execute("transparency.makeOpacityMask", &json!({"ids": [band, mask]})).unwrap();
assert!(short_of_bleed(&mut s).is_empty());
// A `.ai` save with a bleed doesn't warn: the check is PDF export's.
let mut s = bleed_session(json!(9));
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
assert_eq!(short_of_bleed(&mut s).len(), 1);
let r = s.execute("document.export", &json!({"format": "ai", "bleed": {"useDocument": true}})).unwrap();
assert!(!r["warnings"].to_string().contains("short of the bleed"), "{}", r["warnings"]);
}
/// The warning changes neither the art nor the page boxes.
#[test]
fn the_bleed_warning_changes_no_geometry_and_no_page_box() {
let mut s = bleed_session(json!(9));
plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]);
let before = s.doc().unwrap().doc.clone();
let v = s.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}})).unwrap();
assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}");
assert_eq!(s.doc().unwrap().doc, before);
let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap();
let boxes = &info["pageInfo"][0]["boxes"];
let side = |b: &Value| {
let n: Vec<f64> = b.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
(((n[2] - n[0]) * 100.0).round() / 100.0, ((n[3] - n[1]) * 100.0).round() / 100.0)
};
assert_eq!(side(&boxes["trim"]), (200.0, 100.0), "{info}");
assert_eq!(side(&boxes["bleed"]), (218.0, 118.0), "{info}");
}
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
@@ -602,6 +602,56 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a
/// path and with a folder, and so do relinking to the written file, placing it and opening it.
#[test]
fn unembed_keeps_the_clipping_path_of_an_embedded_psd() {
let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip");
// An RGB file is kept as a PNG, a CMYK one as a TIFF.
let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]]));
let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)];
for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) {
let data = vectorcraft_format::base64_encode(file);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
let before = clip_group(&s.doc().unwrap().doc, group);
// Without an extension the image is written in the format it is stored in.
let path = if folder {
let out = dir.join(format!("folder-{kind}"));
std::fs::create_dir_all(&out).unwrap();
let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap();
r["unembedded"][0]["path"].as_str().unwrap().to_string()
} else {
let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap();
r["path"].as_str().unwrap().to_string()
};
let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() };
assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}");
for step in ["unembed", "relink"] {
if step == "relink" {
s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap();
}
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") };
assert!(im.link.is_some(), "linked to the file written");
assert_eq!(clip_group(d, group), before, "{kind}, {step}, folder: {folder}");
}
// Placing the written file gives the same clip group as placing the PSD file did.
let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap();
let placed = NodeId(r["ids"][0].as_u64().unwrap());
let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed);
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, place");
// Opening it gives a document of the image in that clip group.
s.execute("document.open", &json!({"path": path})).unwrap();
let d = &s.doc().unwrap().doc;
let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object");
let (anchors, even_odd, _) = clip_group(d, top);
assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, open");
}
}
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
/// text chunk within the size limit that reads as a path gives one back.
#[test]
@@ -610,6 +610,35 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
}
/// A PDF row with a bleed warns about art that reaches an artboard's edge and stops short of the
/// bleed, with or without Include Bleed: the page's trim is the artboard either way. It doesn't
/// warn about art that reaches the bleed, or on a page of a selection's bounds.
#[test]
fn pdf_rows_warn_about_art_short_of_the_bleed_on_artboard_pages_only() {
let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap()));
let row = json!([{"format": "pdf", "bleed": {"useDocument": true}}]);
let mut s = session(1);
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
// Against the artboard's top edge.
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
assert!(warned(&export(&mut s, json!({"formats": row}))));
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": [{"format": "pdf"}]}))), "the row takes the document's bleed");
assert!(!warned(&export(&mut s, json!({"selection": "one", "formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
// Out to the bleed edge on the top, left and right.
let mut s = session(1);
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
s.execute("shape.rectangle", &json!({"x": -6, "y": -6, "width": 52, "height": 16})).unwrap();
assert!(!warned(&export(&mut s, json!({"formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
// Without a document bleed, a row's own bleed warns.
let mut s = session(1);
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap();
let row = json!([{"format": "pdf", "bleed": {"top": 6, "bottom": 6, "left": 6, "right": 6}}]);
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
}
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
+246
View File
@@ -0,0 +1,246 @@
//! Flares (the Flare tool): `shape.flare` draws a group of radial-gradient paths that keeps the
//! settings it was drawn with ([`FlareSpec`]), and `shape.editFlare` draws it again from them.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::flare::{DEFAULT_SEED, FlareSpec, json_close, part_node, parts};
use vectorcraft_doc::{Document, Node, NodeId};
use vectorcraft_geom::{Affine, Point, Vec2};
use super::{EngineError, Result, Session, bad, check_numbers, f64_or, f64_req, given_objects, number_or};
const C: &str = "shape.editFlare";
/// `shape.flare`'s settings besides the center, the rings' end point, the counts and the seed:
/// (key, default).
const SETTINGS: [(&str, f64); 9] = [
("diameter", 100.0),
("opacity", 50.0),
("brightness", 30.0),
("growth", 20.0),
("fuzziness", 50.0),
("longest", 300.0),
("rayFuzziness", 100.0),
("rotation", 0.0),
("largest", 50.0),
];
/// The whole number of 0 or more `p` gives for `key`, or `default`.
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
let n = number_or(p, key, default as f64, cmd)?;
if n.is_finite() && n >= 0.0 && n.fract() == 0.0 {
Ok(n as u64)
} else {
Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}")))
}
}
/// `end`, the rings' end point, or an error naming `x2` or `y2` when that coordinate is not a
/// finite number (a `pathLength` so large that the end point overflows).
fn finite_end(end: Point, cmd: &str) -> Result<Point> {
match [("x2", end.x), ("y2", end.y)].into_iter().find(|(_, v)| !v.is_finite()) {
None => Ok(end),
Some((key, _)) => Err(bad(cmd, format!("{key} must be a finite coordinate"))),
}
}
/// `shape.flare`'s params `p` with every setting given: the defaults filled in, the counts at most
/// 50 and the rings' end point as `x2`, `y2` (from `pathLength` and `direction` when `p` gives no
/// end point), with `ringSeed` when `p` gives one.
fn settings_of(p: &Value, cmd: &str) -> Result<Value> {
let c = Point::new(f64_req(p, "cx", cmd)?, f64_req(p, "cy", cmd)?);
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
numbers.extend(["x2", "y2", "direction", "pathLength", "seed", "ringSeed"]);
check_numbers(p, &numbers, cmd)?;
let seed_of = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 0, not {v}"))),
};
let seed = seed_of("seed")?.unwrap_or(DEFAULT_SEED);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) places the rings anew.
let ring_seed = match seed_of("ringSeed")? {
Some(r) if r >= 1 << 53 => return Err(bad(cmd, format!("`ringSeed` must be below 2^53, not {r}"))),
r => r,
};
let rays = count_or(p, "rays", 15, cmd)?.min(50);
let rings = count_or(p, "rings", 10, cmd)?.min(50);
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
(Some(x), Some(y)) => Point::new(x, y),
_ => {
let a = f64_or(p, "direction", 45.0).to_radians();
finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)?
}
};
let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed });
if let Some(r) = ring_seed {
v["ringSeed"] = json!(r);
}
for (key, default) in SETTINGS {
v[key] = json!(f64_or(p, key, default));
}
Ok(v)
}
/// The objects of a flare drawn with the settings `v`, transformed by `xf`. A new flare's parts
/// (`old` None) get new ids and take the document's Align New Objects to Pixel Grid. A flare drawn
/// again from its parts `old` keeps, for each part, the id and pixel-aligned property of the old
/// part it replaces (the same kind of part, counted in order: the second ring replaces the second
/// ring); a part that replaces none gets a new id and the first old part's property.
fn part_nodes(d: &mut Document, v: &Value, xf: Affine, old: Option<&[Arc<Node>]>) -> Vec<Arc<Node>> {
let mut seen: Vec<&str> = vec![];
parts(v)
.into_iter()
.map(|part| {
let name = part.0;
let nth = seen.iter().filter(|n| **n == name).count();
seen.push(name);
let replaced = old.and_then(|old| old.iter().filter(|c| c.name.as_deref() == Some(name)).nth(nth));
let id = replaced.map_or_else(|| d.alloc_id(), |c| c.id);
let mut n = part_node(id, part, Affine::IDENTITY, false);
match old {
None => super::object::align_new_object(d, &mut n),
Some(old) => n.extras_mut().pixel_aligned = replaced.or(old.first()).is_some_and(|c| c.extras().pixel_aligned),
}
if xf != Affine::IDENTITY {
n.transform(xf, false);
}
Arc::new(n)
})
.collect()
}
/// `shape.flare`: a flare group that keeps its settings.
pub(super) fn flare(s: &mut Session, p: &Value) -> Result<Value> {
let v = settings_of(p, "shape.flare")?;
let parent = s.doc()?.target_parent()?;
let id = s.edit("Flare", |d, sel| {
let children = part_nodes(d, &v, Affine::IDENTITY, None);
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = Some("Flare".into());
g.extras_mut().flare = Some(Box::new(FlareSpec::new(v)));
d.insert(parent, usize::MAX, g)?;
sel.set([gid]);
Ok(gid)
})?;
Ok(json!({ "id": id.0 }))
}
/// The settings of flare `id`: a group drawn by the Flare tool whose parts are still the ones its
/// settings draw, in place ([`FlareSpec::draws`]). A flare whose parts were edited, distorted,
/// removed or added to, or whose art was flattened to a line, is no longer one.
pub fn flare_settings(d: &Document, id: NodeId) -> Option<FlareSpec> {
let n = d.node(id)?;
let spec = n.extras().flare.as_deref()?;
// Settings a file holds are read as `shape.flare` reads them.
let spec = FlareSpec { params: settings_of(&spec.params, "shape.flare").ok()?, transform: spec.transform };
spec.draws(n).then_some(spec)
}
/// The flares `shape.editFlare` changes: those `p` names, else the selected flares. Each must be a
/// flare that can be edited.
fn flares_to_edit(s: &Session, p: &Value) -> Result<Vec<(NodeId, FlareSpec)>> {
let given = given_objects(s, p, C)?;
let d = &s.doc()?.doc;
let flare = |id: NodeId| flare_settings(d, id).filter(|_| d.is_editable(id)).map(|spec| (id, spec));
let flares: Vec<(NodeId, FlareSpec)> = match &given {
Some(ids) => ids.iter().map(|id| flare(*id)).collect::<Option<Vec<_>>>().unwrap_or_default(),
None => s.doc()?.selection.objects.iter().filter_map(|id| flare(*id)).collect(),
};
if flares.is_empty() {
return Err(EngineError::Other("select a flare".into()));
}
Ok(flares)
}
/// The settings `old` changed as `p` asks (`shape.editFlare`'s params). The center and the end
/// point `p` gives are in the document, where the flare is now drawn, which `xf` maps from where
/// it was drawn.
fn edited(old: &Value, p: &Value, xf: Affine) -> Result<Value> {
let mut v = old.clone();
let inv = xf.inverse();
let point = |kx: &str, ky: &str| -> Result<Option<Point>> {
if p.get(kx).is_none_or(Value::is_null) && p.get(ky).is_none_or(Value::is_null) {
return Ok(None);
}
// A point that leaves the finite range where the flare was drawn is refused, not stored.
let q = inv * Point::new(f64_req(p, kx, C)?, f64_req(p, ky, C)?);
match [(kx, q.x), (ky, q.y)].into_iter().find(|(_, v)| !v.is_finite()) {
None => Ok(Some(q)),
Some((key, _)) => Err(bad(C, format!("{key} must be a finite coordinate"))),
}
};
let c = point("cx", "cy")?;
let end = point("x2", "y2")?;
if let Some(c) = c {
v["cx"] = json!(c.x);
v["cy"] = json!(c.y);
}
let centre = Point::new(f64_or(&v, "cx", 0.0), f64_or(&v, "cy", 0.0));
let old_end = Point::new(f64_or(&v, "x2", centre.x), f64_or(&v, "y2", centre.y));
let end = match end {
Some(e) => e,
None if p.get("pathLength").is_some_and(|l| !l.is_null()) || p.get("direction").is_some_and(|a| !a.is_null()) => {
// The path length and the direction are where the flare is drawn now; the direction is
// measured counter-clockwise from 3 o'clock, as `shape.flare` takes it.
let (c, e) = (xf * centre, xf * old_end);
let d = e - c;
let a = number_or(p, "direction", (-d.y).atan2(d.x).to_degrees(), C)?.to_radians();
finite_end(inv * (c + Vec2::new(a.cos(), -a.sin()) * number_or(p, "pathLength", d.hypot(), C)?), C)?
}
// Moving the center leaves the rings' end point where it is.
None => old_end,
};
v["x2"] = json!(end.x);
v["y2"] = json!(end.y);
for (key, _) in SETTINGS {
if p.get(key).is_some_and(|x| !x.is_null()) {
v[key] = json!(number_or(p, key, 0.0, C)?);
}
}
for key in ["rays", "rings"] {
if p.get(key).is_some_and(|x| !x.is_null()) {
v[key] = json!(count_or(p, key, 0, C)?.min(50));
}
}
settings_of(&v, C)
}
/// `shape.editFlare`: draw the flares again with the settings `p` changes, each in its place and
/// transformed as it has been since it was drawn, as one undo step.
pub(super) fn edit_flare(s: &mut Session, p: &Value) -> Result<Value> {
let mut numbers: Vec<&str> = SETTINGS.iter().map(|(key, _)| *key).collect();
numbers.extend(["cx", "cy", "x2", "y2", "pathLength", "direction", "rays", "rings"]);
check_numbers(p, &numbers, C)?;
let flares = flares_to_edit(s, p)?;
let mut changed: Vec<(NodeId, FlareSpec)> = vec![];
for (id, spec) in &flares {
let v = edited(&spec.params, p, spec.transform)?;
if !json_close(&v, &spec.params, 1e-9) {
changed.push((*id, FlareSpec { params: v, transform: spec.transform }));
}
}
let ids: Vec<u64> = flares.iter().map(|(id, _)| id.0).collect();
// Nothing changes: no undo step.
if changed.is_empty() {
return Ok(json!({ "ids": ids }));
}
let edited_ids: Vec<NodeId> = changed.iter().map(|(id, _)| *id).collect();
s.edit("Edit Flare", |d, _| {
for (id, spec) in changed {
let old: Vec<Arc<Node>> = d.node(id).and_then(Node::children).cloned().unwrap_or_default();
let children = part_nodes(d, &spec.params, spec.transform, Some(&old));
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().flare = Some(Box::new(spec));
}
if !crate::sanity::objects_in_range(d, &edited_ids) {
return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()));
}
Ok(())
})?;
Ok(json!({ "ids": ids }))
}
+2 -19
View File
@@ -19,23 +19,6 @@ use crate::DocState;
const MAX_FONTS: usize = 1_000;
/// The longest family or style name listed or given (bytes).
const MAX_NAME: usize = 256;
/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place
/// of a font and no font file provides; compared in any ASCII case. The list leaves out
/// `fangsong`, which is also the family name of a Chinese font (FangSong).
const GENERIC_FAMILIES: &[&str] = &[
"serif",
"sans-serif",
"monospace",
"cursive",
"fantasy",
"system-ui",
"ui-serif",
"ui-sans-serif",
"ui-monospace",
"ui-rounded",
"math",
"emoji",
];
/// The longest folder path given (bytes).
const MAX_PATH: usize = 4096;
/// The most files one `text.addFontFiles` copies: as many as a search keeps.
@@ -105,10 +88,10 @@ pub struct MissingFont {
/// The fonts the type of `d` uses, in its layers, symbols and patterns, opacity masks included (a composite font's parts, those
/// its characters are drawn in, in place of its name), that aren't available as named (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
/// ([`vectorcraft_text::GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
let db = FontDb::global();
let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim()));
let generic = vectorcraft_text::is_generic_family;
let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect();
// Sorted by family and style: the versions type names of one face are neighbors.
used.dedup();
+66 -2
View File
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
super::typecmd::export_overflow_warning(&overflow)
}
/// The objects behind production findings. Resource art points to its first visible owner on
/// the canvas, so a finding can be located without selecting an id outside the layer tree.
#[derive(Default)]
pub(super) struct PreflightType {
pub fonts: BTreeMap<UsedFont, BTreeSet<NodeId>>,
pub overflow: BTreeSet<NodeId>,
pub images: BTreeMap<NodeId, NodeId>,
}
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> PreflightType {
let mut walk = Printed::new(d);
walk.preflight = Some(PreflightType::default());
for l in layers {
walk.node(l, Some(areas));
}
walk.preflight.unwrap_or_default()
}
/// The walk of [`printed_type`].
struct Printed<'a> {
d: &'a Document,
@@ -546,13 +564,25 @@ struct Printed<'a> {
/// The symbols and patterns whose art was walked.
symbols: BTreeSet<String>,
patterns: BTreeSet<String>,
preflight: Option<PreflightType>,
owner: Option<NodeId>,
}
impl<'a> Printed<'a> {
/// A walk of `d` among its own objects, nothing found yet.
fn new(d: &'a Document) -> Self {
let boxes = d.symbol_boxes();
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
Self {
d,
boxes,
own: true,
fonts: BTreeSet::new(),
overflow: BTreeSet::new(),
symbols: BTreeSet::new(),
patterns: BTreeSet::new(),
preflight: None,
owner: None,
}
}
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
@@ -560,6 +590,15 @@ impl<'a> Printed<'a> {
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
/// object) all of them but those outside the clipping path of a clip group.
fn node(&mut self, n: &Node, areas: Option<&[Rect]>) {
let previous = self.owner;
if self.own {
self.owner = Some(n.id);
}
self.node_contents(n, areas);
self.owner = previous;
}
fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) {
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
return;
}
@@ -571,6 +610,14 @@ impl<'a> Printed<'a> {
&& !open
&& !self.meets(n, a)
{
// An entirely overset frame paints nothing, but is still a delivery problem. Keep
// the export walk unchanged; only preflight checks the frame itself in this case.
if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind)
&& n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b)))
&& vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow
{
p.overflow.insert(owner);
}
return;
}
// The art that its opacity mask, pattern paints and brushed strokes draw.
@@ -616,16 +663,33 @@ impl<'a> Printed<'a> {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
for r in runs {
self.fonts.extend(run_fonts(r));
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
}
}
}
NodeKind::Image(_) => {
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.images.entry(n.id).or_insert(owner);
}
}
NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol),
NodeKind::PlacedDocument(p) => {
if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) {
report.images.entry(n.id).or_insert(owner);
}
for art in p.art(n) {
self.art(&art);
}
+34 -7
View File
@@ -13,6 +13,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, Rect};
use super::buildcmds::LivePaintMove;
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
@@ -83,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layer Options…",
["Window", "Layers"],
None,
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step",
has_doc,
set_props
),
@@ -110,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). A row that goes into a Live Paint group from elsewhere joins its paths as livePaint.merge adds them, and the group is selected (paths, compound paths, groups of them and Live Paint groups; anything else is refused and nothing moves); a row that goes into or leaves a Live Paint group's paths makes the group's faces and edges again, keeping the paint of those that stay. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids} (a row that joined a Live Paint group is listed as the group)",
has_doc,
move_rows
),
@@ -119,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
has_doc,
move_node
),
@@ -625,12 +626,22 @@ fn highlight(s: &mut Session, p: &Value) -> Result<Value> {
"add" | "toggle" => {}
other => return Err(bad(C, format!("mode is set, add or toggle, not `{other}`"))),
}
// `rows` keeps the highlight order. With more than 8 ids, `held` holds the same rows as a set and
// answers each lookup; with fewer, each lookup searches `rows`.
let mut held: Option<HashSet<NodeId>> = (ids.len() > 8).then(|| rows.iter().copied().collect());
let mut last = None;
for id in ids {
if mode == "toggle" && rows.contains(&id) {
let has = held.as_ref().map_or_else(|| rows.contains(&id), |h| h.contains(&id));
if mode == "toggle" && has {
rows.retain(|r| *r != id);
} else if !rows.contains(&id) {
if let Some(h) = &mut held {
h.remove(&id);
}
} else if !has {
rows.push(id);
if let Some(h) = &mut held {
h.insert(id);
}
last = Some(id);
}
}
@@ -651,6 +662,10 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "no rows"));
}
if let Some(v) = str_param(p, "name").filter(|v| !v.trim().is_empty()) {
let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() };
super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?;
}
s.edit("Layer Options", |d, sel| {
for id in &ids {
apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id);
@@ -807,7 +822,15 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if parent.is_some_and(|p| locked_within(d, p)) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
// Rows that go into a Live Paint group join its paths, as Live Paint › Merge adds them.
let live_paint = LivePaintMove::plan(d, &ids, parent, copy)?;
let label = if live_paint.joins() {
"Merge Live Paint"
} else if copy {
"Duplicate Rows"
} else {
"Move Rows"
};
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
// Intertwine groups it leaves.
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
@@ -848,6 +871,7 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
}
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
super::intertwine::settle_members(d, &placed, &left)?;
let out = live_paint.finish(d, sel, &out)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(out)
@@ -870,11 +894,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
let live_paint = LivePaintMove::plan(d, &[id], parent, false)?;
let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" };
let from = d.parent_of(id);
let left = super::intertwine::groups_of(d, &[id]);
s.edit("Reorder", |d, sel| {
s.edit(label, |d, sel| {
d.move_node(id, parent, index)?;
super::intertwine::settle_members(d, &[(id, from)], &left)?;
live_paint.finish(d, sel, &[id])?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(())
+3 -2
View File
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Locate Object",
["Window", "Layers"],
None,
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
"{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
has_doc,
locate
),
@@ -437,7 +437,8 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "layer.locate")?;
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
let st = s.doc_mut()?;
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
// With no id, the frontmost selected object in the stacking order, whatever order it was selected in.
let id = id.or_else(|| st.selection.in_paint_order(&st.doc).last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
if layers_only {
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
+3 -2
View File
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unembed",
[],
None,
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
has_doc,
unembed
),
@@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) ->
/// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a
/// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels
/// can't be read ([`readable`]).
/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image
/// is read with the clipping path it keeps ([`fileio::raster_image`]).
fn linked_image(bytes: &[u8], path: Option<&str>) -> Result<RasterImage> {
let mut img = super::place::dcs::raster(bytes, path)?;
img.blob = readable(img.blob, kept_unread(bytes), true)?;
+38 -1
View File
@@ -214,6 +214,25 @@ fn spine_points_param(p: &Value, cmd: &str) -> Result<Vec<usize>> {
list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect()
}
/// Whether linking handle `out` of spine point `index` at `q` would leave the blend's spine as it
/// is (false when the blend or the point is not there, for the edit to report it).
fn spine_link_unchanged(s: &Session, p: &Value, cmd: &str, index: usize, out: bool, q: Point) -> Result<bool> {
let id = match crate::cmd::object_param(p, "id", cmd)? {
Some(id) => Some(id),
None => selected_of(s, is_blend).first().copied(),
};
let d = &s.doc()?.doc;
let Some(NodeKind::Blend { children, spec }) = id.and_then(|id| d.node(id)).map(|n| &n.kind) else { return Ok(false) };
let Some((path, _)) = live::pin_spine(children, spec) else { return Ok(false) };
Ok(path.subpaths.first().is_some_and(|sp| {
sp.anchors.get(index).is_some_and(|a| {
let mut linked = *a;
linked.link_handle(out, q, sp.has_segment(index, !out));
linked == *a
})
}))
}
pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.spine.moveAnchor";
let index = index_param(p, "anchor", C)?;
@@ -225,15 +244,33 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
let link = switch_or(p, "link", false, C)?;
let with = spine_points_param(p, C)?;
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
if link && independent {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
if link && handle.is_none() {
return Err(bad(C, "`link` places a handle: give `handle`"));
}
if link && let Some(out) = handle {
// A spine point the linked handles would leave as it is records no undo step.
if spine_link_unchanged(s, p, C, index, out, q)? {
return ok();
}
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
a.set_handle(out, q, independent);
if link {
a.link_handle(out, q, pull_out);
} else {
a.set_handle(out, q, independent);
}
return Ok(());
}
let delta = q - a.p;
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Spine Point",
[],
None,
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
+126 -16
View File
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Object Mosaic…",
["Object"],
None,
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}",
"{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}",
has_image,
object_mosaic
),
@@ -970,7 +970,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> {
}
}
fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles'
/// placement, their size and spacing in image pixels, and the options.
struct MosaicPlan {
id: NodeId,
im: ImageObject,
cols: u32,
rows: u32,
xf: Affine,
tile: (f64, f64),
gap: (f64, f64),
gray: bool,
delete: bool,
}
/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the
/// image or changing the document.
fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
const C: &str = "object.createObjectMosaic";
let st = s.doc()?;
let id = st
@@ -980,28 +996,97 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
.copied()
.find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_))))
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?;
let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?;
let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32;
let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32;
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
return Err(bad(C, "the image has no embedded pixels"));
}
let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32;
let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32;
let gray = switch_or(p, "gray", false, C)?;
let colors = vectorcraft_trace::mosaic(&raster, cols, rows);
let percentages = switch_or(p, "percentages", false, C)?;
// A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it.
let side = |key: &str, v: &Value, also: &str| match v.as_str() {
Some("width") => Ok(true),
Some("height") => Ok(false),
_ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))),
};
let constrain = match p.get("constrain") {
None | Some(Value::Null) => None,
Some(v) => Some(side("constrain", v, "")?),
};
// Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out).
let use_ratio = match p.get("useRatio") {
None | Some(Value::Null | Value::Bool(false)) => None,
Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)),
Some(v) => Some(side("useRatio", v, ", true, false")?),
};
// Tiles in image space, placed by the image transform (scaled to a new size if asked).
let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?;
let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1));
let resize = Affine::translate(b.origin().to_vec2())
* Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9))
* Affine::translate(-b.origin().to_vec2());
let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9));
// A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's.
let size = |key: &str, base: f64| -> Result<f64> {
let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) };
let (min, max) = (0.1, 1_000_000.0);
if !(min..=max).contains(&x) {
return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})")));
}
Ok(if percentages { base * x / 100.0 } else { x })
};
let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?);
// Constrain Ratio keeps the image's proportions: the named side leads and the other follows.
match constrain {
Some(true) => nh = nw * bh / bw,
Some(false) => nw = nh * bw / bh,
None => {}
}
// A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side
// Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it.
let (nw, nh) = match constrain {
Some(_) => {
let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh));
// Proportions over 10,000,000 to 1 leave no size with both sides within the range.
if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) {
return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt"));
}
(nw * k, nh * k)
}
None => (nw.max(0.1), nh.max(0.1)),
};
let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2());
let xf = resize * im.xf;
let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64);
// Spacing is in points; convert to image pixels along each axis.
// Points per image pixel along each of the image's axes (the image may be turned).
let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9);
let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9);
let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9));
let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0));
let (iw, ih) = (im.width as f64, im.height as f64);
// Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side,
// measured along the image's axes.
match use_ratio {
Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy),
Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx),
None => {}
}
let (tw, th) = (iw / cols as f64, ih / rows as f64);
// Spacing is in points; convert to image pixels along each axis.
let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9));
let delete = switch_or(p, "deleteRaster", false, C)?;
Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete })
}
/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio
/// included, without making the mosaic (the dialog's Use Ratio button shows them).
pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> {
mosaic_plan(s, p).map(|m| (m.cols, m.rows))
}
fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.createObjectMosaic";
let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?;
let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?;
let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?;
let colors = vectorcraft_trace::mosaic(&raster, cols, rows);
let (gid, n) = s.edit("Create Object Mosaic", |d, sel| {
let mut tiles = vec![];
for r in 0..rows {
@@ -1039,7 +1124,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result<Value> {
sel.set([gid]);
Ok((gid, n))
})?;
Ok(json!({ "id": gid.0, "tiles": n }))
Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows }))
}
/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square
/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long.
/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at
/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all
/// lengths in points.
pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 {
let drawn = |len: f64, n: u32, gap: f64| {
let cell = len / n.max(1) as f64;
cell - gap.max(0.0).min(cell * 0.9)
};
let side = drawn(kept_len, kept, kept_gap);
if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) {
return 1;
}
// A tile on this side shrinks as the count grows: find the first count whose tile is no wider
// than `side`, then take it or the count before it, whichever is closer.
let (mut lo, mut hi) = (1u32, 1000u32);
while lo < hi {
let mid = (lo + hi) / 2;
if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid }
}
let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs();
if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo }
}
fn polygon_path(pts: &[Point]) -> PathData {
+1
View File
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
pub use transform::{reflect_axis, scale_factors, shear_tangent};
+12 -7
View File
@@ -371,16 +371,21 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
/// inside it; → the group when paths were added.
/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does,
/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]).
/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group
/// that paths were added to.
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
let d = &s.doc()?.doc;
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
return Ok(None);
let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default();
let left: Vec<NodeId> = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect();
let mut added = None;
for g in left {
if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? {
added = Some(g);
}
}
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
Ok(added)
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
+3 -3
View File
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shear…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection,
shear
),
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exit Isolation Mode",
[],
None,
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each",
has_doc,
exit_isolation
),
@@ -259,7 +259,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Object Properties",
[],
None,
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind",
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already",
has_doc,
set_props
),
+3
View File
@@ -65,6 +65,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
})
};
let d = &s.doc()?.doc;
if let Some(v) = str_param(p, "name") {
crate::cmd::buildcmds::check_part_name(d, &ids, v)?;
}
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
let transparency = opacity.is_some() || blend.is_some();
+49 -16
View File
@@ -369,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
if sx == 0.0 || sy == 0.0 {
return Err(bad("object.scale", "scale must be non-zero"));
}
let sx = f64_req(p, "sx", "object.scale")?;
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
let frame = basis_frame(s, p, "object.scale", &ids)?;
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
}
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
/// either factor is 0.
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
let (sx, sy) = (sx / 100.0, sy / 100.0);
if sx == 0.0 || sy == 0.0 {
return Err("scale must be non-zero".into());
}
Ok((sx, sy))
}
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
@@ -402,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
let named = match p.get("axis") {
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
Some(Value::Number(_)) => None,
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
}
};
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
let m = match named {
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
None => {
@@ -423,12 +421,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
apply_transform(s, "Reflect", ids, about(o, m), p, true)
}
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
/// which is a line on the page; or the error for any other value.
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
match axis {
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
Some(Value::Number(_)) => Ok(None),
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
}
}
}
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
/// angle outside -359 to 359, or ±90 or ±270, is an error.
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
if !(-359.0..=359.0).contains(&angle) {
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
}
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
let flat = angle.rem_euclid(180.0);
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
}
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
}
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["angle"], "object.shear")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
let m = match p.get("axis") {
+1 -1
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attributes",
[],
None,
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
"{ids?|id?, item?, target?: \"object\"|\"contents\"} → {ids, overprintFill, overprintStroke, showCenter, imageMap: \"none\"|\"rectangle\"|\"polygon\", url, note, fillRule: \"nonZero\"|\"evenOdd\" (of the paths and compound paths in them), reversed (their subpaths run counter-clockwise on screen: Reverse Path Direction On), recentUrls: [newest first, at most 30]} the Attributes panel's values for `ids` or the selection, overprint aimed as object.setOverprint aims; a value is null where they differ (or nothing has a fill, stroke or path)",
has_doc,
|s, p| Ok(attributes(s, p)?.to_json())
),
+64 -19
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
has_doc,
package
)]
@@ -113,27 +113,65 @@ thread_local! {
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
}
let data =
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
vectorcraft_format::load(&data?).ok()
/// The native document a linked file is or carries ([`carried_document`]).
enum Carried {
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
/// without editing data.
Absent,
/// The native document, read.
Readable(Box<Document>),
/// The file is a native document, or carries one, that can't be read: a damaged native file,
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
/// whose attachments are too many to search to their end, or editing data that doesn't read as
/// a native document.
Unreadable,
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file.
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
}
if super::place::document::is_pdf(name, bytes) {
// A PDF that can't be opened may carry editing data all the same.
return match vectorcraft_pdf::open_pdf(bytes, None) {
// Attachments left unsearched may list another editing file, which can't be checked.
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
// An editing file listed whose data can't be resolved can't be checked either.
Ok(opened) => match opened.editing() {
Some(e) => read(&e.data),
None if opened.has_editing_file() => Carried::Unreadable,
None => Carried::Absent,
},
Err(_) => Carried::Unreadable,
};
}
if !vectorcraft_eps::has_native(bytes) {
return Carried::Absent;
}
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
}
/// The error for a linked file the package would copy whose native document can't be read to
/// check the files and folders it names against the read roots.
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
/// relative path taken from the file's folder): the copy would name it.
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
/// whose native document can't be read is refused, as its links can't be checked. The error names
/// no file or folder.
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
None => Ok(()),
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
Carried::Unreadable => Err(bad(C, UNREADABLE)),
Carried::Absent => Ok(()),
}
}
@@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
Err(bad(C, FOLDER_OUTSIDE))
}
Carried::Unreadable => Err(bad(C, UNREADABLE)),
_ => Ok(()),
}
}
@@ -498,6 +539,9 @@ pub struct Package {
root: Option<PathBuf>,
info: Option<String>,
doc: std::sync::Arc<Document>,
/// The read roots in force where the package was prepared: [`Package::write`] collects under
/// them.
scope: crate::file_access::ScopeHandle,
}
impl Session {
@@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
let doc = s.doc()?.doc.clone();
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
let scope = crate::file_access::ScopeHandle::capture();
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
}
impl Package {
/// Collect the linked files and fonts and write the package's files with `write` into
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
/// `file.package`.
/// `file.package`, with the read roots in force where it was prepared, on any thread.
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
collect_and_write(self, write)
self.scope.clone().run(|| collect_and_write(self, write))
}
}
/// [`Package::write`].
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
let mut doc = (*original).clone();
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
+16 -10
View File
@@ -274,8 +274,9 @@ impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
/// each selected object's own stack is compared. One walk of the document, so callers that ask
/// every frame cache it by revision.
/// each selected object's own stack is compared. The selected objects are found through the id
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
/// of the document, so callers that ask every frame cache it by revision.
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
self.proxy_mixed_with(item, &[])
}
@@ -290,15 +291,17 @@ impl DocState {
if self.selection.symbol_part.is_some() {
return (false, false);
}
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
self.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
let (mut selected, mut nodes) = (vec![], vec![]);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
#[cfg(test)]
tests::note_gathered();
selected.push(n);
painted(n, true, &mut nodes);
}
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
@@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
}
s.execute("object.setProps", &Value::Object(q))
}
#[cfg(test)]
mod tests;
+335
View File
@@ -0,0 +1,335 @@
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
//! reads only those.
use std::cell::Cell;
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
/// [`gathered`] of this thread.
static GATHERED: Cell<u64> = const { Cell::new(0) };
}
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
pub(super) fn note_gathered() {
GATHERED.set(GATHERED.get() + 1);
}
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
fn gathered() -> u64 {
GATHERED.get()
}
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
if st.selection.is_empty() {
return (false, false);
}
if st.selection.symbol_part.is_some() {
return (false, false);
}
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let (mut selected, mut nodes) = (vec![], vec![]);
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
painted(n, true, &mut nodes);
}
});
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
});
let Some(p0) = paints.next() else { return false };
paints.any(|p| !same_in_proxy(&p0, &p))
};
(differ(false), differ(true))
}
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
/// and with and without `points`, with the id cache built and without it.
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
for cold in [true, false] {
if cold {
st.doc.drop_lookup_cache();
}
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
for points in [points, &[]] {
assert_eq!(
st.proxy_mixed_with(item, points),
walked(st, item, points),
"{what}: item {item:?}, {} picked points, cold cache {cold}",
points.len()
);
}
}
}
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
id
}
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
/// different fills or strokes, a group with different contents, a group with one of its objects,
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
/// gradient mesh with points picked beside another object, ids not in the document and an id that
/// appears twice (a damaged file) with different paints.
#[test]
fn the_question_marks_match_a_walk_of_the_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
// Two fills: [Fill, Stroke, Fill].
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
let missing = NodeId(999_999);
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
let points = vec![(mesh, vec![p00, p01])];
let points_alike = vec![(mesh, vec![p01, p11])];
let selections = [
vec![a],
vec![a, b],
vec![b, a],
vec![a, h],
vec![g],
vec![g, e],
vec![e, g],
vec![f, e],
vec![c],
vec![c, a],
vec![a, c],
vec![mesh],
vec![mesh, a],
vec![a, mesh, h],
vec![hidden],
vec![hidden, b],
vec![missing],
vec![missing, a],
vec![a, missing, b],
vec![a, a],
];
let check = |s: &mut Session, what: &str| {
for sel in &selections {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
agree(st, &points, &format!("{what}: {sel:?}"));
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
}
s.execute("select.all", &json!({})).unwrap();
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
};
check(&mut s, "unique ids");
// A second node with a's id and another fill, at the end of the tree.
let st = s.active_mut().unwrap();
let mut copy = st.doc.node(a).unwrap().clone();
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let doc = Arc::make_mut(&mut st.doc);
let last = doc.layers.len() - 1;
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
doc.drop_lookup_cache();
check(&mut s, "a repeated id");
let st = s.active_mut().unwrap();
st.selection.objects = vec![a];
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
}
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(612.0, 792.0);
d.layers.clear();
let mut rects = vec![];
for l in 0..layers {
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
for _ in 0..groups {
let children = (0..per_group)
.map(|_| {
let id = d.alloc_id();
let mut ap = Appearance::default_art();
let red = rects.len() % 2 == 0;
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
rects.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
})
.collect();
let group = Node::group(d.alloc_id(), children);
layer.children_mut().unwrap().push(Arc::new(group));
}
d.layers.push(Arc::new(layer));
}
(d, rects)
}
fn state(doc: Document) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
s.active_mut().unwrap().doc = Arc::new(doc);
s
}
/// With one object selected, the "?" reads only that object, not every node of the document, and
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
/// once.
#[test]
fn the_question_marks_read_only_the_selected_objects() {
let (doc, rects) = big(2, 40, 25);
let mut s = state(doc);
let st = s.active_mut().unwrap();
st.selection.objects = vec![rects[777]];
assert_eq!(st.proxy_mixed(None), (false, false));
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (false, false));
assert_eq!(gathered() - read, 1, "only the selected object is read");
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
st.selection.objects = vec![rects[3], rects[1500]];
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
st.selection.objects = rects.clone();
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
assert_eq!(st.proxy_mixed(None), (true, false));
assert_eq!(gathered() - read, rects.len() as u64);
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
}
/// Random selections of a document with nested groups answer as a walk does.
#[test]
fn random_selections_match_a_walk_of_the_document() {
let (doc, rects) = big(3, 12, 6);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
let mut r = 0x2545_f491_4f6c_dd1d_u64;
let mut next = |n: usize| {
r ^= r << 13;
r ^= r >> 7;
r ^= r << 17;
(r % n as u64) as usize
};
for round in 0..200 {
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> std::time::Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
}
}
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn proxy_mixed_timing() {
let (doc, rects) = big(5, 100, 100);
let mut s = state(doc);
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
let cases: [(&str, Vec<NodeId>); 5] = [
("1 object", vec![rects[25_000]]),
("2 objects, different fills", vec![rects[10], rects[40_001]]),
("a group of 100", vec![groups[250]]),
("all 500 groups", groups.clone()),
("all 50,000 objects", rects.clone()),
];
const CALLS: usize = 200;
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
println!("|---|---|---|---|---|");
for (name, sel) in &cases {
for cold in [false, true] {
let st = s.active_mut().unwrap();
st.selection.objects = sel.clone();
let st = s.active().unwrap();
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
let (mut old, mut new) = (vec![], vec![]);
let calls = if cold { CALLS / 10 } else { CALLS };
for _ in 0..7 {
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
let d = time(|| {
for _ in 0..calls {
if cold {
st.doc.drop_lookup_cache();
}
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
}
});
times.push(d.as_secs_f64() * 1e6 / calls as f64);
}
}
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
println!(
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
if cold { "dropped before each call" } else { "built" },
median(old.clone()),
median(new.clone()),
runs(&old),
runs(&new)
);
}
}
}
+1
View File
@@ -382,6 +382,7 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
("addon.pathtools.cornerSet", "items", "ids"),
("addon.pathtools.cornerRemove", "items", "ids"),
("addon.pathtools.bridge", "radius", "gap"),
("links.unembed", "id", "ids"),
("links.unembed", "path", "folder"),
];
+40 -1
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false",
has_doc,
set_handle
),
@@ -457,6 +457,9 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
let out = str_param(p, "which") != Some("in");
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
if switch_or(p, "link", false, "path.setHandle")? {
return link_handle(s, p, id, si, ai, out, pos);
}
let independent = switch_or(p, "independent", false, "path.setHandle")?;
// A handle already there, on an anchor already of the kind it would get, changes nothing and
// records no undo step. The handle is compared directly: `set_handle` would recompute the
@@ -476,6 +479,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// `path.setHandle` with `link` (the Anchor Point tool's Alt-drag on a handle): the handle goes to
/// (x, y) and the anchor becomes smooth, its other handle turned in line at its own length. A
/// retracted other handle is pulled out to the moved handle's length when a segment leaves the
/// anchor on its side, and stays retracted at an open end. An anchor the edit would leave as it
/// is records no undo step.
fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out: bool, pos: Point) -> Result<Value> {
const C: &str = "path.setHandle";
if switch_or(p, "independent", false, C)? {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
return Err(bad(C, "x and y must be finite"));
}
if s.script_running() {
return Err(EngineError::Busy);
}
let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| {
sp.anchors.get(ai).is_some_and(|a| {
let mut linked = *a;
linked.link_handle(out, pos, sp.has_segment(ai, !out));
linked == *a
})
});
if unchanged {
return ok();
}
s.edit("Reshape", |d, _| {
let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
let pull_out = sp.has_segment(ai, !out);
let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
a.link_handle(out, pos, pull_out);
Ok(())
})?;
ok()
}
/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point
/// tool's Shift-drag).
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+8 -4
View File
@@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result<Value> {
Ok(out)
}
/// Resolution at a placed image's transform: 72 points per inch over each pixel axis.
pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] {
let [a, b, c, d, ..] = xf.as_coeffs();
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
[ppi(a, b), ppi(c, d)]
}
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "image.info";
let st = s.doc()?;
@@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
let doc = super::links::with_brush_art(&st.doc);
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
let [a, b, c, d, ..] = im.xf.as_coeffs();
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
let size = n.geometric_bounds().unwrap_or_default();
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
let doc_path = super::links::LinkBase::of(st).doc;
@@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
"pixelWidth": im.width,
"pixelHeight": im.height,
"ppi": [ppi(a, b), ppi(c, d)],
"ppi": effective_ppi(im.xf),
"width": size.width(),
"height": size.height(),
}))
-2
View File
@@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
})?;
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
Ok(doc)
}
+15 -3
View File
@@ -161,6 +161,8 @@ pub struct FilterRun {
parent: Option<NodeId>,
/// The document it was made from, and that document's revision then.
document: (u64, u64),
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
limits: vectorcraft_plugins::Limits,
}
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
@@ -245,7 +247,11 @@ impl FilterRun {
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
let limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
/// The plug-in, for its name and budget.
@@ -274,7 +280,13 @@ impl FilterRun {
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
/// two slices of its budget.
pub fn run(&self) -> Result<Vec<u8>> {
self.plugin.run(&self.input, &self.params).map_err(err)
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
@@ -289,7 +301,7 @@ impl FilterRun {
let may = self.plugin.manifest().permissions();
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
}
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
@@ -88,6 +88,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.type.textTweaker",
"addon.units.convert",
"addon.units.selectionSize",
"app.toast",
"appearance.addEffect",
"appearance.addFill",
"appearance.addStroke",
@@ -177,6 +178,7 @@ pub(super) const ALLOWED: &[&str] = &[
"edit.duplicate",
"edit.findNext",
"edit.findReplace",
"edit.replaceMatch",
"effect.apply",
"effect.deferredStatus",
"effect.duplicate",
@@ -555,6 +557,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.update",
"shape.arc",
"shape.circleThroughPoints",
"shape.editFlare",
"shape.ellipse",
"shape.flare",
"shape.line",
@@ -689,6 +692,7 @@ pub(super) const ALLOWED: &[&str] = &[
"type.pathOptions",
"type.resetHorizontalScale",
"type.resetTracking",
"type.retype",
"type.ruby",
"type.scaleTextAttributes",
"type.size.decrease",
+133
View File
@@ -0,0 +1,133 @@
//! Production preflight: the existing output-aware type walk, linked-file probes and image
//! resolution calculation, returned as findings that the interface can locate and recheck.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_text::{FontDb, FontMatch};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param};
const COMMAND: &str = "document.preflight";
const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"];
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
query "document.preflight",
"Production Preflight",
[],
None,
"{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file",
has_doc,
check
)]
}
fn check(s: &mut Session, p: &Value) -> Result<Value> {
let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf");
if !matches!(output, "pdf" | "print" | "screen") {
return Err(bad(COMMAND, "output must be pdf, print or screen"));
}
let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?;
if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) {
return Err(bad(COMMAND, "minPpi must be from 1 to 9600"));
}
let indices = match p.get("artboards").filter(|v| !v.is_null()) {
Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?,
None => (0..s.doc()?.doc.artboards.len()).collect(),
};
let context = if output == "print" {
super::print::preflight_context(s, &indices)?
} else {
let doc = &s.doc()?.doc;
let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect();
super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] }
};
let areas = context.pages.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let st = s.doc()?;
let doc = st.doc.with_placed_art();
let mut layers = doc.layers.clone();
vectorcraft_pdf::keep_layers(&mut layers, context.layers);
let typed = super::fonts::preflight_type(&doc, &layers, &areas);
let statuses = super::links::statuses(st);
let mut findings = vec![];
let db = FontDb::global();
for (font, ids) in typed.fonts {
let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) {
None | Some(FontMatch::Missing) => "missingFont",
Some(FontMatch::Style) => "substitutedFont",
_ => continue,
};
findings.push(
json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "name": super::fonts::font_label(&font) }),
);
}
for id in typed.overflow {
findings.push(finding("text", "overflow", id, &doc));
}
let mut resolution_unchecked = 0usize;
for (source, owner) in typed.images {
if let Some((status, _, _)) = statuses.get(&source) {
let code = match status.as_str() {
"missing" => Some("missingLink"),
"modified" => Some("modifiedLink"),
_ => None,
};
if let Some(code) = code {
let mut f = finding("links", code, owner, &doc);
f["sourceId"] = json!(source.0);
findings.push(f);
}
}
// A vector placed document has no single bitmap resolution. Its embedded artwork, and
// resources with their own coordinate systems, must never be certified at a local scale.
if doc.node(source).is_none() || source != owner {
resolution_unchecked += 1;
continue;
}
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else {
resolution_unchecked += 1;
continue;
};
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
let ppi = context
.pages
.iter()
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
let Some(ppi) = ppi else {
resolution_unchecked += 1;
continue;
};
// Inverting the placed-size transform can round an exact threshold slightly down.
if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) {
resolution_unchecked += 1;
} else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) {
let mut f = finding("resolution", "lowResolution", owner, &doc);
f["effectivePpi"] = json!(ppi);
f["threshold"] = json!(min_ppi);
findings.push(f);
}
}
let checks = KINDS.map(|kind| {
let count = findings.iter().filter(|f| f["kind"] == kind).count();
let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 };
let status = if count > 0 {
"failed"
} else if not_checked > 0 {
"notChecked"
} else {
"passed"
};
json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked })
});
Ok(json!({
"output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks,
"findings": findings, "outputWarnings": context.warnings,
"limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."]
}))
}
fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value {
json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) })
}
+10
View File
@@ -157,6 +157,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool),
p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool),
p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool),
p!("holdShortcuts", "General", "Options", "Hold Shortcuts", bool),
p!("keyHoldDelay", "General", "Options", "Hold Shortcut Delay", num(0.2, 1.0, "s")),
p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool),
// Selection & Anchor Display
p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")),
@@ -324,6 +326,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
// Plug-ins & Scratch Disks
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
p!(
"pluginInstructionBudget",
"Plug-ins & Scratch Disks",
"Plug-ins",
"Plug-in Instruction Budget",
choice(&[("normal", "Normal"), ("large", "Large")])
),
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
// User Interface
+26
View File
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
Ok(v)
}
/// Reuse the Print dialog's saved settings and page geometry for production preflight, without
/// printing, writing a file or duplicating its type warnings.
pub(super) struct PreflightContext {
pub layers: PrintLayers,
pub pages: Vec<(Rect, Affine)>,
pub warnings: Vec<String>,
}
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
let settings =
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().join(",") } });
let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?;
super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?;
let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?;
let pages = pv
.sheets
.iter()
.filter_map(|p| {
let to_page = Affine::new(p.transform);
on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page))
})
.collect();
pv.warnings.extend(pv.setting_notes);
Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings })
}
/// The parts of the document (document space) that the pages of `pv` print.
fn areas(pv: &PrintPreview) -> Vec<Rect> {
pv.sheets
+17 -14
View File
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1680,12 +1680,18 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::Array(cs)) => Some(cs),
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
};
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
// at its place its color, without the Global Adjust.
let own: Vec<Option<Color>> = match group {
Some(g) => {
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
}
// The places of groupColors are those of the group's color swatches: a gradient, pattern or
// None swatch keeps its place and paint. A null removes the color swatch at its place, and
// "keep" leaves it its color, without the Global Adjust.
let own: Vec<Color> = match group {
Some(g) => s
.doc()?
.doc
.swatch_groups
.iter()
.find(|x| x.name == g)
.map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).collect())
.unwrap_or_default(),
None => vec![],
};
let new: Vec<Option<Color>> = match group_colors {
@@ -1694,12 +1700,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
.enumerate()
.map(|(i, v)| match v {
Value::Null => Ok(None),
// Past the group's swatches it adds nothing.
Value::String(k) if k == "keep" => match own.get(i) {
Some(Some(c)) => Ok(Some(*c)),
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
None => Ok(None),
},
// Past the group's color swatches it adds nothing.
Value::String(k) if k == "keep" => Ok(own.get(i).copied()),
v => color_value(v)
.map(|c| adjust.apply(c))
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
@@ -1747,6 +1749,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
.map(|g| {
g.swatches
.iter()
.filter(|w| w.paint.color().is_some())
.zip(&new)
.filter(|(w, _)| w.global && !w.is_reserved())
.filter_map(|(w, c)| Some((w, (*c)?)))
@@ -1766,7 +1769,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
.collect();
map.converted.set(false);
let changed = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &f, &lf).run(d, &ids)))?;
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?;
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, true, rename, C)).transpose()?;
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
// Rewriting the group's swatches can change the colors of art linked to them, left out or
// not, and of the patterns it uses. Art that only loses its link keeps its colors and is
+619
View File
@@ -0,0 +1,619 @@
//! Type › Retype (#4934), phase 1: outlined text whose glyph shapes are glyphs of a font the app
//! has becomes live point text again, in that font and size, at the same baseline.
//!
//! Behaviour follows the public description of Illustrator's Retype
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>):
//! select outlined text and Retype finds the fonts that match it, from the fonts on the device among
//! others, for use as live text. Illustrator ranks candidate fonts in a panel; this phase is local
//! and exact instead, and sets the text itself, as #4934 asks. Each selected glyph shape (a path or compound
//! path, inside groups too) is compared with the glyphs of the candidate fonts
//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched
//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object
//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as
//! they are and are reported. Near matches (another version of the font, simplified outlines,
//! merged glyphs) and images are phase 2.
use std::f64::consts::{PI, TAU};
use std::sync::Arc;
use kurbo::{BezPath, Point, Vec2};
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject};
use vectorcraft_text::FontDb;
use vectorcraft_text::retype::{GlyphMatch, RetypeIndex};
use super::edit::selected_roots;
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
/// At most this many shapes are compared.
const MAX_PIECES: usize = 2048;
/// Groups deeper than this are not looked into.
const MAX_DEPTH: usize = 16;
/// Extra families named by `fonts`.
const MAX_FONT_PARAMS: usize = 32;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"type.retype",
"Retype",
["Type"],
None,
"{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches",
has_selected_path,
retype
)]
}
/// A shape to match: a path or compound path, in document space.
struct Piece {
id: NodeId,
/// The group or layer holding it: glyphs of different groups, which may composite
/// differently, never share a line.
parent: Option<NodeId>,
/// Other art (not retyped) lies between it and the shape before it, so the type after that
/// art must stay painted after it: the line ends here.
after_barrier: bool,
path: BezPath,
appearance: Appearance,
/// The shape's own transparency, which the new type takes.
opacity: f32,
blend: vectorcraft_color::BlendMode,
/// The shape has what type cannot take (its own opacity mask, more than one fill or stroke,
/// effects, a brush, width profile or arrowheads): it stays an outline.
keeps_outline: bool,
}
/// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a
/// shape lies before the next one; it starts set for a root that does not follow the last root.
/// `truncated` is set when shapes past [`MAX_PIECES`] or [`MAX_DEPTH`] were left out.
fn collect(n: &Node, parent: Option<NodeId>, depth: usize, barrier: &mut bool, truncated: &mut bool, out: &mut Vec<Piece>) {
if out.len() >= MAX_PIECES || depth > MAX_DEPTH {
*barrier = true;
*truncated = true;
return;
}
// Hidden and locked art is left as it is: a hidden glyph must not come back as visible type.
if !n.visible || n.locked {
*barrier = true;
return;
}
let piece = |path: BezPath, after_barrier: bool| Piece {
id: n.id,
parent,
after_barrier,
path,
appearance: (*n.appearance).clone(),
opacity: n.opacity,
blend: n.blend,
keeps_outline: n.extras().mask.is_some() || !type_can_paint(&n.appearance),
};
match &n.kind {
NodeKind::Group { children, clip: false } => {
for c in children {
collect(c, Some(n.id), depth + 1, barrier, truncated, out);
}
}
// Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one.
NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))),
NodeKind::Compound { children, .. } => {
let mut path = BezPath::new();
for c in children {
match &c.kind {
// A hidden or locked path keeps its whole compound as it is.
NodeKind::Path { path: p, .. } if p.is_closed() && c.visible && !c.locked => path.extend(p.to_bezpath()),
_ => {
*barrier = true;
return;
}
}
}
out.push(piece(path, std::mem::take(barrier)));
}
// Live type, images, clip groups and the rest stay, and the type after them stays after them.
_ => *barrier = true,
}
}
/// Can type's character style paint `ap` as it is: a basic appearance (at most one fill and one
/// stroke, no effects, no item opacity or blend), with a plain stroke?
fn type_can_paint(ap: &Appearance) -> bool {
ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none())
}
/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face.
fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vectorcraft_text::FontFace>> {
let mut families: Vec<String> = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect();
d.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for r in &t.runs {
if !families.contains(&r.style.font_family) && families.len() < vectorcraft_text::retype::MAX_FACES {
families.push(r.style.font_family.clone());
}
}
}
});
let cap = vectorcraft_text::retype::MAX_FACES;
let mut faces = vec![];
'families: for f in &families {
for style in db.styles(f) {
// No more faces are loaded than the index takes.
if faces.len() >= cap {
break 'families;
}
if let Some(face) = db.face(f, &style)
&& !faces.iter().any(|k: &Arc<vectorcraft_text::FontFace>| k.id() == face.id())
{
faces.push(face);
}
}
}
for face in db.loaded_faces() {
if faces.len() >= cap {
break;
}
if !faces.iter().any(|k| k.id() == face.id()) {
faces.push(face);
}
}
faces
}
/// One line of retyped glyphs.
struct Line {
pieces: Vec<NodeId>,
/// What each piece matched, as `pieces`.
matches: Vec<GlyphMatch>,
/// Every glyph the first piece fits, while the line holds only it: the next glyph may tell
/// which one it is (see [`join`]).
first_cands: Vec<GlyphMatch>,
text: String,
face: Arc<vectorcraft_text::FontFace>,
scale: f64,
angle: f64,
origin: Point,
end: Point,
appearance: Appearance,
parent: Option<NodeId>,
opacity: f32,
blend: vectorcraft_color::BlendMode,
}
impl Line {
fn dir(&self) -> Vec2 {
Vec2::new(self.angle.cos(), self.angle.sin())
}
/// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same
/// font, size and turn, on its baseline, after its end)?
fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool {
let size = self.scale * self.face.units_per_em();
let d = m.origin - self.origin;
let dir = self.dir();
let across = d.cross(dir).abs();
pc.parent == self.parent
&& pc.appearance == self.appearance
&& pc.opacity == self.opacity
&& pc.blend == self.blend
&& m.face.id() == self.face.id()
// One size and turn for the whole line: the type sets every glyph at the first one's.
&& (m.scale - self.scale).abs() <= self.scale * 1e-4
// Wrapped: type turned 180° has angles near +π and −π.
&& ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5
&& across < size * 0.05
&& (m.origin - self.end).dot(dir) > -size * 0.25
}
fn push(&mut self, id: NodeId, m: &GlyphMatch) {
// A gap wider than half a space before the glyph is spaces the outlines left no shape for.
let dir = self.dir();
let gap = (m.origin - self.end).dot(dir);
let space = space_advance(&self.face) * self.scale;
if space > 0.0 && gap > space * 0.5 {
let n = ((gap / space).round() as usize).clamp(1, 64);
self.text.extend(std::iter::repeat_n(' ', n));
}
self.text.push(m.ch);
self.pieces.push(id);
self.matches.push(m.clone());
self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale);
}
/// The line of this one's glyphs `from..to`, with its group, paint and transparency.
fn part(&self, from: usize, to: usize) -> Option<Line> {
let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?);
let (first, m) = (ids.first()?, ms.first()?);
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
let mut l = Line {
pieces: vec![*first],
matches: vec![m.clone()],
first_cands: vec![],
text: m.ch.to_string(),
face: m.face.clone(),
scale: m.scale,
angle: m.angle,
origin: m.origin,
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
appearance: self.appearance.clone(),
parent: self.parent,
opacity: self.opacity,
blend: self.blend,
};
for (id, m) in ids.iter().zip(ms).skip(1) {
l.push(*id, m);
}
Some(l)
}
/// The point type that sets this line.
fn text_object(&self, system_layout: bool) -> TextObject {
let style = CharStyle {
font_family: self.face.family.clone(),
font_style: self.face.style.clone(),
// The version that matched, when two of the family and style are loaded.
font_version: (!self.face.version.is_empty()).then(|| self.face.version.clone()),
// Each outlined glyph was drawn on its own; a ligature would draw another shape.
features: vec!["-liga".into()],
size: self.scale * self.face.units_per_em(),
fill: self.appearance.fill_paint(),
stroke: self.appearance.stroke_paint(),
stroke_width: self.appearance.stroke_width(),
..Default::default()
};
let mut style = style;
if let Some(st) = self.appearance.stroke() {
style.stroke_cap = st.cap;
style.stroke_join = st.join;
style.stroke_miter_limit = st.miter_limit;
style.stroke_dash = st.dash.clone();
style.stroke_align = st.align;
}
let mut t = TextObject::point(self.origin, &self.text, style);
if self.angle != 0.0 {
t.xf *= kurbo::Affine::rotate(self.angle);
}
t.para = super::create::new_type_para();
t.system_layout = system_layout;
super::typecmd::refresh_bounds(&mut t);
t
}
/// The first of this line's glyphs its type does not draw as the outlines did: another glyph
/// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
fn first_mismatch(&self, t: &TextObject) -> Option<usize> {
let lay = vectorcraft_text::layout(FontDb::global(), t);
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01);
for (k, m) in self.matches.iter().enumerate() {
let Some(g) = drawn.next() else { return Some(k) };
let at = t.xf * (g.xf * Point::ORIGIN);
if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol {
return Some(k);
}
}
// Ink the outlines did not have: the last glyph is where it went wrong.
drawn.next().map(|_| self.matches.len().saturating_sub(1))
}
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
let mut todo: std::collections::VecDeque<Line> = lines.into();
let mut out = vec![];
while let Some(l) = todo.pop_front() {
let n = l.pieces.len();
// The line's type is laid out over a window from its start that doubles while the type
// draws the window's glyphs as the outlines do, so finding where it stops costs about
// twice the glyphs before that point, not the whole rest of the line each time.
let mut w = 8usize;
loop {
let e = n.min(w);
let Some(part) = l.part(0, e) else { break };
let Some(left) = budget.checked_sub(e) else {
// Unchecked glyphs stay outlines.
unmatched.extend(l.pieces.iter().copied());
break;
};
budget = left;
match part.first_mismatch(&part.text_object(system_layout)) {
// The whole line is drawn as it was: one object.
None if e == n => {
out.push(part);
break;
}
None => w = w.saturating_mul(2),
// The first glyph on its own may still be drawn as it was (a contextual form
// changed it in the line); else it stays an outline. Checked again either way.
Some(0) if n > 1 => {
todo.extend_front_parts(&l, [(0, 1), (1, n)]);
break;
}
Some(0) => {
unmatched.extend(l.pieces.first().copied());
break;
}
// The glyphs before the mismatch, then the rest, each checked as a line of its
// own: the type before the mismatch may draw otherwise without what follows it (a
// font can place a glyph by the glyph after it).
Some(k) => {
todo.extend_front_parts(&l, [(0, k), (k, n)]);
break;
}
}
}
}
out
}
/// Puts parts of a line at the front of the work list, in order.
trait FrontParts {
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]);
}
impl FrontParts for std::collections::VecDeque<Line> {
fn extend_front_parts<const N: usize>(&mut self, l: &Line, ranges: [(usize, usize); N]) {
for (a, b) in ranges.into_iter().rev() {
if let Some(p) = l.part(a, b) {
self.push_front(p);
}
}
}
}
fn space_advance(face: &vectorcraft_text::FontFace) -> f64 {
face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0)
}
/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses,
/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in
/// more than one pose). A line of one shape may turn to another of that shape's candidates to take
/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it
/// tells which. Whether it was added.
fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool {
let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp));
if let Some(mp) = fits(l) {
l.push(pc.id, &mp);
return true;
}
let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false };
let current = current.clone();
let others: Vec<GlyphMatch> = l
.first_cands
.iter()
.flat_map(|c| c.poses())
.filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle))
.collect();
for fp in others {
let mut turned = reposed(l, id, &fp);
if let Some(mp) = fits(&turned) {
turned.push(pc.id, &mp);
*l = turned;
return true;
}
}
false
}
/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it.
fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Line {
pieces: vec![id],
matches: vec![m.clone()],
first_cands: l.first_cands.clone(),
text: m.ch.to_string(),
face: m.face.clone(),
scale: m.scale,
angle: m.angle,
origin: m.origin,
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
appearance: l.appearance.clone(),
parent: l.parent,
opacity: l.opacity,
blend: l.blend,
}
}
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`).
fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option<Line> {
let m = cands.first()?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
pieces: vec![pc.id],
matches: vec![m.clone()],
first_cands: cands.to_vec(),
text: m.ch.to_string(),
face: m.face.clone(),
scale: m.scale,
angle: m.angle,
origin: m.origin,
end: m.origin + dir * (m.face.advance(m.gid) * m.scale),
appearance: pc.appearance.clone(),
parent: pc.parent,
opacity: pc.opacity,
blend: pc.blend,
})
}
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.retype";
let fonts: Vec<String> = match p.get("fonts") {
None | Some(Value::Null) => vec![],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
};
let roots = selected_roots(s)?;
let db = FontDb::global();
let system_layout = s.doc()?.doc.setup.system_layout;
let (lines, unmatched, truncated) = {
let d = &s.doc()?.doc;
let mut pieces = vec![];
let mut truncated = false;
let mut last: Option<(Option<NodeId>, usize)> = None;
// Carried across roots: a selected root that yields no shape (live type, an open path) still
// ends the line.
let mut barrier = true;
for r in &roots {
let Some(n) = d.node(*r) else { continue };
let parent = d.parent_of(*r);
let idx = d.position(*r).map(|(_, i, _)| i);
// A root right after the last one, in the same parent, continues its lines; unselected
// art between two roots is a barrier.
if !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j) {
barrier = true;
}
last = idx.map(|i| (parent, i));
collect(n, parent, 0, &mut barrier, &mut truncated, &mut pieces);
}
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
// Only glyphs with a selected shape's key (segments per contour) can match one: the others are
// not sampled.
let wanted: std::collections::BTreeSet<u64> =
pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
// Nothing to match (every shape stays an outline): no font is read.
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) };
let found: Vec<Vec<GlyphMatch>> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect();
// The face most shapes match, so a glyph several fonts share is set in the same font as
// the glyphs around it.
let mut votes: Vec<(u32, usize)> = vec![];
for ms in &found {
// Each shape votes once for each face it fits.
let mut faces: Vec<u32> = ms.iter().map(|m| m.face.id()).collect();
faces.sort_unstable();
faces.dedup();
for f in faces {
match votes.iter_mut().find(|(v, _)| *v == f) {
Some(v) => v.1 += 1,
None => votes.push((f, 1)),
}
}
}
let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1);
let mut lines: Vec<Line> = vec![];
let mut unmatched = vec![];
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
let mut open = false;
for (pc, ms) in pieces.iter().zip(&found) {
if pc.after_barrier {
open = false;
}
// The shape's candidates in the face most shapes fit (the first such face, as the
// matches come upright and closest first).
let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
if cands.is_empty() {
unmatched.push(pc.id);
open = false;
continue;
}
let joined = match lines.last_mut() {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
if !joined {
lines.extend(new_line(pc, &cands));
}
open = true;
}
// A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn
// art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is
// what was asked for. Lone means alone on its baseline as the outlines lie, before the
// layout check splits lines (tracking and manual kerning split them glyph by glyph).
let lone_pieces: std::collections::HashSet<NodeId> =
lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect();
let mut lines = verified(lines, system_layout, &mut unmatched);
if pieces.len() > 1 {
lines.retain(|l| {
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
if lone {
unmatched.extend(l.pieces.iter().copied());
}
!lone
});
}
(lines, unmatched, truncated)
};
if lines.is_empty() {
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
}
let made = s.edit("Retype", |d, sel| {
let mut ids = vec![];
let mut emptied = vec![];
for l in &lines {
let Some(first) = l.pieces.first() else { continue };
let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?;
let t = l.text_object(system_layout);
let id = d.alloc_id();
let mut node = Node::new(id, NodeKind::Text(Box::new(t)));
// The glyphs' own transparency (the group's, kept, still applies over it).
node.opacity = l.opacity;
node.blend = l.blend;
d.insert(par, idx, node)?;
for pc in &l.pieces {
if let Some((Some(parent), _, _)) = d.position(*pc) {
emptied.push(parent);
}
d.remove(*pc)?;
}
ids.push(id);
}
// A group left holding only the new type (Create Outlines' group) gives way to it, unless
// the group has transparency, effects, a mask or a name of its own, which then keep
// applying to the type inside it. A group left empty goes.
emptied.sort_unstable();
emptied.dedup();
for g in emptied {
let Some(n) = d.node(g) else { continue };
let NodeKind::Group { children, clip: false } = &n.kind else { continue };
let plain = n.opacity == 1.0
&& n.blend == vectorcraft_color::BlendMode::Normal
&& *n.appearance == Appearance::default()
&& n.name.is_none()
// Its mask, Attributes note and the rest of what few objects have stay with it.
&& {
let mut ex = n.extras().clone();
ex.type_outlines = false;
ex == vectorcraft_doc::NodeExtras::default()
}
// Isolation and knockout change how the group composites its type.
&& !n.isolate
&& n.knockout == vectorcraft_doc::Knockout::default()
&& !n.knockout_shape;
let only_type = children.iter().all(|c| ids.contains(&c.id));
if children.is_empty() {
d.remove(g)?;
} else if plain && only_type {
let kids: Vec<Arc<Node>> = children.clone();
let (par, idx, _) = d.position(g).ok_or(EngineError::NoNode(g))?;
d.remove(g)?;
for (i, k) in kids.into_iter().enumerate() {
d.insert(par, idx + i, (*k).clone())?;
}
}
}
let mut keep: Vec<NodeId> = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect();
keep.extend(&ids);
sel.set(keep);
Ok(ids)
})?;
Ok(json!({
"ids": made.iter().map(|i| i.0).collect::<Vec<_>>(),
"texts": lines.iter().map(|l| l.text.clone()).collect::<Vec<_>>(),
"fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
}))
}
#[cfg(test)]
#[path = "retype_tests.rs"]
mod tests;
+539
View File
@@ -0,0 +1,539 @@
use serde_json::json;
use vectorcraft_doc::{NodeId, NodeKind, TextObject};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
/// Point text, outlined: the id of the outlines' group.
fn outlined(s: &mut Session, p: serde_json::Value) -> u64 {
let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap()
}
fn text_of(s: &Session, id: u64) -> TextObject {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text object") };
(**t).clone()
}
fn near(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() <= tol
}
#[test]
fn outlined_point_text_retypes_to_the_same_text_font_size_and_place() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Retype me, 42!", "size": 36, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Retype me, 42!"]), "{r}");
assert_eq!(r["unmatched"], json!([]));
let id = r["ids"][0].as_u64().unwrap();
let t = text_of(&s, id);
assert_eq!(t.plain_text(), "Retype me, 42!");
let st = t.first_style();
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Source Sans 3", "Regular"));
assert!(near(st.size, 36.0, 0.01), "size {}", st.size);
let o = t.xf.translation();
assert!(near(o.x, 40.0, 0.01) && near(o.y, 100.0, 0.01), "baseline start {o:?}");
// The outlines are gone, in one undo step that brings them back.
let d = &s.doc().unwrap().doc;
assert!(d.node(NodeId(g)).is_none(), "the emptied group goes");
s.execute("edit.undo", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(NodeId(g)).is_some() && d.node(NodeId(id)).is_none());
}
#[test]
fn turned_bold_and_serif_type_keeps_its_font_and_angle() {
let mut s = session();
let a = outlined(&mut s, json!({"x": 100, "y": 200, "text": "Bold", "size": 24, "font": "Source Sans 3", "style": "Bold", "rotation": 30}));
let b = outlined(&mut s, json!({"x": 300, "y": 80, "text": "Serif", "size": 18, "font": "Source Serif 4", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Bold", "Serif"]), "{r}");
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
let bold = text_of(&s, ids[0]);
assert_eq!(bold.first_style().font_style, "Bold");
assert!(near(bold.first_style().size, 24.0, 0.01));
// text.create turns as kurbo does: compare the turn the new type has with the old one's.
let turned = kurbo::Affine::translate((100.0, 200.0)) * vectorcraft_geom::rotate_deg(30.0);
for (x, y) in bold.xf.as_coeffs().iter().zip(turned.as_coeffs()) {
assert!(near(*x, y, 1e-3), "{:?} vs {:?}", bold.xf, turned);
}
let serif = text_of(&s, ids[1]);
assert_eq!(serif.first_style().font_family, "Source Serif 4");
assert!(near(serif.first_style().size, 18.0, 0.01));
}
#[test]
fn a_drawn_shape_is_reported_and_left_alone() {
let mut s = session();
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
// With outlines that would match, a bad `fonts` is refused for itself, and nothing changes.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] {
let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string();
assert!(e.contains("fonts must be a list of family names"), "{e}");
}
assert!(s.doc().unwrap().doc == before);
}
#[test]
fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Mix", "size": 30}));
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g, rect]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Mix"]));
assert_eq!(r["unmatched"], json!([rect]));
let d = &s.doc().unwrap().doc;
assert!(matches!(d.node(NodeId(rect)).unwrap().kind, NodeKind::Path { .. }), "the rectangle stays");
}
#[test]
fn two_words_keep_their_space() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "two words", "size": 20}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["two words"]));
}
#[test]
fn craft_fonts_glyphs_retype_too() {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
};
let mut s = session();
let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "漢字です", "size": 20, "font": f.family, "style": f.style}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({"fonts": [f.family]})).unwrap();
assert_eq!(r["texts"], json!(["漢字です"]), "{r}");
assert_eq!(r["fonts"][0]["family"], json!(f.family));
}
fn children_of(s: &Session, g: u64) -> Vec<u64> {
s.doc().unwrap().doc.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect()
}
#[test]
fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 50})).unwrap()["id"].as_u64().unwrap();
// The rectangle goes between A and B, inside the outlines' group.
s.edit("test", |d, _| {
let n = d.node(NodeId(rect)).unwrap().clone();
d.remove(NodeId(rect))?;
d.insert(Some(NodeId(g)), 1, n)?;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["A", "B"]), "{r}");
assert_eq!(r["unmatched"], json!([rect]));
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(children_of(&s, g), vec![ids[0], rect, ids[1]], "A under the rectangle, B over it");
}
#[test]
fn glyphs_of_different_groups_and_transparency_stay_apart() {
let mut s = session();
let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20}));
let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "ed", "size": 20}));
let first_d = children_of(&s, b)[1];
s.edit("test", |d, _| {
d.node_mut(NodeId(b)).unwrap().opacity = 0.5;
d.node_mut(NodeId(first_d)).unwrap().opacity = 0.25;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab", "e", "d"]), "same baseline, other group; d has its own opacity: {r}");
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
let d = &s.doc().unwrap().doc;
assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type");
assert_eq!(d.node(NodeId(b)).unwrap().opacity, 0.5, "the half-transparent group stays");
assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]);
assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over");
}
#[test]
fn live_type_between_glyphs_ends_the_line_too() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap();
s.edit("test", |d, _| {
let n = d.node(NodeId(live)).unwrap().clone();
d.remove(NodeId(live))?;
d.insert(Some(NodeId(g)), 1, n)?;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["A", "B"]), "{r}");
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(children_of(&s, g), vec![ids[0], live, ids[1]], "B stays over the live type");
let t = text_of(&s, ids[0]);
assert!(t.first_style().features.iter().any(|f| f == "-liga"), "glyphs drawn one by one: no ligatures");
}
#[test]
fn an_open_path_along_a_glyph_is_not_a_glyph() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "I", "size": 40}));
s.edit("test", |d, _| {
let glyph = d.node(NodeId(g)).unwrap().children().unwrap()[0].id;
for sp in &mut d.node_mut(glyph).unwrap().path_data_mut().unwrap().subpaths {
sp.closed = false;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches");
}
#[test]
fn live_type_selected_between_loose_glyphs_still_ends_the_line() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap();
let (a, b) = (children_of(&s, g)[0], children_of(&s, g)[1]);
// A, the live type and B as siblings in the layer, as Ungroup leaves them.
s.edit("test", |d, _| {
let (par, idx, _) = d.position(NodeId(g)).unwrap();
let live_n = d.node(NodeId(live)).unwrap().clone();
let (an, bn) = (d.node(NodeId(a)).unwrap().clone(), d.node(NodeId(b)).unwrap().clone());
d.remove(NodeId(live))?;
d.remove(NodeId(g))?;
d.insert(par, idx, an)?;
d.insert(par, idx + 1, live_n)?;
d.insert(par, idx + 2, bn)?;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a, live, b]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["A", "B"]), "the selected live type between them ends the line: {r}");
}
#[test]
fn glyphs_selected_inside_groups_join_only_their_siblings() {
let mut s = session();
let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20}));
let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "ed", "size": 20}));
let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]);
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["ab", "e"]), "a and b are siblings; e is in another group: {r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it");
}
#[test]
fn tracked_type_splits_where_its_spacing_cannot_be_set_again() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abe", "size": 30})).unwrap()["id"].as_u64().unwrap();
// Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two
// spaces in this font, and the outlines cannot tell those apart from tracking).
s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), "abe", "{r}");
assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}");
assert_eq!(r["unmatched"], json!([]));
}
#[test]
fn a_masked_glyph_stays_an_outline() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let a = children_of(&s, g)[0];
s.edit("test", |d, _| {
let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default());
d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["B"]), "{r}");
assert_eq!(r["unmatched"], json!([a]));
assert!(s.doc().unwrap().doc.node(NodeId(a)).unwrap().extras().mask.is_some(), "A keeps its mask");
}
#[test]
fn shapes_past_the_limits_are_reported_as_left_out() {
let mut s = session();
let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40}));
// B, deeper than Retype looks.
s.edit("test", |d, _| {
let (par, idx, _) = d.position(NodeId(deep)).unwrap();
let mut n = d.node(NodeId(deep)).unwrap().clone();
d.remove(NodeId(deep))?;
for _ in 0..20 {
n = vectorcraft_doc::Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]);
}
let wrapper = n.id.0;
d.insert(par, idx, n)?;
Ok(wrapper)
})
.map(|w| s.execute("select.set", &json!({"ids": [top, w]})).unwrap())
.unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["A"]));
assert_eq!(r["truncated"], json!(true), "{r}");
}
#[test]
fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let a = children_of(&s, g)[0];
s.edit("test", |d, _| {
let n = d.node_mut(NodeId(a)).unwrap();
let mut ap = (*n.appearance).clone();
let fill = ap.items.iter().find(|i| i.is_fill()).unwrap().clone();
ap.items.push(fill);
n.appearance = ap.into();
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}");
assert_eq!(r["unmatched"], json!([a]));
}
#[test]
fn a_hidden_or_locked_glyph_stays_an_outline() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ABD", "size": 40}));
let k = children_of(&s, g);
s.edit("test", |d, _| {
d.node_mut(NodeId(k[0])).unwrap().visible = false;
d.node_mut(NodeId(k[2])).unwrap().locked = true;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["B"]), "{r}");
let d = &s.doc().unwrap().doc;
assert!(!d.node(NodeId(k[0])).unwrap().visible, "A stays a hidden outline");
assert!(d.node(NodeId(k[2])).unwrap().locked, "D stays a locked outline");
}
#[test]
fn an_isolated_or_knockout_group_keeps_its_type_inside() {
for case in ["isolate", "knockout", "knockout_shape"] {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
s.edit("test", |d, _| {
let n = d.node_mut(NodeId(g)).unwrap();
match case {
"isolate" => n.isolate = true,
"knockout" => n.knockout = vectorcraft_doc::Knockout::On,
_ => n.knockout_shape = true,
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let id = r["ids"][0].as_u64().unwrap();
assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type");
}
}
#[test]
fn type_turned_half_round_stays_one_object() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "Upside", "size": 30, "rotation": 180}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["Upside"]), "{r}");
}
#[test]
fn a_drawn_dot_or_bar_beside_type_stays_art() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
// A bar that is exactly a hyphen of the font, somewhere else: the worst case.
let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50}));
s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["AB"]), "{r}");
let un = r["unmatched"].as_array().unwrap();
assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}");
// Selected on its own, the hyphen is what was asked for.
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["-"]), "{r}");
}
/// How long Retype takes with a large CJK face to match against (run with `--ignored
/// --nocapture`; skips when no such face is installed). Not a pass/fail budget: it prints.
#[test]
#[ignore = "timing: needs an installed CJK font"]
fn timing_with_a_large_cjk_face() {
let db = vectorcraft_text::FontDb::global();
let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f))
else {
eprintln!("skipped: no large CJK font installed");
return;
};
let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap();
let mut s = session();
let g = outlined(&mut s, json!({"x": 20, "y": 80, "text": "漢字のテスト ABC", "size": 24, "font": family, "style": face.style}));
for run in ["cold", "warm"] {
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let t0 = std::time::Instant::now();
let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap();
let ms = t0.elapsed().as_secs_f64() * 1000.0;
eprintln!("{run}: Retype with {family} ({} encoded glyphs) loaded: {ms:.0} ms → {}", face.mapped_chars().len(), r["texts"]);
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn a_compound_with_a_locked_or_hidden_part_stays_whole() {
let mut s = session();
// "B" outlines as a compound path of three contours.
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
let b = children_of(&s, g)[1];
let part = children_of(&s, b)[1];
s.edit("test", |d, _| {
d.node_mut(NodeId(part)).unwrap().locked = true;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["A"]), "{r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(NodeId(part)).unwrap().locked, "B's locked part, and B, stay as they are");
}
#[test]
fn a_group_with_an_attributes_note_keeps_its_type_inside() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40}));
s.execute("attributes.set", &json!({"ids": [g], "note": "logo, keep"})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let id = r["ids"][0].as_u64().unwrap();
assert_eq!(children_of(&s, g), vec![id], "the group and its note stay, holding the type");
}
#[test]
fn nothing_retypable_reads_no_font() {
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40}));
let a = children_of(&s, g)[0];
s.edit("test", |d, _| {
let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default());
d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}");
}
#[test]
fn tracked_one_contour_letters_still_become_type() {
for text in ["LIT", "HELLO", "LIST"] {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap();
let n = text.len() as u64;
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}");
assert!(texts.len() > 1, "the tracking splits the line: {r}");
assert_eq!(r["unmatched"], json!([]), "{r}");
}
}
/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`;
/// skips when no large CJK font is installed). Not a pass/fail budget: it prints.
#[test]
#[ignore = "timing: needs an installed CJK font"]
fn timing_with_hundreds_of_cjk_outlines() {
let db = vectorcraft_text::FontDb::global();
let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f))
else {
eprintln!("skipped: no large CJK font installed");
return;
};
let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap();
// 300 common ideographs, ten lines of thirty.
let chars: Vec<char> = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect();
let mut s = session();
let mut groups = vec![];
for (i, line) in chars.chunks(30).enumerate() {
let text: String = line.iter().collect();
groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style})));
}
for run in ["cold", "warm"] {
s.execute("select.set", &json!({"ids": groups})).unwrap();
let t0 = std::time::Instant::now();
let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap();
let ms = t0.elapsed().as_secs_f64() * 1000.0;
let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum();
eprintln!(
"{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched",
chars.len(),
r["unmatched"].as_array().unwrap().len()
);
s.execute("edit.undo", &json!({})).unwrap();
}
}
#[test]
fn a_long_tracked_line_is_checked_in_time() {
// Tracking splits the line at every glyph: the layout check must not lay out the rest of the
// line again after each split.
let text = "abe".repeat(150);
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let t0 = std::time::Instant::now();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
assert_eq!(texts.concat(), text);
assert_eq!(r["unmatched"], json!([]));
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
}
+43 -20
View File
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Graphic Style",
["Window", "Appearance"],
None,
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
has_doc,
style_redefine
),
@@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value {
fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "graphicStyle.redefine";
let (src, n) = source(s, p, cmd)?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
let n = super::appearance::look_holder(d, n);
let src = if n.id == src { src } else { n.id };
let i = match str_param(p, "name") {
Some(name) => style_index(d, name)?,
None => n
.extras()
.graphic_style
.and_then(|id| d.graphic_style_by_id(id))
.and_then(|g| d.graphic_style_index(&g.name))
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
// The style to replace, its new look, and the object that look comes from (none for another style's look).
let (i, look, src) = match p.get("from") {
Some(from) => {
let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?;
if p.get("id").is_some() {
return Err(bad(cmd, "pass `id` or `from`, not both"));
}
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?;
let d = &s.doc()?.doc;
let (i, j) = (style_index(d, name)?, style_index(d, from)?);
// A style dropped on itself, or on a style with the same look, stays as it is.
let target = &d.graphic_styles[i];
let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() };
if i == j || look == *target {
return Ok(json!({ "name": name }));
}
(i, look, None)
}
None => {
let (src, n) = source(s, p, cmd)?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
let n = super::appearance::look_holder(d, n);
let src = if n.id == src { src } else { n.id };
let i = match str_param(p, "name") {
Some(name) => style_index(d, name)?,
None => n
.extras()
.graphic_style
.and_then(|id| d.graphic_style_by_id(id))
.and_then(|g| d.graphic_style_index(&g.name))
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
};
(i, GraphicStyle::of(String::new(), captured(n), n), Some(src))
}
};
let look = GraphicStyle::of(String::new(), captured(n), n);
let name = d.graphic_styles[i].name.clone();
let name = s.doc()?.doc.graphic_styles[i].name.clone();
let chars = s.prefs.override_char_color;
let before = s.doc()?.doc.clone();
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
@@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
// source or as a linked object: the graph draws it again from the design.
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
set_link(d, &edited, None);
@@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
let mut follow_marks = super::graph::series_group_marks(d, &follow);
let edited: HashSet<NodeId> = edited.into_iter().collect();
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
let g = d.graphic_styles[i].clone();
let mut shared = None;
@@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
}
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
super::graph::capture_label_rows(d, &follow_marks);
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
if let Some(src) = src {
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
}
Ok(())
})?;
Ok(json!({ "name": name }))
+39 -16
View File
@@ -1279,40 +1279,63 @@ impl GroupEdit {
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
/// are added as new swatches and swatches past the end are removed. With `colors_only`, a swatch
/// that is not a color (a gradient, pattern or None swatch) keeps its place and paint and takes no
/// entry of `colors`, which go to the group's color swatches in order. Paints linked to its global
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
/// (None, Registration) it would change or remove is refused.
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
pub(super) fn rewrite_group(
d: &mut Document,
group: &str,
colors: &[Option<Color>],
colors_only: bool,
rename: Option<&str>,
cmd: &str,
) -> Result<GroupEdit> {
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
Some(n) => d.free_swatch_name(n),
None => group.to_string(),
};
let old = &d.swatch_groups[gi].swatches;
// The place in `colors` of each swatch's new color; none for a swatch kept as it is.
let mut taken = 0;
let places: Vec<Option<usize>> = old
.iter()
.map(|w| {
(!colors_only || w.paint.color().is_some()).then(|| {
taken += 1;
taken - 1
})
})
.collect();
let new_color = |place: Option<usize>| place.and_then(|i| colors.get(i).copied().flatten());
if let Some(w) = old
.iter()
.enumerate()
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
.map(|x| x.1)
.zip(&places)
.find(|(w, place)| place.is_some() && w.is_reserved() && new_color(**place).is_none_or(|c| w.paint.color() != Some(c)))
.map(|x| x.0)
{
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
}
let colorized_ok = super::paint::check_colorized(d).is_ok();
let mut relinks = vec![];
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
let old_len = old.len();
// The swatches that stay, each with its new color.
let mut kept: Vec<(Swatch, Color)> = vec![];
for (i, w) in old.into_iter().enumerate() {
match colors.get(i).copied().flatten() {
Some(c) => kept.push((w, c)),
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
None => {}
// The swatches that stay, each with its new color (none for one kept as it is).
let mut kept: Vec<(Swatch, Option<Color>)> = vec![];
for (w, place) in old.into_iter().zip(places) {
match (place, new_color(place)) {
(None, _) => kept.push((w, None)),
(_, Some(c)) => kept.push((w, Some(c))),
(_, None) if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
(_, None) => {}
}
}
let mut swatches = Vec::with_capacity(kept.len());
for (mut w, c) in kept {
if w.paint.color() != Some(c) {
if let Some(c) = c
&& w.paint.color() != Some(c)
{
// A tint swatch becomes a colour of its own.
w.paint = Paint::solid(c);
if w.global {
@@ -1325,7 +1348,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
let mut free = d.free_swatch_names();
free.insert(&name);
swatches.iter().for_each(|w| free.insert(&w.name));
for c in colors.iter().skip(old_len).flatten() {
for c in colors.iter().skip(taken).flatten() {
let nm = free.take(&color_name(*c));
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
}
@@ -1379,7 +1402,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
{
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
}
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, false, rename, C))?;
e.defaults(s)?;
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
}
+25
View File
@@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() {
}
}
/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the
/// thread as it was: every frame stays a frame of the thread with the text it holds, and the
/// symbol's art holds a copy of the text the frame shows.
#[test]
fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() {
for command in ["symbol.new", "symbol.update"] {
let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0);
let shown = frames.map(|id| text(&s, id));
let name = if command == "symbol.update" {
let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap());
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
"Mark"
} else {
"Story"
};
s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap();
let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap();
assert!(r["id"].is_null(), "{command}: {r}");
assert_eq!(threads(&s), [frames], "{command}: the thread is as it was");
assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text");
assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows");
}
}
/// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the
/// mask art too.
#[test]
+283
View File
@@ -0,0 +1,283 @@
//! `app.toast`: a short message shown over the window that does not stop work and goes away by
//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and plug-ins raise
//! one with the command, and the app's code can raise one with [`Session::toast`]. The engine
//! queues the messages and the desktop app takes them each frame ([`Session::take_toasts`]) and
//! shows them. A failed script run puts the documents back but keeps the messages it raised.
use std::collections::VecDeque;
use serde_json::{Value, json};
use super::{CommandSpec, Result, always, bad, cmd};
use crate::Session;
const ID: &str = "app.toast";
/// The most characters a message has.
pub const MAX_CHARS: usize = 500;
/// How long a message shows when `seconds` is omitted, and the shortest and longest time it may
/// show.
pub const DEFAULT_SECONDS: f64 = 4.0;
pub const MIN_SECONDS: f64 = 0.5;
pub const MAX_SECONDS: f64 = 60.0;
/// The most messages waiting for the app to take them: past it the oldest one goes. A session
/// without a window (the headless MCP server, `vectorcraft-cli run`) never takes them.
pub const MAX_QUEUED: usize = 32;
/// What kind of news a message is, which sets its color.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Level {
#[default]
Info,
Success,
Warning,
Error,
}
impl Level {
pub const ALL: [Level; 4] = [Level::Info, Level::Success, Level::Warning, Level::Error];
/// Its `level` value.
pub fn param(self) -> &'static str {
match self {
Level::Info => "info",
Level::Success => "success",
Level::Warning => "warning",
Level::Error => "error",
}
}
/// The level whose `level` value is `param`.
pub fn from_param(param: &str) -> Option<Level> {
Level::ALL.into_iter().find(|l| l.param() == param)
}
}
/// A message to show.
#[derive(Clone, Debug, PartialEq)]
pub struct Toast {
pub message: String,
pub level: Level,
/// How long it shows, in seconds.
pub seconds: f64,
}
impl Toast {
/// A message of `level` shown for [`DEFAULT_SECONDS`].
pub fn new(message: impl Into<String>, level: Level) -> Toast {
Toast { message: message.into(), level, seconds: DEFAULT_SECONDS }
}
}
/// The messages waiting for the app to show them.
#[derive(Clone, Debug, Default)]
pub struct Queue(VecDeque<Toast>);
impl Session {
/// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. Its
/// time is held to [`MIN_SECONDS`] to [`MAX_SECONDS`], and a time that is not a number is
/// [`DEFAULT_SECONDS`].
pub fn toast(&mut self, mut toast: Toast) {
toast.seconds = if toast.seconds.is_nan() { DEFAULT_SECONDS } else { toast.seconds.clamp(MIN_SECONDS, MAX_SECONDS) };
while self.toasts.0.len() >= MAX_QUEUED {
self.toasts.0.pop_front();
}
self.toasts.0.push_back(toast);
}
/// Take the messages queued since the last call, oldest first.
pub fn take_toasts(&mut self) -> Vec<Toast> {
self.toasts.0.drain(..).collect()
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"app.toast",
"Show Message",
[],
None,
"{message: string (1 to 500 characters, not only whitespace), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}",
always,
run
)]
}
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let toast = parse(p)?;
let r = json!({"message": &toast.message, "level": toast.level.param(), "seconds": toast.seconds});
s.toast(toast);
Ok(r)
}
/// The message `p` asks for; an invalid value of any key is an error.
fn parse(p: &Value) -> Result<Toast> {
let message = match p.get("message") {
Some(Value::String(m)) => m,
Some(_) => return Err(bad(ID, "`message` must be a string")),
None => return Err(bad(ID, "`message` is required")),
};
if message.trim().is_empty() {
return Err(bad(ID, "`message` must have a character other than whitespace"));
}
let chars = message.chars().count();
if chars > MAX_CHARS {
return Err(bad(ID, format!("`message` has {chars} characters; at most {MAX_CHARS} are allowed")));
}
let level = match p.get("level") {
None => Level::default(),
Some(v) => v.as_str().and_then(Level::from_param).ok_or_else(|| {
let all: Vec<&str> = Level::ALL.iter().map(|l| l.param()).collect();
bad(ID, format!("`level` must be one of {}", all.join(", ")))
})?,
};
let seconds = match p.get("seconds") {
None => DEFAULT_SECONDS,
Some(v) => v
.as_f64()
.filter(|s| (MIN_SECONDS..=MAX_SECONDS).contains(s))
.ok_or_else(|| bad(ID, format!("`seconds` must be a number from {MIN_SECONDS} to {MAX_SECONDS}")))?,
};
Ok(Toast { message: message.clone(), level, seconds })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_message_is_queued_with_its_defaults() {
let mut s = Session::new();
let r = s.execute(ID, &json!({"message": "Saved 3 files"})).unwrap();
assert_eq!(r, json!({"message": "Saved 3 files", "level": "info", "seconds": 4.0}));
assert_eq!(s.take_toasts(), vec![Toast::new("Saved 3 files", Level::Info)]);
// Taken once.
assert_eq!(s.take_toasts(), vec![]);
}
#[test]
fn level_and_seconds_are_kept() {
let mut s = Session::new();
for level in Level::ALL {
s.execute(ID, &json!({"message": "m", "level": level.param(), "seconds": 0.5})).unwrap();
}
s.execute(ID, &json!({"message": "long", "seconds": 60})).unwrap();
let got: Vec<(Level, f64)> = s.take_toasts().iter().map(|t| (t.level, t.seconds)).collect();
assert_eq!(got, vec![(Level::Info, 0.5), (Level::Success, 0.5), (Level::Warning, 0.5), (Level::Error, 0.5), (Level::Info, 60.0)]);
}
#[test]
fn invalid_values_are_errors_and_queue_nothing() {
let mut s = Session::new();
let long = "x".repeat(MAX_CHARS + 1);
for p in [
json!({}),
json!({"message": 3}),
json!({"message": ""}),
json!({"message": " \n\t"}),
json!({"message": long}),
json!({"message": "m", "level": "loud"}),
json!({"message": "m", "level": 1}),
json!({"message": "m", "seconds": 0.4}),
json!({"message": "m", "seconds": 61}),
json!({"message": "m", "seconds": "4"}),
json!({"message": "m", "seconds": null}),
] {
let e = s.execute(ID, &p).unwrap_err().to_string();
assert!(e.contains(ID), "{p}: {e}");
}
assert_eq!(s.take_toasts(), vec![]);
// The longest message is allowed, counted in characters, not bytes.
let most = "é".repeat(MAX_CHARS);
s.execute(ID, &json!({"message": most})).unwrap();
assert_eq!(s.take_toasts().len(), 1);
}
#[test]
fn a_message_queued_by_the_app_shows_for_0_5_to_60_seconds() {
let mut s = Session::new();
for seconds in [f64::INFINITY, 1e9, f64::NEG_INFINITY, 0.0, f64::NAN, 10.0] {
s.toast(Toast { seconds, ..Toast::new("m", Level::Info) });
}
let got: Vec<f64> = s.take_toasts().iter().map(|t| t.seconds).collect();
assert_eq!(got, vec![MAX_SECONDS, MAX_SECONDS, MIN_SECONDS, MIN_SECONDS, DEFAULT_SECONDS, 10.0]);
}
#[test]
fn the_oldest_waiting_message_goes_past_the_limit() {
let mut s = Session::new();
for i in 0..MAX_QUEUED + 2 {
s.toast(Toast::new(format!("{i}"), Level::Info));
}
let left: Vec<String> = s.take_toasts().into_iter().map(|t| t.message).collect();
assert_eq!(left.len(), MAX_QUEUED);
assert_eq!(left.first().map(String::as_str), Some("2"));
assert_eq!(left.last().map(String::as_str), Some("33"));
}
#[test]
fn a_message_is_journaled_without_an_undo_step_or_a_document() {
let mut s = Session::new();
// No document open.
s.execute(ID, &json!({"message": "no document"})).unwrap();
assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "no document"})));
s.execute("file.new", &json!({})).unwrap();
let undo = s.active().unwrap().history.undo.len();
let revision = s.active().unwrap().revision;
s.execute(ID, &json!({"message": "m", "level": "success"})).unwrap();
assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "m", "level": "success"})));
assert_eq!(s.active().unwrap().history.undo.len(), undo);
assert_eq!(s.active().unwrap().revision, revision);
}
#[test]
fn a_script_raises_a_message_with_vc_run() {
let mut s = Session::new();
let r = s
.execute(
"script.run",
&json!({"source": "vc.run('app.toast', {message: 'Done: ' + (1 + 1), level: 'success'});", "name": "t.js", "answers": []}),
)
.unwrap();
assert!(r.get("error").is_none_or(Value::is_null), "{r}");
assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]);
}
#[test]
fn a_failed_script_run_puts_the_documents_back_and_keeps_its_messages() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let art = format!("{:?}", s.active().unwrap().doc.layers);
let e = s
.execute(
"script.run",
&json!({
"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.run('app.toast', {message: 'Failed: no artboard'}); throw new Error('stop');",
"name": "t.js",
"answers": [],
}),
)
.unwrap_err()
.to_string();
assert!(e.contains("stop"), "{e}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art, "the rectangle is put back");
assert_eq!(s.take_toasts(), vec![Toast::new("Failed: no artboard", Level::Info)]);
}
#[test]
fn a_command_batch_raises_its_messages_in_order() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute(
"command.batch",
&json!({"commands": [
{"command": "app.toast", "params": {"message": "one"}},
{"command": "app.toast", "params": {"message": "two", "level": "warning"}},
]}),
)
.unwrap();
assert_eq!(s.take_toasts(), vec![Toast::new("one", Level::Info), Toast::new("two", Level::Warning)]);
}
}
+200 -64
View File
@@ -10,8 +10,8 @@ use super::object::choice;
use super::threads::ThreadIndex;
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
use super::{
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
number_or, switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, index_opt,
named_ids, number_or, object_param, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Find and Replace…",
["Edit"],
None,
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, ids?} replace in every text object (or ids) → {count}. Matches never span style runs.",
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, hiddenLayers?: false, lockedLayers?: false, ids?} replace every match in the type the search reaches (or in ids, whatever their layers), as one undo step → {count (every match), replaced (the matches that did not already read as `replace`)}. The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards; hiddenLayers adds the type of hidden layers and sublayers and lockedLayers that of locked ones, while a hidden or locked object or group keeps its type out. Matches never span style runs. When nothing matches, or every match already reads as `replace`, nothing changes and no undo step is recorded.",
has_doc,
find_replace
),
@@ -129,10 +129,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Next",
["Edit"],
None,
"{find, matchCase?, wholeWord?} select the next text object (after the selected one, wrapping) containing `find` → {id|null}",
"{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected, or with a null `from`, it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.",
has_doc,
find_next
),
cmd!(
"edit.replaceMatch",
"Replace",
[],
None,
"{find, replace?: \"\", matchCase?: false, wholeWord?: false, id, start, end} replace one match of `find`, the bytes start..end of type object id as edit.findNext returns them, with `replace`, as one undo step → {id, start, end (the replacement's bytes; pass them to edit.findNext as `from` to go on), replaced}. Bytes that are no match of `find` are refused. When the match already reads as `replace`, nothing changes, no undo step is recorded and replaced is false.",
has_doc,
replace_one
),
cmd!(
"edit.pasteWithoutFormatting",
"Paste without Formatting",
@@ -1657,14 +1666,9 @@ fn is_word(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// Byte ranges of `needle` in `hay`.
pub(crate) fn find_all(hay: &str, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> {
find_all_between(hay, needle, match_case, whole_word, None, None)
}
/// [`find_all`] in run `i` of `runs`: a whole word looks past the run's ends at the characters
/// next to it, so a change of style inside a word is not a word boundary (#5901). Matches stay
/// inside the run.
/// Byte ranges of `needle` in run `i` of `runs`: a whole word looks past the run's ends at the
/// characters next to it, so a change of style inside a word is not a word boundary (#5901).
/// Matches stay inside the run.
fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> {
let Some(run) = runs.get(i) else { return vec![] };
let before = runs.get(..i).and_then(|r| r.iter().rev().find_map(|r| r.text.chars().next_back()));
@@ -1672,8 +1676,8 @@ fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole
find_all_between(&run.text, needle, match_case, whole_word, before, after)
}
/// [`find_all`], with `before` and `after` the characters on either side of `hay` (none at the
/// text's ends), which a whole word must not touch either.
/// Byte ranges of `needle` in `hay`, with `before` and `after` the characters on either side of
/// `hay` (none at the text's ends), which a whole word must not touch either.
fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, before: Option<char>, after: Option<char>) -> Vec<(usize, usize)> {
let nc: Vec<char> = needle.chars().collect();
if nc.is_empty() {
@@ -1705,102 +1709,234 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool,
/// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint
/// order: the text Find and Replace and Check Spelling go through.
pub(crate) fn all_texts(d: &Document) -> Vec<NodeId> {
fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec<NodeId>) {
if !n.visible || n.locked {
searched_texts(d, false, false)
}
/// [`all_texts`], with the type of hidden layers (`hidden_layers`) and of locked layers
/// (`locked_layers`) as well, as Check Hidden Layers and Check Locked Layers of Find and Replace
/// ask. The switches are about layers and sublayers: a hidden or locked object or group keeps its
/// type out, and so does a locked artboard.
fn searched_texts(d: &Document, hidden_layers: bool, locked_layers: bool) -> Vec<NodeId> {
fn visit(n: &Node, locks: &LockedArtboards<'_>, layers: (bool, bool), v: &mut Vec<NodeId>) {
let layer = matches!(n.kind, NodeKind::Layer { .. });
if (!n.visible && !(layer && layers.0)) || (n.locked && !(layer && layers.1)) {
return;
}
if matches!(n.kind, NodeKind::Text(_)) && !locks.holds_id(n.id) {
v.push(n.id);
}
for c in n.children().into_iter().flatten() {
visit(c, locks, v);
visit(c, locks, layers, v);
}
}
let mut v = vec![];
let locks = d.locked_artboards();
for l in &d.layers {
visit(l, &locks, &mut v);
visit(l, &locks, (hidden_layers, locked_layers), &mut v);
}
v
}
/// What Find and Replace looks for: the text, Match Case and Find Whole Word.
struct Query {
find: String,
match_case: bool,
whole_word: bool,
}
impl Query {
/// The `find`, `matchCase` and `wholeWord` params of command `c`. An empty or missing `find`
/// is an error.
fn of(p: &Value, c: &str) -> Result<Self> {
let find = text_param(p, "find", c)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(c, "missing `find`"))?.to_string();
Ok(Self { find, match_case: switch_or(p, "matchCase", false, c)?, whole_word: switch_or(p, "wholeWord", false, c)? })
}
/// The matches in `t`, in reading order, each as (run, start, end) with `start..end` the bytes
/// of the match in the object's plain text. A match stays inside one style run, and an inline
/// graphic is art, not characters to find.
fn matches(&self, t: &TextObject) -> Vec<(usize, usize, usize)> {
let mut hits = vec![];
let mut base = 0;
for (ri, r) in t.runs.iter().enumerate() {
if r.inline.is_none() {
hits.extend(
find_in_run(&t.runs, ri, &self.find, self.match_case, self.whole_word).into_iter().map(|(a, b)| (ri, base + a, base + b)),
);
}
base += r.text.len();
}
hits
}
}
/// Replace bytes `start..end` of the plain text of `t`, which lie inside run `run`, with `rep`.
/// The paragraph styles and the ruby follow the edit, as `text.editRange` moves them. The caller
/// refreshes the bounds.
fn replace_match(t: &mut TextObject, run: usize, start: usize, end: usize, rep: &str) {
let base: usize = t.runs.iter().take(run).map(|r| r.text.len()).sum();
let (Some(a), Some(b)) = (start.checked_sub(base), end.checked_sub(base)) else { return };
if !t.runs.get(run).is_some_and(|r| a <= b && r.text.is_char_boundary(a) && r.text.is_char_boundary(b)) {
return;
}
t.splice_paras(start, end, rep);
if let Some(r) = t.runs.get_mut(run) {
r.text.replace_range(a..b, rep);
}
t.ruby_after_replace(start, end, rep.len());
}
fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.findReplace";
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let q = Query::of(p, C)?;
let rep = text_param(p, "replace", C)?.unwrap_or("").to_string();
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?);
let ids = match p.get("ids").filter(|v| !v.is_null()) {
Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?),
None => all_texts(&s.doc()?.doc),
None => searched_texts(&s.doc()?.doc, hidden, locked),
};
let st = s.doc()?;
let total: usize = ids
// Every match, and the matches that do not already read as the replacement.
let (total, replaced) = ids
.iter()
.filter_map(|id| match &st.doc.node(*id)?.kind {
NodeKind::Text(t) => Some((0..t.runs.len()).map(|i| find_in_run(&t.runs, i, &find, mc, ww).len()).sum::<usize>()),
NodeKind::Text(t) => {
let plain = t.plain_text();
let hits = q.matches(t);
Some((hits.len(), hits.iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).count()))
}
_ => None,
})
.sum();
if total == 0 {
return Ok(json!({ "count": 0 }));
.fold((0, 0), |(n, r), (hn, hr)| (n + hn, r + hr));
if replaced == 0 {
return Ok(json!({ "count": total, "replaced": 0 }));
}
super::overprint::edit_counted(s, "Replace", |d| {
let mut changed = 0;
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
// Matches as (run, start, end) with offsets inside the run. Inline graphics are art, not
// characters to rewrite.
let mut hits = vec![];
let mut base = 0;
for (ri, r) in t.runs.iter().enumerate() {
if r.inline.is_none() {
for (a, b) in find_in_run(&t.runs, ri, &find, mc, ww) {
if r.text.get(a..b) != Some(rep.as_str()) {
hits.push((ri, base + a, base + b, a, b));
}
}
}
base += r.text.len();
}
let plain = t.plain_text();
let hits: Vec<_> = q.matches(t).into_iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).collect();
if hits.is_empty() {
continue;
}
// Last match first, so the offsets of earlier ones stay valid. The paragraph styles follow
// each edit, as `text.editRange` does.
for (ri, ta, tb, a, b) in hits.into_iter().rev() {
t.splice_paras(ta, tb, &rep);
if let Some(r) = t.runs.get_mut(ri) {
r.text.replace_range(a..b, &rep);
}
// Last match first, so the offsets of earlier ones stay valid.
for (ri, a, b) in hits.into_iter().rev() {
replace_match(t, ri, a, b, &rep);
}
changed += 1;
refresh_bounds(t);
}
Ok(changed)
})?;
Ok(json!({ "count": total }))
Ok(json!({ "count": total, "replaced": replaced }))
}
/// A match of Find and Replace: bytes `start..end` of the plain text of type object `id`.
#[derive(Clone, Copy)]
struct Match {
id: NodeId,
start: usize,
end: usize,
}
impl Match {
/// The `id`, `start` and `end` that `p` gives for a match, under command `c`: an object id and
/// two byte offsets, put in order as `text.editRange` orders its own.
fn of(p: &Value, c: &str) -> Result<Self> {
let whole = |key: &str| index_opt(p, key, c)?.ok_or_else(|| bad(c, format!("missing `{key}`")));
let id = object_param(p, "id", c)?.ok_or_else(|| bad(c, "missing `id`"))?;
let (start, end) = (whole("start")?, whole("end")?);
Ok(Self { id, start: start.min(end), end: start.max(end) })
}
}
fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.findNext";
let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string();
let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?);
let q = Query::of(p, C)?;
let backwards = switch_or(p, "backwards", false, C)?;
let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?);
// A `from` that is no object gives no `id`, and is refused as one without it. A null `from`
// starts at the first match, whatever is selected.
let from = match p.get("from") {
None => None,
Some(Value::Null) => Some(None),
Some(v) => Some(Some(Match::of(v, C)?)),
};
let st = s.doc()?;
let all = all_texts(&st.doc);
let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id));
let n = all.len();
let start = cur.map(|c| c + 1).unwrap_or(0);
let hit = (0..n).map(|k| all[(start + k) % n.max(1)]).find(|id| match st.doc.node(*id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => !find_all(&t.plain_text(), &find, mc, ww).is_empty(),
_ => false,
});
match hit {
Some(id) => {
s.select(|_, sel| sel.set([id]))?;
Ok(json!({ "id": id.0 }))
}
None => Ok(json!({ "id": null })),
// The objects in the order the search visits them: from the top of the stacking order down,
// or with Search Backwards from the bottom up.
let mut order = searched_texts(&st.doc, hidden, locked);
if !backwards {
order.reverse();
}
// Every match in that order as (object's place, match): inside an object in reading order, or
// with Search Backwards from its end.
let mut all: Vec<(usize, Match)> = vec![];
for (place, id) in order.iter().enumerate() {
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { continue };
let mut hits = q.matches(t);
if backwards {
hits.reverse();
}
all.extend(hits.into_iter().map(|(_, start, end)| (place, Match { id: *id, start, end })));
}
if all.is_empty() {
return Ok(json!({ "id": null, "count": 0 }));
}
// The search goes on from `from`, or from the whole of the first selected type object it
// visits, so that the same call again reaches the next object. From anywhere else it starts
// at the first match.
let from = from.unwrap_or_else(|| {
st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind {
NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }),
_ => None,
})
});
let after = |(place, m): &(usize, Match), at: usize, f: &Match| {
*place > at || (*place == at && if backwards { m.end <= f.start } else { m.start >= f.end })
};
let k = from
.and_then(|f| order.iter().position(|id| *id == f.id).map(|at| (at, f)))
.and_then(|(at, f)| all.iter().position(|hit| after(hit, at, &f)))
.unwrap_or(0);
let Some((_, m)) = all.get(k).copied() else { return Ok(json!({ "id": null, "count": 0 })) };
let count = all.len();
// Type that a selection tool can't reach (on a hidden or locked layer) is found without being
// selected.
let selected = all_texts(&st.doc).contains(&m.id);
if selected && st.selection.objects != [m.id] {
s.select(|_, sel| sel.set([m.id]))?;
}
let index = if backwards { count - k } else { k + 1 };
Ok(json!({ "id": m.id.0, "start": m.start, "end": m.end, "index": index, "count": count, "selected": selected }))
}
fn replace_one(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.replaceMatch";
let q = Query::of(p, C)?;
let rep = text_param(p, "replace", C)?.unwrap_or("").to_string();
let m = Match::of(p, C)?;
let st = s.doc()?;
let t = match st.doc.node(m.id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t,
Some(_) => return Err(bad(C, format!("node {} is not text", m.id.0))),
None => return Err(EngineError::NoNode(m.id)),
};
let Some((run, ..)) = q.matches(t).into_iter().find(|(_, a, b)| (*a, *b) == (m.start, m.end)) else {
return Err(bad(C, format!("no match of `find` at bytes {}..{} of object {}", m.start, m.end, m.id.0)));
};
let end = m.start + rep.len();
if t.plain_text().get(m.start..m.end) == Some(rep.as_str()) {
return Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": false }));
}
s.edit("Replace", |d, _| {
let Some(NodeKind::Text(t)) = d.node_mut(m.id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(m.id)) };
replace_match(t, run, m.start, m.end, &rep);
refresh_bounds(t);
Ok(())
})?;
Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": true }))
}
// ---------- Paste without Formatting ----------
@@ -250,7 +250,6 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")),
_ => bad(cmd, format!("the variable library is not well-formed XML: {e}")),
})?;
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else {
return Err(bad(cmd, "the file holds no `variableSets` element"));
};
+126 -17
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web",
[],
None,
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
has_doc,
export
),
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web Preview",
[],
None,
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
has_doc,
preview
),
@@ -331,8 +331,14 @@ pub struct ColorTable {
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
/// table when the first color was deleted. Empty: the reduction makes the palette.
pub custom_palette: Vec<String>,
/// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A
/// shifted color is locked, and a source the table does not hold shifts nothing.
pub shifted: std::collections::BTreeMap<String, String>,
}
/// A color shifted by hand: (source, color written).
type Shift = ([u8; 3], [u8; 3]);
/// The most colours a colour table list holds.
const MAX_TABLE: usize = 256;
@@ -352,6 +358,21 @@ impl ColorTable {
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
}
/// The colors shifted by hand as (source, color written). An error names a value that is not a
/// color such as `#ff8800`, two keys that name one color, or more than 256 entries.
fn shifts(&self) -> std::result::Result<Vec<Shift>, String> {
// One entry past the limit is enough for `colors` to refuse a longer map.
let (keys, values): (Vec<String>, Vec<String>) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip();
let sources = Self::colors(&keys, "shifted")?;
let to = Self::colors(&values, "shifted")?;
for (i, (s, k)) in sources.iter().zip(&keys).enumerate() {
if sources[..i].contains(s) {
return Err(format!("colorTable.shifted: `{k}` names a color another key names"));
}
}
Ok(sources.into_iter().zip(to).collect())
}
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
fn rgb(h: &str) -> Option<[u8; 3]> {
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
@@ -487,13 +508,18 @@ impl WebSettings {
{
ColorTable::colors(list, what)?;
}
// A deleted color is no longer locked, transparent or web-shifted.
// A deleted color is no longer locked, transparent, web-shifted or shifted.
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
if !deleted.is_empty() {
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
}
}
// Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and
// a color shifted by hand is not web-shifted.
let shifts: Vec<Shift> = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect();
table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c)));
table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect();
Ok(self)
}
@@ -640,6 +666,8 @@ pub struct TableColor {
pub transparent: bool,
pub locked: bool,
pub web_shifted: bool,
/// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`.
pub shifted: bool,
}
/// An optimised image file.
@@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
let locked = ColorTable::colors(&table.locked, "locked")?;
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
let shift = ColorTable::colors(&table.web_shift, "webShift")?;
let by_hand = table.shifts()?;
let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to);
// A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes
// one of the slots kept for them before the locked colors do.
let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect();
let o = PaletteOptions {
colors: s.colors,
reduction: s.reduction,
@@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
transparency: s.transparency,
matte,
};
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
// Map to transparent works on the colours the reduction made.
let before = ix.palette.clone();
let clear = ix.transparent.map(usize::from);
@@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
*slot = *c;
}
}
// Web snap, then the colours shifted by hand (locked colours stay as they are).
// Web shift and web snap (locked colors and colors shifted by hand stay as they are).
let clear = ix.transparent.map(usize::from);
for (i, c) in ix.palette.iter_mut().enumerate() {
let src = sources.get(i).copied().unwrap_or(*c);
if Some(i) == clear || locked.contains(&src) {
if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) {
continue;
}
if shift.contains(&src) {
@@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
*c = snapped;
}
}
// Lossy compares the pixels with the colors written for them, and moves no pixel into or out of
// a color shifted by hand.
if s.format == WebFormat::Gif {
web::lossy(&mut ix, rgba, s.lossy);
let fixed: Vec<u8> = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect();
web::lossy(&mut ix, rgba, s.lossy, &fixed);
}
// The colors shifted by hand.
for (i, c) in ix.palette.iter_mut().enumerate() {
if Some(i) != clear
&& let Some(to) = sources.get(i).and_then(shifted_to)
{
*c = to;
}
}
let order = web::sort(&mut ix, table.sort);
let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect();
@@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
.iter()
.zip(&sources)
.enumerate()
.map(|(i, (c, src))| TableColor {
color: *c,
source: *src,
transparent: ix.transparent == u8::try_from(i).ok(),
locked: locked.contains(src),
web_shifted: shift.contains(src),
.map(|(i, (c, src))| {
let transparent = ix.transparent == u8::try_from(i).ok();
let shifted = !transparent && shifted_to(src).is_some();
TableColor {
color: *c,
source: *src,
transparent,
locked: locked.contains(src) || shifted,
web_shifted: shift.contains(src) && !shifted,
shifted,
}
})
.collect();
Ok(PaletteImage { ix, colors, mapped })
@@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
/// transparent.
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
/// `colors` together, and its first opaque colors that fit in the rest.
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
let table = &s.color_table;
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
@@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
left.push(c);
}
}
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
if left.is_empty() || (removed && !opaque_left(&left)) {
return Err(KEEP_ONE.into());
}
Ok(quantize::quantize_to(rgba, w, h, o, &left))
// The colors mapped to transparent all become the one transparent entry, so together they take
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
// them and no pixel is transparent, that slot goes to the next opaque color instead.
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
}
Ok(ix)
}
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
let total = 256 - usize::from(has_clear);
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
let mut clear_room = if clear { total - opaque } else { 0 };
left.iter()
.copied()
.filter(|c| {
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
let keep = *slots > 0;
*slots = slots.saturating_sub(1);
keep
})
.collect()
}
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
if dropped.is_empty() {
return;
}
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
let near = quantize::nearest_entries(rgba, o, &all);
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
return;
}
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
Some(i) => i,
None => {
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
return;
};
ix.palette.push(*c);
i
}
};
for (v, n) in ix.indices.iter_mut().zip(&near) {
if n.is_some_and(|n| n >= kept.len()) {
*v = entry;
}
}
}
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
@@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
.map(|c| {
json!({
"color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked,
"webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color,
"webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color,
})
})
.collect();
-55
View File
@@ -1,55 +0,0 @@
//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode.
//!
//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the
//! shared strict reader and remove this second event pass when that dependency is updated.
/// Check names before canonical/local-name rewriting can collapse distinct attributes.
/// The event reader and namespace scope use the same caller-supplied resource caps.
pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> {
use std::collections::BTreeSet;
let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict();
let mut events = opts.events(xml);
let mut bindings: Vec<(String, String)> = Vec::new();
let mut scopes = Vec::new();
while let Some(event) = events.next().map_err(|e| e.to_string())? {
match event {
craft_xml::Event::Start { attrs, .. } => {
scopes.push(bindings.len());
let mut raw = BTreeSet::new();
for (key, value) in &attrs {
if !raw.insert(key.as_str()) {
return Err(format!("duplicate attribute `{key}`"));
}
if let Some(prefix) = key.strip_prefix("xmlns:") {
if bindings.len() >= limits.max_attrs {
return Err("too many in-scope namespace declarations".into());
}
bindings.push((prefix.to_string(), value.clone()));
}
}
let mut expanded = BTreeSet::new();
for (key, _) in &attrs {
if key == "xmlns" || key.starts_with("xmlns:") {
continue;
}
// Default namespaces do not apply to attributes. Preserve undeclared
// prefixes for standalone SVG library fragments, as the importer did.
let name = match key.split_once(':') {
Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local),
Some((prefix, local)) => {
bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local))
}
None => ("", key.as_str()),
};
if !expanded.insert(name) {
return Err(format!("duplicate expanded attribute `{key}`"));
}
}
}
craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)),
_ => {}
}
}
Ok(())
}
+6 -2
View File
@@ -29,6 +29,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
pub use cmd::clipboard::{Clipboard, SourceLayer};
pub use cmd::create::constrain_click;
pub use cmd::distortcmds::{perspective_click, width_point_pair};
pub use cmd::flare::flare_settings;
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
@@ -198,7 +199,8 @@ pub struct Session {
/// `plugin.install` takes `grant` and `allowHeavy` from any request
/// ([`Session::allow_plugin_grants_from_requests`]).
plugin_grants_from_requests: bool,
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first, at most
/// [`cmd::RECENT_URLS`]; not saved.
pub recent_urls: Vec<String>,
/// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]).
pub(crate) trace_preset_changes: cmd::TracePresetChanges,
@@ -360,6 +362,8 @@ pub struct Session {
/// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool
/// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]).
keyboard_text: bool,
/// The messages `app.toast` and [`Session::toast`] queued for the app to show; not saved.
pub(crate) toasts: cmd::toast::Queue,
}
impl Default for Session {
@@ -415,7 +419,7 @@ use history::history_budget_for;
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
pub(crate) use interaction::PreviewCopies;
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
pub use prefs::{DrawMode, Prefs};
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
pub use sanity::TOO_DEEP;
pub(crate) use sanity::{deselect_hidden, is_guide_path};
#[cfg(test)]
+50
View File
@@ -10,6 +10,26 @@ pub enum DrawMode {
Inside,
}
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run
/// may use ([`vectorcraft_plugins::Plugin::large_limits`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PluginBudget {
/// The plug-in's own limits.
#[default]
Normal,
/// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of
/// input; the time budget is unchanged.
Large,
}
/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the
/// other preferences are read as they are.
fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<PluginBudget, D::Error> {
let saved = <Value as serde::Deserialize>::deserialize(d)?;
Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal })
}
/// A saved Default Language as its tag: older preferences hold the language's name, and one the list
/// no longer has reads as the default.
fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
@@ -77,6 +97,13 @@ pub struct Prefs {
/// A single-key tool shortcut held down chooses its tool until the key is let go, and then the
/// tool active before comes back; a quick press chooses the tool for good.
pub hold_tool_keys: bool,
/// Hold shortcuts act (Edit › Keyboard Shortcuts › Hold Shortcuts, off by default): a key with a
/// hold shortcut runs it when held for [`Self::key_hold_delay`], and its own shortcut when let go
/// sooner. Off, every key runs on its press and the dialog shows no Hold column.
pub hold_shortcuts: bool,
/// Seconds a key with a hold shortcut must stay down before the hold shortcut runs (Hold
/// Shortcut Delay, 0.2 to 1.0). VectorCraft's own default, 0.35.
pub key_hold_delay: f64,
/// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the
/// selection, and the shape tools that show it draw it around the shape being drawn. Off (the
/// default), it hides during a move and while a shape is drawn, except that a Selection tool
@@ -179,6 +206,11 @@ pub struct Prefs {
pub fonts_folder: String,
// Plug-ins & Scratch Disks
pub plugins_folder: String,
/// Plug-in Instruction Budget: the instructions each object filter run gets, from
/// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers
/// keep their own budgets.
#[serde(deserialize_with = "plugin_budget")]
pub plugin_instruction_budget: PluginBudget,
pub scratch_primary: String,
pub scratch_secondary: String,
// User Interface
@@ -395,6 +427,21 @@ pub struct Prefs {
pub import_matches: Vec<cmd::importmatches::ImportMatch>,
}
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
pub const KEY_HOLD_DELAY: f64 = 0.35;
/// The range of the Hold Shortcut Delay, in seconds.
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
pub fn key_hold_delay(&self) -> f64 {
let (min, max) = KEY_HOLD_DELAY_RANGE;
if self.key_hold_delay.is_finite() { self.key_hold_delay.clamp(min, max) } else { KEY_HOLD_DELAY }
}
}
impl Default for Prefs {
fn default() -> Self {
let s = |v: &str| v.to_string();
@@ -426,6 +473,8 @@ impl Default for Prefs {
scrub_numeric_fields: true,
trackpad_rotate_view: true,
hold_tool_keys: true,
hold_shortcuts: false,
key_hold_delay: KEY_HOLD_DELAY,
bounding_box_while_moving_and_drawing: false,
paste_offset: 10.0,
selection_tolerance: 3.0,
@@ -496,6 +545,7 @@ impl Default for Prefs {
hyphenation_exceptions: String::new(),
fonts_folder: String::new(),
plugins_folder: String::new(),
plugin_instruction_budget: PluginBudget::Normal,
scratch_primary: s("Startup"),
scratch_secondary: s("None"),
ui_brightness: s("mediumDark"),
+33 -15
View File
@@ -1559,12 +1559,14 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
}
}
/// `message`, with what to do about a failure that comes from a script written for another program.
fn explained(kind: &RunErrorKind, message: &str) -> String {
/// `e`'s message, with what to do about a failure that comes from a script written for another
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"];
let message = &e.message;
let names_host_object =
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
if *kind == RunErrorKind::Thrown && names_host_object {
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
} else {
message.to_string()
@@ -1582,7 +1584,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message),
};
let file = (f.index > 0).then_some(f.file);
(RunError { kind, message, line: f.line, column: f.column }, file)
(RunError { kind, message, line: f.line, column: f.column, authored: false }, file)
}
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
@@ -1591,20 +1593,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
let map = |m: &include::SourceMap| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column }, index, file)
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
};
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
// file's place.
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
return (RunError { kind: e.kind.clone(), message, line, column }, Some(file));
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
}
if e.line == 0 {
return (e.clone(), None);
}
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
// is given without a place.
let unplaced = || (RunError { kind: e.kind.clone(), message: e.message.clone(), line: 0, column: 0 }, None);
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
match realm.error_source() {
0 => {
let (e, index, file) = map(&host.script_map.borrow());
@@ -1777,6 +1779,15 @@ impl Session {
self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text)
}
/// [`Self::script_failure_text`] split around the message when that message is text the script
/// supplied itself (`messageOrigin` `script`): the text before it, the message and the text after
/// it. `None` when the last run did not fail, or failed with one of the app's own errors.
pub fn script_authored_failure(&self) -> Option<(String, &str, String)> {
let r = self.script_report.as_ref().filter(|r| r["ok"] == false && r["messageOrigin"] == "script")?;
let (before, after) = failure_frame(r);
Some((before, r["message"].as_str().unwrap_or_default(), after))
}
/// Has the running script used up its growth allowance, so a person must answer? A run asked
/// to stop no longer waits: the next [`Session::script_pump`] ends it.
pub fn script_waiting(&self) -> bool {
@@ -1873,7 +1884,7 @@ impl Session {
};
drop(key);
let kind = LimitKind::Interrupted;
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
let _ = self.script_failed(job, &e);
true
}
@@ -2120,14 +2131,14 @@ impl Session {
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
if job.realm.waits() {
let kind = LimitKind::Interrupted;
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
job.host.calls_this_slice.set(0);
let outcome = run_slice(self, &mut job);
match outcome {
Err(panic) => {
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 };
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
Some(self.script_failed(job, &e))
}
Ok(Err(e)) => Some(self.script_failed(job, &e)),
@@ -2144,7 +2155,7 @@ impl Session {
} else {
format!("`answers` has {n} answers the script did not use")
};
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
}
Ok(Ok(Progress::Done(_))) => {
let r = self.script_commit(job);
@@ -2179,7 +2190,7 @@ impl Session {
let unwritten = job.host.flush_files();
if !unwritten.is_empty() {
let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", "));
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 };
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0, authored: false };
return self.script_failed(job, &e);
}
// The working copy goes into the session; `job.world` holds the state before the run.
@@ -2197,7 +2208,7 @@ impl Session {
if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) {
job.world.docs = start;
job.world.swap(self);
let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 };
let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0, authored: false };
return self.script_failed(job, &e);
}
}
@@ -2302,7 +2313,8 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue
let mut report = json!({
"ok": false,
"kind": kind_id(&e.kind),
"message": explained(&e.kind, &e.message),
"message": explained(e),
"messageOrigin": if e.authored { "script" } else { "built-in" },
"name": name,
"line": e.line,
"column": e.column,
@@ -2395,6 +2407,12 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
/// The text of a failed run's error.
fn failure_text(report: &Value) -> String {
let (before, after) = failure_frame(report);
format!("{before}{}{after}", report["message"].as_str().unwrap_or_default())
}
/// The text of a failed run's error before its message and after it.
fn failure_frame(report: &Value) -> (String, String) {
let s = |k: &str| report[k].as_str().unwrap_or_default();
let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0));
let at = match report["file"].as_str() {
@@ -2409,7 +2427,7 @@ fn failure_text(report: &Value) -> String {
} else {
String::new()
};
format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind"))
(format!("{}{at}: ", s("name")), format!(" ({}){kept}", s("kind")))
}
/// A run's slice: the working copy in, the real session lent to the host functions, one measured
+2 -2
View File
@@ -149,6 +149,7 @@ impl Session {
global_edit_options: Default::default(),
select_similar: crate::cmd::SIMILAR[0].0,
keyboard_text: false,
toasts: Default::default(),
script_key: None,
script_engines: crate::script::EnginesKey::new(),
script_stop: vectorcraft_js::Interrupt::new(),
@@ -204,8 +205,7 @@ impl Session {
let _ = self.finish_tool_edit_later();
// The switch goes on whatever the lent tool's last actions did, as for the deactivation.
let _ = self.give_back_tool(view);
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
let _ = self.apply_actions(acts);
let _ = self.deactivate_tool(view);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
// the rest of the batch; anything else in progress (a drag) is cancelled.
if self.batch_stash.is_none() {
Loaded 100 of 406 files, more files were not shown because too many files have changed in this diff. Show more