Merge main into feat/proof-setup-customize

This commit is contained in:
dotCooCoo committed 2026-11-18 13:13:29 -08:00
commit f1542e5af0
469 files changed
+55534 -2516

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",
+3
View File
@@ -154,7 +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.
+88 -10
View File
@@ -10,7 +10,7 @@
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -31,6 +31,8 @@ pub(crate) struct Reader {
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
/// [`DisplayProfile::attach_reader`] was called.
attached: bool,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
@@ -45,22 +47,22 @@ impl Drop for Done {
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
if !self.attached {
profile.attach_reader();
self.attached = true;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else {
return;
}
self.last = Some((now, display.clone()));
};
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
let changed = profile.report(read(display));
drop(done);
// A request made while this reading ran starts on the next frame.
if changed || profile.read_requested() {
ctx.request_repaint();
}
});
@@ -68,6 +70,32 @@ impl Reader {
log::warn!("couldn't start reading the display profile: {e}");
}
}
/// The display to read at `now` when a reading is to start, looked up with `display`. A
/// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once,
/// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the
/// preference off drops it. A request made with the preference on is kept when the preference
/// goes off and on again between two frames.
fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option<String>) -> Option<Option<String>> {
if !enabled {
profile.take_request();
return None;
}
if self.busy.load(Ordering::Acquire) {
return None;
}
let asked = profile.take_request();
if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return None;
}
self.looked = Some(now);
let display = display();
if !asked && !due(self.last.as_ref(), now, display.as_deref()) {
return None;
}
self.last = Some((now, display.clone()));
Some(display)
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
@@ -570,6 +598,56 @@ mod tests {
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
fn attached() -> DisplayProfile {
let profile = DisplayProfile::default();
profile.attach_reader();
profile
}
#[test]
fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into())));
// Inside the display lookup interval and the reading interval: nothing starts.
assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None);
assert_eq!(r.start(102.0, true, &profile, dp1), None);
profile.request_read(true).unwrap();
assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into())));
assert!(!profile.read_requested(), "the request is taken");
// The intervals run again from the requested reading.
assert_eq!(r.start(102.2, true, &profile, dp1), None);
assert_eq!(r.start(111.0, true, &profile, dp1), None);
assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into())));
}
#[test]
fn a_request_made_while_a_reading_runs_waits_for_it_to_end() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert!(r.start(0.0, true, &profile, dp1).is_some());
r.busy.store(true, Ordering::Release);
profile.request_read(true).unwrap();
assert_eq!(r.start(0.1, true, &profile, dp1), None);
assert_eq!(r.start(5.0, true, &profile, dp1), None);
assert!(profile.read_requested(), "kept while the reading runs");
r.busy.store(false, Ordering::Release);
assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into())));
assert!(!profile.read_requested());
}
#[test]
fn a_request_is_dropped_when_the_preference_goes_off() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert!(r.start(0.0, true, &profile, dp1).is_some());
profile.request_read(true).unwrap();
assert_eq!(r.start(0.1, false, &profile, dp1), None);
assert!(!profile.read_requested());
assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it");
assert!(profile.request_read(false).is_err());
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
+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())
}
+69
View File
@@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
walk(n, mode, key);
}
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
/// [`crate::track::seed_of`]).
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
for n in copies {
let turn = rng.range(-amount, amount) as f32;
turn_hues(n, turn);
}
}
/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it
/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as
/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue:
/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink).
fn turned(c: &Color, degrees: f32) -> Option<Color> {
if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
return None;
}
let turn = |v: [f32; 3]| {
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
(s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b]))
};
match *c {
Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
Color::Gray { .. } => None,
Color::Lab { l, a, b } => {
let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
let (a, b) = (f64::from(a), f64::from(b));
Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32))
}
}
}
fn turn_paint(p: &mut Paint, degrees: f32) {
if let Paint::Solid { color, .. } = p
&& let Some(c) = turned(color, degrees)
{
*p = Paint::solid(c);
}
}
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
/// mask's colors are its values, so they stay.
fn turn_hues(n: &mut Node, degrees: f32) {
for it in &mut n.appearance.items {
match it {
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
turn_paint(&mut r.style.fill, degrees);
turn_paint(&mut r.style.stroke, degrees);
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
turn_hues(Arc::make_mut(c), degrees);
}
}
}
/// Strip the brushes from every stroke under `n`, its masks' art included.
fn strip_brushes(n: &mut Node) {
for it in &mut n.appearance.items {
+2
View File
@@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] {
rotation: (-180.0, 180.0),
rotation_relative_to_path: false,
colorization: Colorization::Tints,
hue_jitter: 0.0,
modes: None,
}),
},
@@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] {
rotation: (-35.0, 35.0),
rotation_relative_to_path: true,
colorization: Colorization::None,
hue_jitter: 0.0,
modes: None,
}),
},
+20
View File
@@ -298,6 +298,12 @@ pub struct Scatter {
/// Rotation relative to the path direction (else to the page).
pub rotation_relative_to_path: bool,
pub colorization: Colorization,
/// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after
/// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's
/// path and the brush name fix the amounts, so a stroke draws the same colors every time.
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
#[serde(skip_serializing_if = "is_zero")]
pub hue_jitter: f64,
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
@@ -318,6 +324,7 @@ impl Default for Scatter {
rotation: (0.0, 0.0),
rotation_relative_to_path: false,
colorization: Colorization::None,
hue_jitter: 0.0,
modes: None,
}
}
@@ -326,6 +333,8 @@ impl Default for Scatter {
impl Scatter {
/// The ranges of size (%), spacing (%), scatter (%) and rotation (°).
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
/// The range of [`Scatter::hue_jitter`] (°).
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
/// Size, spacing, scatter and rotation, each as its (first, second) values.
pub fn values(&self) -> [(f64, f64); 4] {
@@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6
(within(a, range, fallback), within(b, range, fallback))
}
fn is_zero(v: &f64) -> bool {
*v == 0.0
}
fn valid_tile_frame(frame: Rect) -> bool {
[frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite)
&& frame.width().is_finite()
@@ -714,6 +727,7 @@ impl Brush {
s.spacing = within_pair(s.spacing, spacing, d.spacing.0);
s.scatter = within_pair(s.scatter, scatter, 0.0);
s.rotation = within_pair(s.rotation, rotation, 0.0);
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
s.colorization.sanitize();
}
BrushKind::Art(a) => {
@@ -1093,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
for n in &mut out {
colorize(n, colorization, &stroke.paint);
}
// One piece per copy, in the order the copies run along the path.
if let BrushKind::Scatter(s) = &brush.kind
&& s.hue_jitter > 0.0
{
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
}
leave_out_brushed(doc, &mut out, &mut Known::new());
out
}
+159
View File
@@ -1033,6 +1033,165 @@ fn stain_mixes_type_strokes_too() {
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
}
/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`.
fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush {
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(Paint::solid(fill));
Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) }
}
/// The fill color of each copy.
fn fill_colors(out: &[Node]) -> Vec<Color> {
out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect()
}
/// How far hue `h` is from `from`, in degrees, either way round.
fn hue_gap(h: f32, from: f32) -> f32 {
let d = (h - from).rem_euclid(360.0);
d.min(360.0 - d)
}
#[test]
fn hue_jitter_turns_each_copy_the_same_every_time() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0);
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(out.len(), 20);
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
let colors = fill_colors(&out);
let hues: Vec<f32> = colors.iter().map(|c| c.to_hsb()[0]).collect();
assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}");
assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}");
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}");
// Saturation and brightness stay; the copies stay where they were, at their size and angle.
assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}");
let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0));
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
assert_eq!(boxes(&out), boxes(&plain));
// Another path draws other amounts.
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
assert_ne!(other, colors);
}
#[test]
fn hue_jitter_of_zero_changes_nothing() {
let red = Color::rgb(1.0, 0.0, 0.0);
let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red));
// A brush without hue jitter is saved as before, and one saved before reads as 0.
let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap();
assert!(v.get("hue_jitter").is_none(), "{v}");
let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap();
assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0)));
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0");
let mut with = v.clone();
with["hue_jitter"] = serde_json::json!(45.0);
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, 45.0);
// Values outside 0..180 are clamped.
for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] {
let mut v = v.clone();
v["hue_jitter"] = serde_json::json!(given);
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, kept, "{given}");
}
}
#[test]
fn hue_jitter_turns_after_the_colorization() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// Tints: black art takes the blue stroke color, which then turns.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let hues: Vec<f32> =
fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect();
assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}");
assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}");
// A gray stroke color has no hue: its tints stay as they are.
let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0);
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray);
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray);
assert_eq!(fill_colors(&turned), fill_colors(&still));
// Nor does black ink alone, nor a gray, as a process stroke color.
for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] {
let key = StrokeLayer::new(Paint::solid(key), 1.0);
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key);
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key);
assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}");
}
// A turned process color stays a process color, turned over its C, M and Y with its K kept.
let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0)));
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}");
for c in &cmyk {
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
assert_eq!(k, 0.25);
// Full ink in one channel and none in another, as the color before it.
assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}");
}
// An RGB color keeps its saturation and brightness in its own values.
let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0)));
for c in &rgb {
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}");
}
// A Lab color keeps its lightness and chroma.
let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0)));
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
for c in &lab {
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}");
}
}
/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color
/// linked to a swatch (which loses the link); a pattern paint stays.
#[test]
fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let typed = |hue_jitter| Brush {
name: "s".into(),
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }),
};
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0)));
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
assert_eq!(turned.len(), still.len());
assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}");
assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}");
// Tints and Shades and Hue Shift: the colors they give turn.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] {
let art = Color::rgb(1.0, 0.0, 0.0);
let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue));
let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue));
assert_eq!(turned.len(), still.len());
assert_ne!(turned, still, "{colorization:?}");
for (t, s) in turned.iter().zip(&still) {
assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}");
}
}
// A color linked to a swatch turns and loses the link; a pattern paint stays.
let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 };
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(linked.clone());
art.appearance.set_stroke(pattern.clone());
let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) };
let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0));
let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0));
assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked));
assert_eq!(turned.len(), still.len());
for n in &turned {
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
}
}
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
/// swatch links.
#[test]
+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")]
+39
View File
@@ -339,6 +339,7 @@ impl Document {
/// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in
/// tree order where `id` appears.
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
crate::id_index::note_path_lookup();
// The cached path, while the node there still has the id ([`id_index`]).
let cached = self.index.get();
match cached.as_ref().and_then(|m| m.get(&id)) {
@@ -423,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);
+26
View File
@@ -82,6 +82,16 @@ impl Paths {
pub(crate) fn len(&self) -> usize {
self.ids.len()
}
/// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None`
/// when it isn't in the table.
pub(crate) fn entry(&self, id: &NodeId) -> Option<Option<u32>> {
self.ids.get(id).copied()
}
/// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its
/// siblings.
pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> {
self.at.get(e as usize).copied()
}
}
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
@@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() {
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
}
thread_local! {
/// [`path_lookups`] of this thread.
static PATH_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that
/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included.
pub fn path_lookups() -> u64 {
PATH_LOOKUPS.get()
}
/// Adds one to [`path_lookups`].
pub(crate) fn note_path_lookup() {
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
}
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
#[derive(Default)]
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
+5 -2
View File
@@ -17,11 +17,12 @@ pub mod corners;
pub mod decode;
pub mod depth;
pub mod dimension;
pub mod flare;
pub mod graph;
mod halftone_radii;
pub mod hit;
mod id_index;
pub use id_index::tree_walks;
pub use id_index::{path_lookups, tree_walks};
pub mod inks;
mod inline;
pub mod intertwine;
@@ -48,6 +49,8 @@ pub mod marks;
mod mem;
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
pub mod metadata;
mod nearest;
pub use nearest::NearestFinder;
pub mod node;
pub mod objects_on_path;
pub mod orient;
@@ -168,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>();
+90
View File
@@ -0,0 +1,90 @@
//! The nearest node of a kind at or above each of many objects, found along one index path per
//! object.
use std::sync::Arc;
use crate::id_index::Paths;
use crate::{Document, Node, NodeId};
/// Finds, for one object after another, the nearest node that passes a test: the object itself,
/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`].
///
/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that
/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache
/// places the object and each id on its path where they are, a lookup reads that one path; an id
/// the cache does not place there (one that appears more than once, or a cache older than the
/// tree) is looked up with [`Document::node`].
pub struct NearestFinder<'a> {
doc: &'a Document,
cache: Option<Arc<Paths>>,
/// The cache entries from the top-level layer down to the object.
entries: Vec<u32>,
/// The nodes at those entries.
nodes: Vec<&'a Node>,
}
impl Document {
/// A [`NearestFinder`] for this document.
pub fn nearest_finder(&self) -> NearestFinder<'_> {
NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] }
}
}
impl<'a> NearestFinder<'a> {
/// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred`
/// holds; `None` when `id` is not in the tree or no node on its path passes.
pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> {
let doc = self.doc;
let ids: Vec<NodeId> = if self.cached_path(id) {
let cache = self.cache.as_deref()?;
// The depth of the first id from the object up that the cache does not place there.
let mut unplaced = None;
for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() {
if cache.entry(&node.id) != Some(Some(e)) {
unplaced = Some(k);
break;
}
if pred(node) {
return Some(node);
}
}
let k = unplaced?;
self.nodes[..=k].iter().map(|n| n.id).collect()
} else {
doc.ancestry(id).unwrap_or_default()
};
let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n)));
// Those lookups may have built the cache again.
self.cache = doc.index.get();
found
}
/// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for
/// it or the path no longer leads to it.
fn cached_path(&mut self, id: NodeId) -> bool {
self.entries.clear();
self.nodes.clear();
let Some(cache) = self.cache.as_deref() else { return false };
let Some(Some(mut e)) = cache.entry(&id) else { return false };
loop {
let Some((parent, _)) = cache.place(e) else { return false };
self.entries.push(e);
if parent == u32::MAX {
break;
}
// A parent's entry is made before its children's, so the walk up ends.
if parent >= e {
return false;
}
e = parent;
}
self.entries.reverse();
let mut siblings: &'a [Arc<Node>] = &self.doc.layers;
for &e in &self.entries {
let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false };
self.nodes.push(&**n);
siblings = n.children().map_or(&[], |c| c.as_slice());
}
self.nodes.last().is_some_and(|n| n.id == id)
}
}
+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() {
+161
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> {
@@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() {
assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was");
}
}
/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node`
/// for each id finds it.
fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> {
d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node)
}
/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone
/// each, so both start from the same cache.
fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) {
type Pred = fn(&Node) -> bool;
let preds: [(&str, Pred); 5] = [
("group", |n| matches!(n.kind, NodeKind::Group { .. })),
("layer", |n| n.is_layer()),
("any", |_| true),
("none", |_| false),
("id divisible by 3", |n| n.id.0 % 3 == 0),
];
for (name, pred) in preds {
let (a, b) = (d.clone(), d.clone());
let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect();
let mut find = b.nearest_finder();
let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect();
assert_eq!(got, want, "{what}: {name}");
}
}
#[test]
fn nearest_finder_matches_the_ancestry_walk() {
for seed in 1..30 {
let (mut d, ids) = tree(seed);
nearest_agrees(&d, &ids, "no cache");
d.node(ids[0]);
nearest_agrees(&d, &ids, "cached");
// Every path in the first layer shifts: the cache is stale there.
let extra = d.alloc_id();
let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
ch.insert(0, leaf);
}
nearest_agrees(&d, &ids, "a stale cache");
// A group with the id of a node in the last layer, earlier in tree order than it, put in
// after the cache was built.
d.drop_lookup_cache();
d.node(ids[0]);
let last = d.layers.len() - 1;
let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id);
if let Some(dup) = dup
&& let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut()
{
ch.insert(0, Arc::new(Node::group(dup, vec![])));
}
nearest_agrees(&d, &ids, "a duplicate put in after the cache was built");
d.drop_lookup_cache();
nearest_agrees(&d, &ids, "a duplicate, cached afresh");
}
}
/// An id on the path that an earlier node of another kind also has: the earlier node is the one
/// tested, as `node` gives it.
#[test]
fn nearest_finder_tests_the_first_node_with_a_repeated_id() {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()));
d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap();
d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
// A group that has the path's id, after the path in tree order.
d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap();
let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. });
for cached in [false, true] {
d.drop_lookup_cache();
if cached {
d.node(layer);
}
let mut find = d.nearest_finder();
assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}");
assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path");
assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree");
}
}
/// With the cache built, finding the nearest group of every object of a large tree looks no id up
/// and walks the tree no time.
#[test]
fn nearest_finder_reads_one_path_per_object() {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
let mut leaves = vec![];
for g in 0..2_000 {
let kids: Vec<Arc<Node>> = (0..3)
.map(|_| {
let id = d.alloc_id();
leaves.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
})
.collect();
let gid = d.alloc_id();
d.insert(Some(layer), g, Node::group(gid, kids)).unwrap();
}
d.drop_lookup_cache();
d.node(layer);
let (lookups, walks) = (path_lookups(), tree_walks());
let mut find = d.nearest_finder();
let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count();
assert_eq!(found, leaves.len());
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
}
+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.
+1 -1
View File
@@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
+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
+5 -3
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,
@@ -103,8 +105,8 @@ pub use solids::{
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
graphics_reshaped_after, rename_appearance_graphic_symbol,
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+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);
+5 -5
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
use crate::solids::{
@@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
// With no member to carry them, the graphics' art must still fit its limits.
None => {
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
}
}
}
@@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op
let graphics = crate::solids::mapped_graphics(p);
let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) };
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
let faces = vectorcraft_three_d::revolve(path, b, options)?;
let mut used = *copies;
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) {
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) {
Some(_) => {
*copies = used;
Ok(())
@@ -523,7 +523,7 @@ fn surface(
let mut parts = if graphics.is_empty() {
vec![]
} else {
match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) {
match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) {
Some(parts) => {
copies.graphics = used;
parts
+2 -1
View File
@@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() {
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap();
let parts_of = |symbol: &str, copies: &mut usize| {
let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]}));
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len())
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies)
.map(|p| p.concat().len())
};
// Each opaque part copies the paint into its fill and its seam stroke; a part with
// transparent stops takes no seam stroke and copies it once.
+181 -17
View File
@@ -30,7 +30,7 @@ pub use graphics::{
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
rename_appearance_graphic_symbol,
fitting as graphic_fitting_scale, rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
@@ -84,11 +84,14 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
// on the back cap are dropped.
// on the back cap and on Extrude & Bevel's side are dropped.
if (to == ROTATE || to == crate::REVOLVE)
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
list.retain(|g| {
let face = g.get("face").and_then(Value::as_str);
face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id())
});
}
Value::Object(out)
}
@@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
both_sides: flag(p, "bevelBothSides", false),
}),
hidden: false,
map_surface: false,
}
}
@@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
}
}
/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest
/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics.
fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result<Vec<Facet>, String> {
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p))
}
/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build
/// ([`facets_and_faces`]).
fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result<CastingSolid, String> {
if !cast {
return side_facets(path, rule, bounds, p).map(|f| (f, None));
}
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
let options = Extrude { map_surface: true, ..extrude_options(p) };
vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces)))
}
/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side,
/// with parameters `p` and built about `bounds`: the first of those with the longest outline
/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel
/// or has no graphic on its side, or when no part has a side.
fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option<usize> {
if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) {
return None;
}
let options = extrude_options(p);
parts
.iter()
.enumerate()
.filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w)))
.fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) })
.map(|(k, _)| k)
}
/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of
/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0
/// that does not reach its cut and as tall as the length across its bevels and walls.
fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> {
let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?);
let options = extrude_options(p);
parts
.iter()
.filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options))
.fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) })
.map(|(_, height, span)| (span, height))
}
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
/// classic effects cast no shadow: they keep no faces.
@@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
reshape_members(n, before, &mut shapes);
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
check_profiles(id, p, &shapes, b)?;
return check_solids(id, p, &shapes);
check_solids(id, p, &shapes)?;
return check_side_graphics(doc, n, id, p, &shapes);
}
let (path, rule) = object_profile(n, label)?;
let anchors = || format!("{label} requires a shape with at least two anchors");
@@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let b = path.bounds().ok_or_else(anchors)?;
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)
check_solids(id, p, &shapes)?;
check_side_graphics(doc, n, id, p, &shapes)
}
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
@@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
paint_of(item, member).1 > 0.0
}
/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the
/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are
/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts
/// included. Without `doc` nothing is drawn, and nothing is checked.
fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
let Some(doc) = doc else { return Ok(()) };
let Some(b) = union_bounds(shapes) else { return Ok(()) };
let (parts, bounds) = solid_parts(shapes, b);
if side_carrier(id, p, &parts, bounds).is_none() {
return Ok(());
}
graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?;
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built draws the source path, without the side's graphics.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
Ok(())
}
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
@@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
@@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by
/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]):
/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it
/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
if parts.iter().all(Vec::is_empty) {
return surface;
}
let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface };
if children.len() != parts.len() {
return surface;
}
for (child, extra) in children.iter_mut().zip(parts) {
if extra.is_empty() {
continue;
}
let mut list = Vec::with_capacity(extra.len() + 1);
list.push(child.clone());
list.extend(extra);
*child = Arc::new(Node::group(id, list));
}
surface
}
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
@@ -802,7 +906,7 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
@@ -813,7 +917,9 @@ type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]).
/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one,
/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics
/// on Extrude & Bevel's side ([`side_carrier`]).
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
@@ -821,6 +927,7 @@ fn built_solids_cast<'a>(
bounds: Rect,
limit: usize,
cast: bool,
side: Option<usize>,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
@@ -834,7 +941,7 @@ fn built_solids_cast<'a>(
});
let mut kept = 0usize;
let mut ended = false;
parts.iter().map_while(move |(item, _, area, rule, _, _)| {
parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| {
if ended {
return None;
}
@@ -846,6 +953,7 @@ fn built_solids_cast<'a>(
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
each.next().unwrap_or_else(|| Ok((vec![], None)))
}
None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast),
None => facets_and_faces(id, area, *rule, bounds, p, cast),
};
let result = match built {
@@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op
f.depth = s.depth_at(mid).unwrap_or(s.depth);
f.contours = vec![points];
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
// A piece keeps where the whole face lies on the side: the parts of the side's graphics
// drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]).
Some(f)
};
Some((piece(1.0)?, piece(-1.0)?))
@@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
surfaces_with(doc, n, fx, shapes, cast, &mut false)
}
/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past
/// their limits on the pieces drawn, and the solid that takes them draws without them.
fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option<SurfacesAndFaces> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
}
let (parts, bounds) = solid_parts(shapes, b);
// The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest
// outline, whose pieces are built carrying where they lie on it.
let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None };
let mut solids = vec![];
let mut built = vec![];
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier);
for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() {
let item: &AppearanceItem = item;
match f {
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
@@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
solids.push((item, *opacity, *scopes, f, *member));
built.push(faces);
}
// A stroke's outline past the limits is left out; the fill's solid still draws.
Ok(None) => built.push(None),
// A stroke's outline past the limits is left out; the fill's solid still draws, and
// the side's graphics on that outline are not drawn.
Ok(None) => {
built.push(None);
*side_dropped |= carrier == Some(k);
}
// A loaded file or a shape edited past the limits (its own, or those of the object's
// solids together) keeps drawing its source path instead of failing the frame;
// commands validate the same evaluator and report its errors.
@@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
// ([`in_one_order`], [`underlaid_surface`]).
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default();
// The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve.
let mut graphic_copies = 0usize;
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
@@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
// The carrier's pieces draw the parts of the side's graphics that fall on them; past
// the graphics' limits the solid draws without them.
let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) {
vec![]
} else {
let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination));
let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies);
*side_dropped |= parts.is_none();
parts.unwrap_or_default()
};
let drawn = parts.iter().any(|p| !p.is_empty());
let art = if classic {
classic::surface(n, f, &paint, opacity, blend, &p)
} else {
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
};
(depths, art, scopes, ends)
})
@@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> b
/// Finds a 3D effect in a list of effects, with its index there.
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the
/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it
/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that
/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a
/// depth, or its art can't be built.
pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<(f64, f64)> {
let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?;
side_size(&crate::merged_params(&fx.id, &fx.params), &shapes)
}
/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from.
fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(Effect, Vec<Profile>)> {
let n = &*resolve(doc, n, "").ok()?;
let (fx, shapes) = if is_container(n) {
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
@@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
}
}
};
Some((fx.clone(), shapes))
}
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
let (fx, shapes) = frame_shapes(doc, n, item, pick)?;
if !takes_graphics(&fx.id) {
return None;
}
@@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
let plane = vectorcraft_three_d::plane_face_map(b, view);
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (_, bounds) = solid_parts(&shapes, b);
let (parts, bounds) = solid_parts(&shapes, b);
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back));
// With graphics on the side, the part of it the viewer sees places their handles.
let side = side_carrier(&fx.id, &p, &parts, bounds)
.and_then(|k| parts.get(k))
.and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok())
.map(|facets| graphics::SideFrame::of(&facets));
Some(match side {
Some(side) => frame.with_side(side),
None => frame,
})
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
+220 -54
View File
@@ -1,6 +1,6 @@
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
//! plane, turned, foreshortened and shaded with that face and clipped to it.
//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its
//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it.
//!
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
@@ -12,7 +12,10 @@
//! On Revolve the graphics lie on the swept side surface, unrolled flat
//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the
//! middle of that surface, x around the axis and y along the profile, and each face of the side
//! draws the part of the graphics that falls on it ([`surface_parts`]).
//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude &
//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the
//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with
//! the longest outline.
use std::sync::Arc;
@@ -110,7 +113,7 @@ impl MappedGraphic {
};
let face = match m.get("face") {
None => PlanarFace::Front,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?,
};
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
match m.get(key) {
@@ -139,7 +142,7 @@ impl MappedGraphic {
* Affine::scale(self.scale / 100.0)
* Affine::translate(-art.center().to_vec2());
match self.face {
PlanarFace::Front => place,
PlanarFace::Front | PlanarFace::Side => place,
// Seen from behind, the back's right is the front's left.
PlanarFace::Back => {
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
@@ -148,8 +151,8 @@ impl MappedGraphic {
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve
/// (its swept side).
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane)
/// and Revolve (its swept side).
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
}
@@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
/// the front.
/// the front. Only Extrude & Bevel takes graphics on its side.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
@@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
}
for v in list {
let g = MappedGraphic::from_value(v)?;
if id == super::ROTATE && g.face == PlanarFace::Back {
if id == super::ROTATE && g.face != PlanarFace::Front {
return Err("A plane has one face: map its graphics onto the front".into());
}
if id == crate::REVOLVE && g.face == PlanarFace::Back {
if id == crate::REVOLVE && g.face != PlanarFace::Front {
return Err("Revolve maps graphics onto its side: map them onto the front".into());
}
}
@@ -598,14 +601,14 @@ struct Unrolled {
place: Affine,
}
/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side
/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is
/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than
/// [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> {
/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side)
/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does
/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces
/// take more than [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option<Vec<Unrolled>> {
let mut pieces = vec![];
let mut points = 0usize;
for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) {
for g in graphics.iter().filter(|g| g.face == face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(art) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
@@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>
(*points <= MAX_ELEMENTS).then_some(polygons)
}
/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art,
/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> {
/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit
/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface,
/// may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> {
let list = mapped_graphics(p);
if list.is_empty() || unrolled(doc, &list).is_some() {
if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() {
return Ok(());
}
Err("The graphics are too complex: simplify the symbols' art".into())
}
/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing
/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces
/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows
/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it.
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
pub(crate) fn surface_parts(
/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's
/// swept side, or a piece of Extrude & Bevel's walls and bevels.
pub(crate) trait SurfaceFace {
/// Where the face lies on the side unrolled, when it is a face of the side that shows its
/// outside to the viewer.
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>;
/// The outline the face's parts are cut to, when it is not the polygon of its cell's corners:
/// its curved outline, when its edges along an end are curved, or the outline of a piece cut
/// from a larger face.
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>>;
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient>;
fn light(&self) -> [f64; 3];
fn outline_path(&self) -> PathData;
}
impl SurfaceFace for vectorcraft_three_d::Face {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward && !self.cap)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
self.outline.as_ref().map(std::borrow::Cow::Borrowed)
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.illumination
}
fn outline_path(&self) -> PathData {
self.path()
}
}
impl SurfaceFace for Facet {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
if let Some(outline) = &self.outline {
return Some(std::borrow::Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through a wall keeps its face's cell.
let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page));
cut.then(|| std::borrow::Cow::Owned(self.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.illumination
}
fn outline_path(&self) -> PathData {
self.path()
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side)
/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id
/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their
/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past
/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color
/// on a face, as the surface under it is shaded; the colors of gradients and patterns are
/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the
/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are
/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the
/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's
/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded
/// file draws the surface without them.
pub(crate) fn surface_parts<F: SurfaceFace>(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
faces: &[vectorcraft_three_d::Face],
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
(graphics, face): (&[MappedGraphic], PlanarFace),
faces: &[F],
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
copies: &mut usize,
) -> Option<Vec<Vec<Arc<Node>>>> {
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()];
let Some(doc) = doc else { return Some(out) };
let pieces = unrolled(doc, graphics)?;
let pieces = unrolled(doc, graphics, face)?;
let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) };
// Each piece listed in the buckets of the surface's x its bounds reach across.
let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9);
@@ -729,11 +790,12 @@ pub(crate) fn surface_parts(
let mut cut_points = 0usize;
let mut triangle_id = 0usize;
for (face, parts) in faces.iter().zip(out.iter_mut()) {
let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue };
let Some(cell) = face.outer_cell() else { continue };
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
continue;
}
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
let curved = face.curved();
for corners in triangles {
triangle_id += 1;
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
@@ -744,7 +806,7 @@ pub(crate) fn surface_parts(
// where the graphic runs past the end of the profile. A four-cornered face is cut into
// two triangles along its diagonal from corner 0 to corner 2: each takes the part of
// the outline on its own side of it.
let window = if face.outline.is_some() { grown(window, 3.0) } else { window };
let window = if curved.is_some() { grown(window, 3.0) } else { window };
// The pieces are looked up over the whole of the window they are cut to.
let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue };
if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 {
@@ -771,7 +833,7 @@ pub(crate) fn surface_parts(
}
near.sort_unstable();
let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2);
let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
(Some(&toward), Some(&a), Some(&b)) => {
let side = side_of(a, b, toward);
vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect)
@@ -834,21 +896,21 @@ pub(crate) fn surface_parts(
/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes
/// from the unrolled surface onto `face`.
fn surface_piece(
fn surface_piece<F: SurfaceFace>(
id: NodeId,
piece: &Unrolled,
(path, rule): (BezPath, FillRule),
map: Affine,
face: &vectorcraft_three_d::Face,
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
face: &F,
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
) -> Node {
let gradient_map = map * piece.place;
// Under several lights a face's light varies across it in each channel: a solid color draws
// as the face's own lit art in that color, clipped to the part. An opaque part also draws that
// art clipped to a band of the seam stroke's width around its edges, as the other parts take
// a stroke over their seams.
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) {
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light));
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) {
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light));
let clipped = |area: &BezPath, rule: FillRule| {
let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default());
if let NodeKind::Path { rule: r, .. } = &mut clip.kind {
@@ -881,7 +943,7 @@ fn surface_piece(
match solid {
Some(c) => f.paint = shade(face, c),
None => {
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination));
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light()));
}
}
}
@@ -996,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
}
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center) and the maps of its front and back faces, when it has them.
#[derive(Clone, Copy, Debug, PartialEq)]
/// offsets are from their center), the maps of its front and back faces, when it has them, and
/// the visible part of its side unrolled, when it has graphics there.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
side: Option<SideFrame>,
}
/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are
/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the
/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger
/// is nearer).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SideFrame {
pieces: Vec<SidePiece>,
}
#[derive(Clone, Debug, PartialEq)]
struct SidePiece {
uv: Vec<Point>,
page: Vec<Point>,
outline: Option<BezPath>,
depth: f64,
}
impl SideFrame {
/// The pieces of `facets` that carry where they lie on the side unrolled and show its outside.
pub(super) fn of(facets: &[Facet]) -> Self {
let pieces = facets
.iter()
.filter_map(|f| {
let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?;
let outline = f.curved().map(|o| o.to_bezpath());
Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth })
})
.collect();
Self { pieces }
}
/// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped
/// onto the side unrolled, through the nearest piece whose drawn part holds it: within the
/// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and
/// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it.
fn map(&self, p: Point, from_page: bool) -> Option<Point> {
let inside = |t: &[Point; 3], q: Point| {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
};
let mut best: Option<(Point, f64)> = None;
for piece in &self.pieces {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
for corners in triangles {
let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]);
let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue };
let window = if piece.outline.is_some() { grown(a, 3.0) } else { a };
if !inside(&window, p) {
continue;
}
// A four-cornered piece's two triangles meet along its diagonal: each holds its side.
if triangles.len() == 2
&& let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 }))
{
let across = |q: Point| (d2 - d0).cross(q - d0);
if across(p) * across(own) < 0.0 {
continue;
}
}
let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue };
let on_page = if from_page { p } else { q };
if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) {
continue;
}
if best.is_none_or(|(_, depth)| piece.depth > depth) {
best = Some((q, piece.depth));
}
}
}
best.map(|(q, _)| q)
}
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back }
Self { bounds, front, back, side: None }
}
/// The frame with the visible part of the side `side`, for its graphics' handles.
pub(super) fn with_side(self, side: SideFrame) -> Self {
Self { side: Some(side), ..self }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
PlanarFace::Back => self.back.as_ref(),
PlanarFace::Side => None,
}
}
@@ -1023,23 +1168,34 @@ impl GraphicFrame {
match face {
PlanarFace::Front => Point::new(c.x + x, c.y + y),
PlanarFace::Back => Point::new(c.x - x, c.y + y),
PlanarFace::Side => Point::new(x, y),
}
}
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point.
/// viewer. `None` when the object has no such face or the point has no page point. A graphic on
/// the side lands where its center is on the part of the side the viewer sees, and is `None`
/// elsewhere.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
if g.face == PlanarFace::Side {
return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true));
}
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`.
/// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only
/// a point on the part of the side the viewer sees has one.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = self.map(face)?.to_art(page)?;
let art = match face {
PlanarFace::Side => self.side.as_ref()?.map(page, true)?,
_ => self.map(face)?.to_art(page)?,
};
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
PlanarFace::Side => (art.x, art.y),
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
@@ -1047,11 +1203,17 @@ impl GraphicFrame {
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
/// 100: where a newly mapped graphic starts.
pub fn fitting_scale(&self, art: Rect) -> f64 {
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
fitting(self.bounds.width(), self.bounds.height(), art)
}
}
/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at
/// most 100.
pub fn fitting(width: f64, height: f64, art: Rect) -> f64 {
let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
}
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
pub fn graphic_symbols(n: &Node) -> Vec<String> {
appearance_graphic_symbols(&n.appearance)
@@ -1135,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
#[cfg(test)]
#[path = "tests_graphics.rs"]
mod tests;
#[cfg(test)]
#[path = "tests_graphics_side.rs"]
mod tests_side;
+1
View File
@@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
side: true,
away: false,
end: None,
surface: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
+8 -2
View File
@@ -531,12 +531,13 @@ fn graphics_are_checked() {
let n = object(EXTRUDE, json!({}));
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok());
assert!(check(EXTRUDE, json!([])).is_ok());
for bad in [
json!("Mark"),
json!([{"face": "front"}]),
json!([{"symbol": ""}]),
json!([{"symbol": "Mark", "face": "side"}]),
json!([{"symbol": "Mark", "face": "top"}]),
json!([{"symbol": "Mark", "scale": 0.0}]),
json!([{"symbol": "Mark", "rotation": 400.0}]),
json!([{"symbol": "Mark", "x": "1"}]),
@@ -546,10 +547,12 @@ fn graphics_are_checked() {
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err());
assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
@@ -569,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() {
#[test]
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]});
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
// Revolve drops the side's graphics too; Extrude & Bevel keeps every face's.
assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]);
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
@@ -0,0 +1,255 @@
//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat.
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{StrokeLayer, Symbol};
use vectorcraft_geom::shapes;
use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in};
use super::*;
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn square(id: u64, r: Rect, paint: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
}
/// A document with symbol "Mark": a red 10 × 10 square.
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol {
dynamic: false,
name: "Mark".into(),
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
});
d
}
/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the
/// viewer, its front edge at the bottom of the page), with `params` over that.
fn object(params: Value) -> Node {
let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
n
}
fn is_red(p: &Paint) -> bool {
p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
}
/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline.
fn faces_with_parts(art: &Node) -> Vec<Vec<PathData>> {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { children, clip: false } = &n.kind
&& let Some((face, parts)) = children.split_first()
&& matches!(face.kind, NodeKind::Path { .. })
&& !parts.is_empty()
{
let red: Vec<PathData> = parts
.iter()
.filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint))))
.filter_map(|p| p.path_data().cloned())
.collect();
if red.len() == parts.len() {
out.push(red);
}
}
});
out
}
fn bounds(parts: &[Vec<PathData>]) -> Rect {
parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
fn near(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
}
/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the
/// middle of the side toward the back.
#[test]
fn a_side_graphic_lies_on_the_wall_at_its_offset() {
let d = document();
let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let found = faces_with_parts(&art);
assert_eq!(found.len(), 1, "drawn once, on the top wall");
// Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25).
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap());
assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found));
// Without the document nothing is drawn; a graphic on the side leaves the caps without one.
assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty());
}
/// A graphic that reaches past a corner runs on around it onto the next wall.
#[test]
fn a_side_graphic_runs_around_a_corner() {
let d = document();
// x = 50 is the top's right end.
let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap());
assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found));
// Turned to show the top and the right, both walls draw their part.
let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2);
// Twist and taper carry the graphic; it stays on the side.
let twisted =
object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]}));
let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap());
assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))));
}
/// The handle lands where the graphic's center is on the visible side, and a page point there
/// gives back its offset; a graphic on a hidden wall has no handle.
#[test]
fn the_sides_handle_moves_the_graphic_on_its_visible_part() {
let d = document();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap();
let n = object(json!({"graphics": [g.to_value()]}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}");
let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap();
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
// The bottom's middle, half way around, is hidden from above; so is a page point off the top.
let hidden = MappedGraphic { x: 200.0, ..g.clone() };
assert!(frame.handle(&hidden).is_none());
assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none());
// Without a graphic on the side, the frame places no handle there.
let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap();
assert!(caps.handle(&g).is_none());
}
/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's
/// center and a page point there gives back its offset.
#[test]
fn the_handle_follows_a_curved_side() {
let d = document();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap();
let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]}));
if let NodeKind::Path { path, .. } = &mut n.kind {
*path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
}
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible);
let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap();
assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}");
}
/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is
/// the longest, takes them once.
#[test]
fn a_hollow_or_stroked_object_takes_a_side_graphic() {
let d = document();
let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]}));
let art = solid_art_in(Some(&d), &hollow).unwrap();
assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0)));
let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0)));
let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap());
assert_eq!(found.len(), 1, "on the stroke's outer wall only");
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
// The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the
// top's middle: a new graphic fits the 330 pt about x = 0 and the depth.
assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0)));
}
/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and
/// each piece draws only the part of the graphic within its own outline.
#[test]
fn a_piece_cut_from_a_face_draws_its_own_part() {
let d = document();
let facet = |x: f64, normal: [f64; 3], offset: f64| {
let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect();
Facet {
contours: vec![square.clone()],
depth: 0.0,
brightness: 1.0,
illumination: [1.0; 3],
normal,
rgb_gradient: None,
outline: None,
side: true,
away: false,
end: None,
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
}
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
let r = std::f64::consts::FRAC_1_SQRT_2;
let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)];
super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0);
assert_eq!(stroke.len(), 2, "cut where it passes through the wall");
// The graphic covers the whole face, x 5 to 15 on the page.
let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]}));
let shade = |_: &Facet, c: Color| Paint::solid(c);
let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap();
let drawn: Vec<Rect> =
parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect();
// Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic.
let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1));
assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}");
assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}");
}
/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the
/// limit of points, though its own path elements are few; on a cap it is accepted.
#[test]
fn a_side_graphic_past_its_limits_is_refused() {
let mut d = document();
// 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut.
let mut subpaths = vec![];
for k in 0..200 {
let x = f64::from(k);
subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths);
}
let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) });
let n = object(json!({}));
let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]});
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err());
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok());
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok());
}
/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces
/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object
/// casts without a graphic.
#[test]
fn a_side_graphic_keeps_its_place_with_the_shadow_on() {
let d = document();
let shadow = |art: &Node| {
let first = &art.children().unwrap()[0];
let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") };
assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}");
first.path_data().and_then(PathData::bounds).unwrap()
};
let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0});
let mut with_graphic = lit.clone();
with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]);
let n = object(with_graphic);
super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0));
super::super::SOLIDS_BUILT.with(|b| b.set(0));
let art = solid_art_in(Some(&d), &n).unwrap();
let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get));
assert_eq!(builds, (1, 1), "one build for the faces and the shadow");
let found = faces_with_parts(&art);
assert_eq!(found.len(), 1, "drawn once, on the top wall");
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
let without = solid_art_in(Some(&d), &object(lit)).unwrap();
assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without));
}
+1 -1
View File
@@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() {
let p = crate::merged_params(id, &json!({"shadow": true}));
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut built: Vec<Option<SolidFaces>> =
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
+28 -3
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());
@@ -407,7 +413,18 @@ pub fn command_specs() -> &'static [CommandSpec] {
/// The command `id`: a built-in one, or a command an installed plug-in adds
/// ([`plugin::command_specs`]).
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
static INDEX: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static CommandSpec>> = std::sync::OnceLock::new();
INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id))
}
/// `specs` by id. An id that more than one spec has names the first of them, as a search of
/// `specs` in order finds.
pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> {
let mut index = std::collections::HashMap::with_capacity(specs.len());
for spec in specs {
index.entry(spec.id).or_insert(spec);
}
index
}
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
@@ -829,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;
@@ -861,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`).
@@ -888,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;
+4 -1
View File
@@ -3,11 +3,13 @@
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
//! ([`tangents`]) and Tangent Circle
//! ([`tangent_circle`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
mod bridge;
mod corners;
#[cfg(test)]
mod effect_tests;
@@ -183,6 +185,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(corners::specs());
v.extend(shared_edge::specs());
v.extend(trim::specs());
v.extend(bridge::specs());
v.extend(tangent_circle::specs());
v.extend(tangents::specs());
v
@@ -0,0 +1,164 @@
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
//! 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};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
use super::super::super::pathops::{Beside, remove_each};
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
use super::given;
use crate::{EngineError, Result, Session};
#[cfg(test)]
mod tests;
/// The command, and its undo step's name.
const C: &str = "addon.pathtools.bridge";
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!(
"addon.pathtools.bridge",
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{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)?;
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 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();
d.paint_order(roots.iter().copied())
.into_iter()
.filter_map(|id| match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
_ => None,
})
.collect()
};
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))
}
};
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])?;
}
beside.finish(d)?;
} else {
// 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, &gone)?;
}
sel.set(made.iter().chain(&alone).copied());
Ok(made)
})?;
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"),
}
}
@@ -0,0 +1,356 @@
//! 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};
use vectorcraft_geom::kurbo::Shape;
use crate::Session;
const BRIDGE: &str = "addon.pathtools.bridge";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
/// A circle about (`x`, `y`) with radius `r`.
fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId {
let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap();
NodeId(id)
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn top_level(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
fn area(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(BRIDGE, &p).unwrap_err().to_string()
}
#[test]
fn two_circles_become_one_outline_in_the_upper_ones_place() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
select(&mut s, &[a, b]);
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") };
assert!(live.is_none(), "a plain path now");
assert!(path.subpaths.len() == 1 && path.subpaths[0].closed);
let bounds = path.bounds().unwrap();
assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}");
// Both circles and the bridge between them: more than the two circles' area.
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(top_level(&s), [a, b]);
assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was");
}
#[test]
fn keep_originals_adds_the_outline_above_the_upper_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 30.0);
let b = circle(&mut s, 170.0, 100.0, 10.0);
let c = circle(&mut s, 300.0, 250.0, 5.0);
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [a, b, id, c]);
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle");
assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are");
assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }));
let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap();
assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
}
#[test]
fn a_kept_outline_gets_its_own_mask_art() {
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 m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap();
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id);
let (kept, copied) = (art(b).unwrap(), art(id).unwrap());
assert_ne!(kept, copied, "the outline's mask art has ids of its own");
}
#[test]
fn a_larger_radius_makes_a_wider_bridge() {
let area_at = |radius: f64| {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
area(&s, id)
};
let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0));
assert!(default < wider && wider < widest, "{default} {wider} {widest}");
let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0));
assert!(narrow < default && default < wide, "{narrow} {default} {wide}");
// The default is 100%: the smaller circle's radius.
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 15.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
assert!((area(&s, id) - default).abs() < 1e-9);
}
#[test]
fn overlapping_and_touching_circles_are_joined() {
for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 140.0 + gap, 100.0, 20.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "gap {gap}");
}
// Unequal overlapping circles at every radius, the largest included.
for radius in [1.0, 100.0, 300.0, 1000.0] {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 10.0);
let b = circle(&mut s, 125.0, 100.0, 30.0);
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
assert_eq!(top_level(&s), [id], "radius {radius}");
}
}
#[test]
fn far_apart_nested_and_other_objects_are_refused() {
let mut s = session();
let a = circle(&mut s, 50.0, 100.0, 10.0);
let far = circle(&mut s, 250.0, 100.0, 10.0);
let near = circle(&mut s, 110.0, 100.0, 10.0);
let inner = circle(&mut s, 52.0, 100.0, 4.0);
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
let before = top_level(&s);
let steps = s.doc().unwrap().history.undo.len();
// 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can.
assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius"));
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok());
s.execute("edit.undo", &json!({})).unwrap();
// 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above
// ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested.
for radius in [100, 1000] {
let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius}));
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, 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"));
assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false"));
assert_eq!(top_level(&s), before);
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();
let a = circle(&mut s, 100.0, 100.0, 20.0);
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 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 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 {
+3 -3
View File
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
@@ -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
),
@@ -265,7 +265,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Symbol",
[],
None,
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
"{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is 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; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}",
has_selection,
symbol_update
),
+6 -1
View File
@@ -32,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
let name = name_param(p, "brush.get")?;
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
Ok(serde_json::to_value(b).unwrap_or_default())
let mut v = serde_json::to_value(&b).unwrap_or_default();
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
}
Ok(v)
}
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
+33 -4
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),
@@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Redefining the symbol being edited leaves symbol editing mode in the same step.
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
let keep_art = switch_or(p, "keepArt", false, C)?;
if session.is_some() {
crate::cmd::settle_interaction(s)?;
s.end_text_edit();
@@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
// Nor can art that holds an instance of it, directly or through the symbols it nests.
if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) {
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
}
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, c) = normalize(art)?;
let old = natural_size(&s.doc()?.doc, &name);
let editing = session.is_some();
// The isolation the kept art is selected in: the one from before symbol editing mode when
// the step leaves it.
let iso = match &session {
Some(se) => se.back_isolation,
None => s.doc()?.isolation,
};
let id = s.edit("Redefine Symbol", |d, sel| {
if editing {
crate::cmd::symboledit::finish(d, sel);
@@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
}
// Each instance keeps its appearance changes to the objects the new art still has.
fit_overrides(d, &instances);
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 reg = d.symbol_registration(&name);
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
sel.set([id]);
Ok(id)
Ok(Some(id))
})?;
if let Some(se) = &session {
crate::cmd::symboledit::leave_editing(s, se)?;
}
Ok(json!({ "name": name, "id": id.0 }))
Ok(json!({ "name": name, "id": id.map(|i| i.0) }))
}
/// How many levels of nested instances Delete Symbol expands before it gives up.
+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
+51 -160
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",
@@ -126,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -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")?);
@@ -940,7 +806,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
if p.get("font").is_some() || p.get("style").is_some() {
// A face from a redefined [Normal Character Style] is checked too, as one given here is.
let normal_face = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style"));
if p.get("font").is_some() || p.get("style").is_some() || normal_face {
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
_ => Default::default(),
@@ -968,8 +840,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
/// The paragraph alignment, leading model and character alignment new type starts with (`t`'s
/// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel`
/// and `charAlign` from `p`, else em box top to top and em box centre while the
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that
/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432),
/// else the Roman baseline for both. Noted in the journal, so a
/// replay sets the same whatever the interface.
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
use vectorcraft_doc::{CharAlign, LeadingModel};
@@ -989,7 +862,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
l
}
};
let align = match super::textedit::char_align_param(p, cmd)? {
// A redefined [Normal Character Style] that sets Character Alignment gives it to new type.
let normal_align = s
.doc()
.ok()
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
.filter(|m| m.contains_key("charAlign"))
.and(t.runs.first().map(|r| r.style.char_align));
let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) {
Some(a) => a,
None => {
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
@@ -1017,17 +897,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
}
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
/// #7975), in the document's
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else
/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined;
/// never the current fill, #7975), in the style's language, else the document's. A `size` outside
/// [`super::typecmd::TYPE_SIZES`] is an error.
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
let mut style = CharStyle::default();
let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc));
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
style.size = super::typecmd::given_type_size(sz, cmd)?;
}
if str_param(p, "font").is_some() || str_param(p, "style").is_some() {
// A face given to the command takes its own version and axis settings, as a font change
// does, not those [Normal Character Style] gave another face.
style.font_version = None;
style.font_axes.clear();
}
if let Some(f) = str_param(p, "font") {
style.font_family = f.to_string();
// A family alone starts in Regular, whatever style [Normal Character Style] has.
style.font_style = CharStyle::default().font_style;
}
if let Some(f) = str_param(p, "style") {
style.font_style = f.to_string();
@@ -1037,12 +925,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
}
style.fill = match p.get("color").and_then(color_value) {
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
None => style.fill,
};
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
// for the default. Type already in a document keeps its own.
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
// In the language a redefined [Normal Character Style] gives, else the one Document Setup chose,
// else Preferences › Hyphenation › Default Language; none for the default. Type already in a
// document keeps its own.
if style.language.is_none() {
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
}
Ok(style)
}
+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);
+2 -1
View File
@@ -238,7 +238,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Guide",
[],
None,
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
guides_unlocked,
guide_move
),
@@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
let dx = number_or(p, "dx", 0.0, "guide.move")?;
let dy = number_or(p, "dy", 0.0, "guide.move")?;
let copy = switch_or(p, "copy", false, "guide.move")?;
switch_or(p, "interpolate", false, "guide.move")?;
if !s.doc()?.selection.is_empty() {
let ids = super::edit::selected_roots(s)?;
return super::object::apply_transform(
+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)?);
}
}
+17 -7
View File
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
// A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned
// on again, but has no cap to show a new one on. Its side takes graphics.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
let side = base.face == effects::PlanarFace::Side;
if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
{
graphic.scale = frame.fitting_scale(art);
// A graphic on the side starts fitting inside the side unrolled about x = 0, short of
// its cut; one on a cap inside the object's bounds.
let fit = if side {
effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art))
} else {
effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art))
};
if let Some(fit) = fit {
graphic.scale = fit;
}
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, (item, index)).map_err(|e| bad(C, e))?;
@@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() {
let (mut s, id) = setup("threeD.extrude");
// A hollow Extrude & Bevel takes a graphic on its side.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}]));
// A plane, and a depth of 0, have no side.
let (mut s, plane) = setup("threeD.rotate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
let (mut s, flat) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
// A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is
// about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is
// 11 × 21.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap();
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}");
// A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the
// part about x = 0 is three quarters of the outline.
let (mut s, id) = setup("threeD.extrude");
let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap();
let d = &s.doc().unwrap().doc;
let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap();
let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap();
assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}");
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}");
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
+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)?;
+2
View File
@@ -29,6 +29,8 @@ mod commands;
mod common;
mod envelope;
mod mesh;
#[cfg(test)]
mod selected_tests;
pub(crate) use blend::expand_blends;
pub use commands::specs;
+40 -4
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;
@@ -657,9 +694,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
}
/// Is any selected blend one made without a spine?
fn any_without_spine(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
pub(super) fn any_without_spine(s: &Session) -> bool {
super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine))
}
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
+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
),
+21 -11
View File
@@ -1,3 +1,5 @@
use std::collections::HashSet;
use super::mesh::whole;
use super::{
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
@@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let mut sel = Selection::default();
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
let ordered = sel.in_paint_order(&st.doc);
let given: HashSet<NodeId> = ordered.iter().copied().collect();
// Drop ids nested inside other given ids.
return Ok(ordered
.iter()
.copied()
.filter(|id| {
let anc = st.doc.ancestry(*id).unwrap_or_default();
!anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a))
!anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a))
})
.collect());
}
@@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
/// dynamic symbol instance's art is selected.
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut find = st.doc.nearest_finder();
let mut seen = HashSet::new();
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
if let Some(n) = find.nearest(*id, pred)
&& seen.insert(n.id)
{
out.push(n.id);
}
}
out
}
/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the
/// first one that does.
pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false };
let mut find = st.doc.nearest_finder();
st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test))
}
pub(super) fn is_blend(n: &Node) -> bool {
matches!(n.kind, NodeKind::Blend { .. })
}
@@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) }
}
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) }
}
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) }
}
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
@@ -0,0 +1,324 @@
//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones
//! the lookup of every ancestor by id found: the same ids in the same order, the same availability
//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree.
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart};
use super::Session;
use super::blend::any_without_spine;
use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of};
/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from
/// the object up, repeats dropped by a scan of the list.
fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
let mut out = vec![];
for id in &st.selection.objects {
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
if st.doc.node(a).is_some_and(pred) {
if !out.contains(&a) {
out.push(a);
}
break;
}
}
}
out
}
/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`].
fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> {
super::has_selection(s)?;
crate::cmd::edit::no_symbol_part(s)?;
if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) }
}
/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`].
fn without_spine_by_ids(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
}
/// Every check on the current selection gives what the lookups by id gave.
fn agree(s: &Session, what: &str) {
type Has = fn(&Session) -> std::result::Result<(), String>;
for (name, pred, has, msg) in [
("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"),
("envelope", is_envelope, has_envelope, "select an envelope"),
("mesh", is_mesh, has_mesh, "select a gradient mesh"),
] {
let want = selected_of_by_ids(s, pred);
assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s");
assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}");
assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}");
}
assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine");
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id_of(v: &serde_json::Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId {
select(s, ids);
id_of(&s.execute(cmd, &p).unwrap())
}
/// Every node id under the layers, parents before children (as Direct Selection can pick them).
fn all_ids(s: &Session) -> Vec<NodeId> {
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<NodeId>) {
for n in nodes {
out.push(n.id);
if let Some(ch) = n.children() {
walk(ch, out);
}
}
}
let mut out = vec![];
for l in &s.doc().unwrap().doc.layers {
walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out);
}
out
}
/// The active document, to change in place.
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
/// Set the selection's objects as given, stale and repeated ids included.
fn set_objects(s: &mut Session, ids: Vec<NodeId>) {
s.doc_mut().unwrap().selection.objects = ids;
}
/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine.
/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key
/// of `a`.
fn document() -> (Session, [NodeId; 6]) {
let mut s = session();
let r: Vec<NodeId> = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect();
let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({}));
let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({}));
let g = run(&mut s, "object.group", &[a, r[4]], json!({}));
let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({}));
let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50}));
select(&mut s, &[r[7]]);
s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap();
if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) {
spec.no_spine = true;
}
(s, [a, b, c, g, e, r[0]])
}
#[test]
fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() {
let (mut s, [a, b, c, g, e, inner_key]) = document();
s.execute("select.all", &json!({})).unwrap();
agree(&s, "select all");
let all = all_ids(&s);
let keys: Vec<NodeId> = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect();
set_objects(&mut s, keys.clone());
agree(&s, "keys, as Direct Selection picks them");
set_objects(&mut s, all.iter().rev().copied().collect());
agree(&s, "every node, children first");
set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]);
agree(&s, "repeated and stale ids, in first-seen order");
assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order");
set_objects(&mut s, vec![NodeId(999_999)]);
agree(&s, "only a stale id");
set_objects(&mut s, vec![]);
agree(&s, "nothing");
// A blend in another blend's key group: the inner one.
set_objects(&mut s, vec![inner_key]);
agree(&s, "a key of a blend nested in another's key group");
assert_eq!(selected_of(&s, is_blend), vec![a]);
// An object of a dynamic symbol instance's art: nothing.
set_objects(&mut s, all.clone());
s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] });
agree(&s, "a symbol part");
assert!(selected_of(&s, is_blend).is_empty());
}
/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's
/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is
/// built again.
#[test]
fn a_repeated_id_counts_as_its_first_node() {
let (mut s, [a, _, c, _, _, inner_key]) = document();
let all = all_ids(&s);
s.doc().unwrap().doc.node(a);
let doc = doc_mut(&mut s);
if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() {
ch.insert(0, std::sync::Arc::new(Node::group(a, vec![])));
}
set_objects(&mut s, all.clone());
agree(&s, "a repeated id, the cache older than the tree");
s.doc().unwrap().doc.drop_lookup_cache();
agree(&s, "a repeated id, no cache");
s.doc().unwrap().doc.node(a);
agree(&s, "a repeated id, cached afresh");
set_objects(&mut s, vec![inner_key]);
assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts");
}
/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and
/// the checks stop at the first selected object that has one.
#[test]
fn selected_blends_take_no_lookups_by_id() {
let mut s = session();
let mut keys = vec![];
for i in 0..300 {
let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0));
run(&mut s, "object.blend.make", &[x, y], json!({}));
keys.extend([x, y]);
}
for i in 0..1_000 {
rect(&mut s, i as f64);
}
s.execute("select.all", &json!({})).unwrap();
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(keys[0]);
let before = vectorcraft_doc::path_lookups();
assert_eq!(selected_of(&s, is_blend).len(), 300);
assert!(!any_selected_of(&s, is_mesh, |_| true));
set_objects(&mut s, keys.clone());
assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys");
assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id");
// The first key is in a blend: the check tests that key and its blend only.
static TESTED: AtomicUsize = AtomicUsize::new(0);
fn counted(n: &Node) -> bool {
TESTED.fetch_add(1, Ordering::Relaxed);
is_blend(n)
}
assert!(any_selected_of(&s, counted, |_| true));
assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested");
}
/// `n` and everything under it with new ids.
fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node {
let mut n = n.clone();
n.id = d.alloc_id();
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
*c = std::sync::Arc::new(renumber(d, c));
}
}
n
}
/// This thread's CPU time in nanoseconds, where the system reports it (Linux).
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it,
/// otherwise in wall-clock time.
fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 {
let (cpu, wall) = (cpu_ns(), std::time::Instant::now());
for _ in 0..calls {
f();
}
let ms = match (cpu, cpu_ns()) {
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
_ => wall.elapsed().as_secs_f64() * 1e3,
};
ms / f64::from(calls)
}
/// The medians of 7 runs of `a` and of `b`, the runs taking turns.
fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) {
let (mut ta, mut tb) = (vec![], vec![]);
for _ in 0..7 {
ta.push(ms_per_call(calls, a));
tb.push(ms_per_call(calls, b));
}
ta.sort_by(f64::total_cmp);
tb.sort_by(f64::total_cmp);
(ta[3], tb[3])
}
/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers,
/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with
/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand"]
fn timing_of_the_selected_blend_checks() {
let mut s = session();
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0));
let square = rect(&mut s, 120.0);
let blend = run(&mut s, "object.blend.make", &[a, b], json!({}));
let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50}));
let doc = doc_mut(&mut s);
let templates: Vec<Node> = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect();
let mut layers = vec![];
for l in 0..10 {
let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0));
let mut kids = vec![];
for _ in 0..10_000 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[0])));
}
for i in 0..200 {
let b = renumber(doc, &templates[1]);
let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b };
kids.push(std::sync::Arc::new(b));
}
for _ in 0..20 {
kids.push(std::sync::Arc::new(renumber(doc, &templates[2])));
}
if let Some(ch) = layer.children_mut() {
*ch = kids;
}
layers.push(std::sync::Arc::new(layer));
}
doc.layers = layers;
s.execute("select.all", &json!({})).unwrap();
let first = s.doc().unwrap().selection.objects[0];
s.doc().unwrap().doc.drop_lookup_cache();
s.doc().unwrap().doc.node(first);
println!("{} objects selected", s.doc().unwrap().selection.objects.len());
type Check = fn(&Session) -> bool;
let checks: [(&str, Check, Check); 5] = [
("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()),
("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()),
("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()),
(
"selected blends (object.blend.info and the Blend commands)",
|s| !selected_of_by_ids(s, is_blend).is_empty(),
|s| !selected_of(s, is_blend).is_empty(),
),
("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine),
];
assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend));
println!("| Check | Lookups by id (ms) | One path (ms) |");
println!("|---|---:|---:|");
for (name, by_ids, one_path) in checks {
assert_eq!(by_ids(&s), one_path(&s), "{name}");
let (old, new) = medians(
15,
&|| {
std::hint::black_box(by_ids(&s));
},
&|| {
std::hint::black_box(one_path(&s));
},
);
println!("| {name} | {old:.3} | {new:.3} |");
}
}
+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> {
+1 -1
View File
@@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
let refi = reference_index(p)?;
let st = s.doc()?;
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
check_switches(p, &["proportional"], "object.setBounds")?;
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
let how = s.bounds_measure();
if anchors
&& transforms_objects(p)
+9 -9
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform",
[],
None,
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, 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), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, 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), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
has_doc,
transform
),
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move…",
["Object", "Transform"],
Some("Cmd+Shift+M"),
"{ids?: [id…] (selected first; default: the selection), dx, dy, 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), dx, dy, 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), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. 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_or_guides,
move_cmd
),
@@ -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\", 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
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transform Again",
["Object", "Transform"],
Some("Cmd+D"),
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
has_selection,
transform_again
),
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
@@ -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
),
@@ -295,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Bounds",
[],
None,
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
has_selection,
set_bounds
),
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+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();
+17 -2
View File
@@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
let items = match p.get("items").filter(|v| !v.is_null()) {
@@ -193,6 +193,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
// its span (its end angle less its start angle, counterclockwise).
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
}
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
@@ -204,7 +210,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// ellipse as 0° to 360°).
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
let pie_of = |pie: (f64, f64)| {
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
let span = (pie.1 - pie.0).rem_euclid(360.0);
let pie = match (constrain, pie_start, pie_end) {
// The angle it already has: nothing moves.
(true, Some(a), _) if a == pie.0 => pie,
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
// A whole ellipse (a span of 0) stays whole.
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
};
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
};
// When every value given is the current one, the document and its undo history stay as they
+83 -22
View File
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
let d = &s.doc()?.doc;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
let mut interpolate = None;
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
}
if xf != Affine::IDENTITY {
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
}
ids
} else if none || (!copy && xf == Affine::IDENTITY) {
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
options["strokes"] = json!(sc.strokes);
options["corners"] = json!(!sc.keep_corners);
}
if let Some(on) = interpolate {
options["interpolate"] = json!(on);
}
st.last_transform = Some(LastTransform::Matrix(xf, options));
st.last_perspective = None;
}
@@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
// is left as it is, and the reply's warning goes to the status bar.
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.move")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
check_switches(p, &["interpolate"], "object.move")?;
let ids = selected_roots_to_transform(s)?;
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
}
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["dx", "dy"], "object.nudge")?;
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
check_switches(p, &["big"], "object.nudge")?;
check_switches(p, &["big", "interpolate"], "object.nudge")?;
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
@@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if dx == 0.0 && dy == 0.0 {
return ok();
}
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
}
if s.doc()?.selection.is_empty() {
let copy = bool_or(p, "copy", false);
@@ -360,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
@@ -393,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 => {
@@ -414,22 +421,76 @@ 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 vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical");
let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) };
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") {
None | Some(Value::Null) => horizontal,
Some(Value::String(a)) if a == "horizontal" => horizontal,
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
// y is down, so the page's counter-clockwise angle turns the other way on screen.
let r = -n.as_f64().unwrap_or(0.0).to_radians();
Affine::rotate(r) * horizontal * Affine::rotate(-r)
}
Some(v) => {
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
}
};
apply_transform(s, "Shear", ids, about(o, m), p, true)
}
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
const SHEAR_AXIS_MAX: f64 = 359.0;
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
check_switches(p, &["interpolate"], "object.transformAgain")?;
if let Some(again) = s.doc()?.last_perspective.clone() {
return crate::cmd::distortcmds::transform_again(s, &again);
}
+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) };
Loaded 100 of 469 files, more files were not shown because too many files have changed in this diff. Show more