mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 11:23:43 +01:00
Merge main into feat/transform-rectangle-corner-type
This commit is contained in:
commit
d49bd90818
488 files changed
+64894
-2946
No files matched your search
Generated
+16
@@ -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",
|
||||
|
||||
@@ -154,8 +154,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -459,6 +459,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
open_file: Some(Box::new(open_file)),
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
@@ -507,15 +509,32 @@ fn open_in_photocraft(path: &str) -> Result<bool, String> {
|
||||
explorer_safe(path)?;
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
|
||||
let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) };
|
||||
launch_application(&app, path)
|
||||
}
|
||||
|
||||
/// A missing chosen editor falls back; invalid applications and failed launches remain errors.
|
||||
fn open_in_application(app: &str, path: &str) -> Result<bool, String> {
|
||||
explorer_safe(path)?;
|
||||
let app = std::path::Path::new(app);
|
||||
match std::fs::metadata(app) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", app.display())),
|
||||
Ok(_) => {}
|
||||
}
|
||||
check_app(app)?;
|
||||
launch_application(app, path)
|
||||
}
|
||||
|
||||
fn launch_application(app: &std::path::Path, path: &str) -> Result<bool, String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new("open");
|
||||
c.arg("-a").arg(&app).arg(path);
|
||||
c.arg("-a").arg(app).arg(path);
|
||||
c
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new(&app);
|
||||
let mut c = std::process::Command::new(app);
|
||||
c.arg(path);
|
||||
c
|
||||
};
|
||||
@@ -688,6 +707,17 @@ mod open_with_tests {
|
||||
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chosen_editor_only_falls_back_when_missing() {
|
||||
let dir = scratch("chosen");
|
||||
let missing = dir.path().join("Missing.exe");
|
||||
assert!(!super::open_in_application(&missing.to_string_lossy(), "image with spaces.png").unwrap());
|
||||
let doc = dir.path().join("notes.txt");
|
||||
std::fs::write(&doc, "not an application").unwrap();
|
||||
assert!(super::open_in_application(&doc.to_string_lossy(), "image.png").is_err());
|
||||
assert!(super::open_in_application(&dir.path().to_string_lossy(), "image.png").is_err());
|
||||
}
|
||||
|
||||
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
|
||||
/// path.
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush
|
||||
//! pen's finger wheel. winit 0.30
|
||||
//! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit
|
||||
//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads, as on X11 ([`crate::tablet`]).
|
||||
@@ -14,8 +15,9 @@
|
||||
//! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the
|
||||
//! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read
|
||||
//! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation
|
||||
//! from one held upright and unturned. Each reads as none until the pen reports a value other
|
||||
//! than 0 after it comes near ([`Pen`]).
|
||||
//! from one held upright and unturned. Its `tangentialPressure` (−1..1, an airbrush pen's finger
|
||||
//! wheel) goes into the pose as the wheel, 0 for a pen without one as well. Each reads as none
|
||||
//! until the pen reports a value other than 0 after it comes near ([`Pen`]).
|
||||
//! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move.
|
||||
//! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says
|
||||
@@ -68,6 +70,8 @@ struct RawEvent {
|
||||
tilt: (f64, f64),
|
||||
/// `rotation`, in degrees (the same events as `pressure`).
|
||||
rotation: f32,
|
||||
/// `tangentialPressure`, −1..1 (the same events as `pressure`).
|
||||
tangential: f32,
|
||||
/// `pointingDeviceType` (proximity events only).
|
||||
device: usize,
|
||||
/// `isEnteringProximity` (proximity events only).
|
||||
@@ -107,18 +111,42 @@ impl RawEvent {
|
||||
/// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the
|
||||
/// angle is negated and brought into 0..360.
|
||||
///
|
||||
/// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]).
|
||||
fn pose(&self, tilts: bool, turns: bool) -> PenPose {
|
||||
/// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the
|
||||
/// devices that have one (<https://developer.apple.com/documentation/appkit/nsevent/tangentialpressure>).
|
||||
/// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is
|
||||
/// clamped.
|
||||
///
|
||||
/// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel
|
||||
/// unless `read.wheels` ([`Pen`]).
|
||||
fn pose(&self, read: Reads) -> PenPose {
|
||||
let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32;
|
||||
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
|
||||
let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation }
|
||||
let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0);
|
||||
PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel }
|
||||
}
|
||||
|
||||
/// Whether the event reports a tilt other than 0, and a rotation other than 0.
|
||||
fn reads(&self) -> (bool, bool) {
|
||||
/// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential
|
||||
/// pressure other than 0.
|
||||
fn reads(&self) -> Reads {
|
||||
let read = |v: f64| v.is_finite() && v != 0.0;
|
||||
(read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation)))
|
||||
Reads { tilts: read(self.tilt.0) || read(self.tilt.1), turns: read(f64::from(self.rotation)), wheels: read(f64::from(self.tangential)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a pen's tilt, rotation and finger wheel it has reported.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Reads {
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
wheels: bool,
|
||||
}
|
||||
|
||||
impl Reads {
|
||||
fn add(&mut self, other: Reads) {
|
||||
self.tilts |= other.tilts;
|
||||
self.turns |= other.turns;
|
||||
self.wheels |= other.wheels;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,14 +176,14 @@ impl Update {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other
|
||||
/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives
|
||||
/// 0 for a pen without one and for one held upright or unturned.
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt, a rotation or a
|
||||
/// tangential pressure other than 0 since it came near: until it has, that value reads as none,
|
||||
/// since AppKit gives 0 for a pen without one and for one held upright, unturned or with its
|
||||
/// wheel half way.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Pen {
|
||||
eraser: bool,
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
read: Reads,
|
||||
}
|
||||
|
||||
impl Pen {
|
||||
@@ -163,16 +191,14 @@ impl Pen {
|
||||
if e.proximity() {
|
||||
// Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse.
|
||||
self.eraser = e.entering && e.device == device::ERASER;
|
||||
(self.tilts, self.turns) = (false, false);
|
||||
self.read = Reads::default();
|
||||
let pen = e.entering && e.device != device::CURSOR;
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() }));
|
||||
}
|
||||
if e.point() {
|
||||
let (tilts, turns) = e.reads();
|
||||
self.tilts |= tilts;
|
||||
self.turns |= turns;
|
||||
self.read.add(e.reads());
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) };
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) };
|
||||
match (e.point(), e.mouse()) {
|
||||
(true, true) => Update::Move(sample),
|
||||
(true, false) => Update::Set(Some(sample)),
|
||||
@@ -246,6 +272,7 @@ mod monitor {
|
||||
let tilt = e.tilt();
|
||||
raw.tilt = (tilt.x, tilt.y);
|
||||
raw.rotation = e.rotation();
|
||||
raw.tangential = e.tangentialPressure();
|
||||
}
|
||||
if raw.proximity() {
|
||||
raw.device = e.pointingDeviceType().0;
|
||||
@@ -326,26 +353,44 @@ mod tests {
|
||||
let sample = |pressure, pose| PenSample { pressure, eraser: false, pose };
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet");
|
||||
let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None };
|
||||
assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose)));
|
||||
let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None };
|
||||
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped");
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") };
|
||||
assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned");
|
||||
assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}");
|
||||
let feed = StylusFeed::default();
|
||||
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed);
|
||||
assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out");
|
||||
assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out");
|
||||
p.handle(&proximity(1, true));
|
||||
let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() };
|
||||
assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near");
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.pose(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
/// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as
|
||||
/// 0..1, once the pen has reported a value other than 0 since it came near.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
let mut p = Pen::default();
|
||||
let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) {
|
||||
Update::Move(s) => s.pose.wheel,
|
||||
u => panic!("a pen's drag is a move: {u:?}"),
|
||||
};
|
||||
assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet");
|
||||
assert_eq!(wheel(&mut p, -1.0), Some(0.0));
|
||||
assert_eq!(wheel(&mut p, 0.5), Some(0.75));
|
||||
assert_eq!(wheel(&mut p, 0.0), Some(0.5), "once reported, 0 is half way");
|
||||
assert_eq!(wheel(&mut p, 3.0), Some(1.0), "clamped");
|
||||
p.handle(&proximity(1, true));
|
||||
assert_eq!(wheel(&mut p, 0.0), None, "not reported since the pen came near");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_feed_gets_each_moves_pressure_within_0_to_1() {
|
||||
let feed = StylusFeed::default();
|
||||
|
||||
@@ -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() };
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included
|
||||
//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under
|
||||
//! X11, XWayland included
|
||||
//! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app
|
||||
//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`]
|
||||
//! (`Services::stylus`), which the canvas reads.
|
||||
@@ -14,11 +15,17 @@
|
||||
//! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range
|
||||
//! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`];
|
||||
//! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the
|
||||
//! range at 0°.
|
||||
//! range at 0°;
|
||||
//! - "Abs Wheel" (the finger wheel of an airbrush pen), scaled from the valuator's range to 0..1.
|
||||
//! XWayland also sends an Art Pen's barrel rotation on this valuator
|
||||
//! (<https://github.com/mirror/xserver/blob/master/hw/xwayland/xwayland-input.c>), so under
|
||||
//! XWayland it reads as the wheel. A tablet pad's wheel is on a device without a pressure axis,
|
||||
//! which is not read.
|
||||
//!
|
||||
//! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators
|
||||
//! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing.
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. The
|
||||
//! wheel reads nothing until an event carries it.
|
||||
//!
|
||||
//! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains
|
||||
//! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's
|
||||
@@ -60,6 +67,7 @@ enum AxisKind {
|
||||
TiltX,
|
||||
TiltY,
|
||||
Rotation,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
@@ -70,6 +78,7 @@ impl AxisKind {
|
||||
"Abs Tilt X" => Some(Self::TiltX),
|
||||
"Abs Tilt Y" => Some(Self::TiltY),
|
||||
"Abs Rotary Z" => Some(Self::Rotation),
|
||||
"Abs Wheel" => Some(Self::Wheel),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -81,6 +90,7 @@ impl AxisKind {
|
||||
Self::TiltX => 1,
|
||||
Self::TiltY => 2,
|
||||
Self::Rotation => 3,
|
||||
Self::Wheel => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,18 +105,22 @@ struct Axis {
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a
|
||||
/// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number
|
||||
/// is a mouse's pressure, 1, or a tilt or rotation of 0.
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90), a rotation
|
||||
/// in degrees (−180..180, the middle of the range at 0) or a wheel of 0..1. A value that is not
|
||||
/// a number is a mouse's pressure, 1, a tilt or rotation of 0, or a wheel half way.
|
||||
fn map(&self, v: f64) -> f32 {
|
||||
if !v.is_finite() {
|
||||
return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 };
|
||||
return match self.kind {
|
||||
AxisKind::Pressure => 1.0,
|
||||
AxisKind::Wheel => 0.5,
|
||||
_ => 0.0,
|
||||
};
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v };
|
||||
let unit = unit.clamp(0.0, 1.0);
|
||||
match self.kind {
|
||||
AxisKind::Pressure => unit as f32,
|
||||
AxisKind::Pressure | AxisKind::Wheel => unit as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32,
|
||||
AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32,
|
||||
@@ -173,7 +187,7 @@ enum Update {
|
||||
#[derive(Debug, Default)]
|
||||
struct Pens {
|
||||
devices: HashMap<u16, Device>,
|
||||
last: HashMap<u16, [Option<f32>; 4]>,
|
||||
last: HashMap<u16, [Option<f32>; 5]>,
|
||||
}
|
||||
|
||||
impl Pens {
|
||||
@@ -200,10 +214,12 @@ impl Pens {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing.
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The
|
||||
// wheel reads nothing until an event carries it: XWayland lists the axis for every pen.
|
||||
let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0));
|
||||
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]);
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) };
|
||||
let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten());
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel };
|
||||
Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose }))
|
||||
}
|
||||
|
||||
@@ -430,7 +446,7 @@ mod tests {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose })));
|
||||
assert_eq!(feed.eraser(), Some(false));
|
||||
@@ -479,10 +495,36 @@ mod tests {
|
||||
// A pen whose tilt and rotation no event has carried yet is upright and unturned.
|
||||
let mut fresh = Pens::default();
|
||||
fresh.set_devices([pen(9)]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an
|
||||
/// event carries it; a pen that lists it but has not moved it reads no wheel, and a device
|
||||
/// without a pressure axis (a tablet pad's wheel) is not a pen.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
let mut valuators = pen_valuators();
|
||||
valuators.push((6, "Abs Wheel".to_string(), 0.0, 1023.0));
|
||||
let airbrush = Device::new(9, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), valuators);
|
||||
let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]);
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([airbrush, pad, pen(10)]);
|
||||
let feed = StylusFeed::default();
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet");
|
||||
pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25));
|
||||
pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range");
|
||||
pens.raw_event(&feed, 9, &[0b100], &[100.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move");
|
||||
pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]);
|
||||
assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen");
|
||||
pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]);
|
||||
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator");
|
||||
}
|
||||
|
||||
/// A device listed again unchanged keeps its last tilt and rotation; another device listed
|
||||
/// under the same id starts upright and unturned.
|
||||
#[test]
|
||||
@@ -495,7 +537,7 @@ mod tests {
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators());
|
||||
pens.set_devices([other]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
|
||||
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
|
||||
@@ -133,12 +133,13 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po
|
||||
|
||||
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
|
||||
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no
|
||||
/// field for an airbrush pen's finger wheel, so the pose has none.
|
||||
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
|
||||
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
|
||||
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
|
||||
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
|
||||
PenPose { tilt, rotation }.sanitized()
|
||||
PenPose { tilt, rotation, wheel: None }.sanitized()
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
@@ -426,12 +427,12 @@ mod tests {
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None });
|
||||
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel");
|
||||
let wild = pen_pose(all, 400, i32::MIN, 720);
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
|
||||
}
|
||||
|
||||
+34
-12
@@ -160,7 +160,7 @@ impl Calligraphic {
|
||||
pub fn uses_pressure(&self) -> bool {
|
||||
self.modes().contains(&Variation::Pressure)
|
||||
}
|
||||
/// Does the pen (its pressure, tilt, bearing or rotation) change the nib?
|
||||
/// Does the pen (its pressure, tilt, bearing, rotation or wheel) change the nib?
|
||||
pub fn uses_pen(&self) -> bool {
|
||||
self.modes().iter().any(|m| m.follows_pen())
|
||||
}
|
||||
@@ -202,11 +202,25 @@ pub enum Variation {
|
||||
/// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise
|
||||
/// from where the pen reports 0° round to ±180°.
|
||||
Rotation,
|
||||
/// From the value less the variation with an airbrush pen's finger wheel at one end of its
|
||||
/// travel to the value plus the variation at the other (the value itself half way).
|
||||
StylusWheel,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
pub const ALL: [Variation; 6] =
|
||||
pub const ALL: [Variation; 7] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel];
|
||||
/// The modes Brush Options offers for a value other than a size (a Calligraphic brush's Angle
|
||||
/// and Roundness, a Scatter brush's Spacing, Scatter and Rotation): all but
|
||||
/// [`Variation::StylusWheel`], which drives a Calligraphic or Scatter brush's Size and an Art
|
||||
/// brush's Width.
|
||||
pub const OTHER: [Variation; 6] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation];
|
||||
/// The modes Brush Options offers for a size (`true`: [`Self::ALL`]) or another value
|
||||
/// ([`Self::OTHER`]).
|
||||
pub fn offered(size: bool) -> &'static [Variation] {
|
||||
if size { &Self::ALL } else { &Self::OTHER }
|
||||
}
|
||||
/// The name brush definitions use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
@@ -216,6 +230,7 @@ impl Variation {
|
||||
Variation::Tilt => "tilt",
|
||||
Variation::Bearing => "bearing",
|
||||
Variation::Rotation => "rotation",
|
||||
Variation::StylusWheel => "stylusWheel",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -226,15 +241,16 @@ impl Variation {
|
||||
Variation::Tilt => "Tilt",
|
||||
Variation::Bearing => "Bearing",
|
||||
Variation::Rotation => "Rotation",
|
||||
Variation::StylusWheel => "Stylus Wheel",
|
||||
}
|
||||
}
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|v| v.id() == id)
|
||||
}
|
||||
/// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing,
|
||||
/// Rotation)?
|
||||
/// Rotation, Stylus Wheel)?
|
||||
pub fn follows_pen(self) -> bool {
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation)
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,12 +267,14 @@ pub(crate) struct PenAt {
|
||||
bearing: f64,
|
||||
/// ½ plus the counter-clockwise barrel rotation over 360°.
|
||||
rotation: f64,
|
||||
/// Where the airbrush finger wheel was set, 0 at one end of its travel to 1 at the other.
|
||||
wheel: f64,
|
||||
}
|
||||
|
||||
impl PenAt {
|
||||
/// Every input at `c`.
|
||||
pub(crate) fn uniform(c: f64) -> Self {
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c }
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c, wheel: c }
|
||||
}
|
||||
/// What `stroke` recorded at `f` (the fraction of its path's length).
|
||||
pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self {
|
||||
@@ -267,6 +285,7 @@ impl PenAt {
|
||||
tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)),
|
||||
bearing: turn(stroke.bearing.as_ref()),
|
||||
rotation: turn(stroke.rotation.as_ref()),
|
||||
wheel: stroke.wheel.as_ref().map_or(mid, |p| p.at(f)),
|
||||
}
|
||||
}
|
||||
/// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen.
|
||||
@@ -277,6 +296,7 @@ impl PenAt {
|
||||
Variation::Tilt => self.tilt,
|
||||
Variation::Bearing => self.bearing,
|
||||
Variation::Rotation => self.rotation,
|
||||
Variation::StylusWheel => self.wheel,
|
||||
};
|
||||
Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
|
||||
}
|
||||
@@ -307,9 +327,10 @@ pub struct Scatter {
|
||||
/// 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,
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None`
|
||||
/// (brushes saved before there were modes): Random where the two differ, else Fixed (see
|
||||
/// [`Scatter::modes`]).
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°), and Stylus
|
||||
/// Wheel (the size's only) the first at one end of an airbrush pen's finger wheel and the
|
||||
/// second at the other. `None` (brushes saved before there were modes): Random where the two
|
||||
/// differ, else Fixed (see [`Scatter::modes`]).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub modes: Option<[Variation; 4]>,
|
||||
}
|
||||
@@ -384,11 +405,12 @@ pub struct ArtBrush {
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the
|
||||
/// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure
|
||||
/// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing
|
||||
/// and Rotation from −180° to 180° (half way at 0°).
|
||||
/// and Rotation from −180° to 180° (half way at 0°), Stylus Wheel from one end of an airbrush
|
||||
/// pen's finger wheel to the other.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
|
||||
/// at 180° (`width` without one).
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, at
|
||||
/// 180° or at the wheel's far end (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
@@ -732,7 +754,7 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
|
||||
// The width follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
|
||||
if !a.width_mode.is_some_and(Variation::follows_pen) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
|
||||
@@ -1545,6 +1545,64 @@ fn pressure_varies_angle_and_roundness() {
|
||||
assert!(near(h, expected, 0.05), "{h} vs {expected}");
|
||||
}
|
||||
|
||||
/// A stroke that recorded an airbrush pen's finger wheel going from `from` to `to` along it.
|
||||
fn wheeled(from: f64, to: f64) -> StrokeLayer {
|
||||
StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, from), (1.0, to)] }), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
/// Stylus Wheel: a Calligraphic brush's size goes from size − variation at one end of the finger
|
||||
/// wheel to size + variation at the other, a Scatter brush's size from its first value to its
|
||||
/// second, and an Art brush's width from Width to the second width. Each reads only the wheel: the
|
||||
/// pressure, tilt, bearing or rotation recorded instead leaves the value half way.
|
||||
#[test]
|
||||
fn the_stylus_wheel_varies_sizes_and_widths() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let c = Calligraphic {
|
||||
size: 6.0,
|
||||
variation: [0.0, 0.0, 4.0],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]),
|
||||
..Default::default()
|
||||
};
|
||||
let nib = Brush { name: "w".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let out = stroke_pieces(&doc, &nib, &bp, &wheeled(0.0, 1.0));
|
||||
// Round nib: 2 pt across at the start, 10 pt at the end, 6 pt half way.
|
||||
assert!(near(half_width(&out, 0.5, 1.5), 1.0, 0.1), "{}", half_width(&out, 0.5, 1.5));
|
||||
assert!(near(half_width(&out, 98.5, 99.5), 5.0, 0.1), "{}", half_width(&out, 98.5, 99.5));
|
||||
assert!(near(half_width(&out, 49.5, 50.5), 3.0, 0.1), "{}", half_width(&out, 49.5, 50.5));
|
||||
let others = [
|
||||
pressed(vec![(0.0, 0.0), (1.0, 1.0)]),
|
||||
StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) },
|
||||
posed(None, Some(90.0), Some(-90.0)),
|
||||
];
|
||||
for st in &others {
|
||||
let h = bounds(&stroke_pieces(&doc, &nib, &bp, st)).height();
|
||||
assert!(near(h, 6.0, 0.05), "{st:?}: {h}");
|
||||
}
|
||||
// Scatter size 50 % to 300 % of 4 pt art: 2 pt at one end of the wheel, 12 pt at the other.
|
||||
let spray = sized_scatter(50.0, 300.0, Variation::StylusWheel);
|
||||
let h: Vec<f64> =
|
||||
stroke_pieces(&doc, &spray, &line(0.0, 0.0, 400.0, 0.0), &wheeled(1.0, 0.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect();
|
||||
assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}");
|
||||
// Art width 50 % to 300 % of 4 pt art.
|
||||
let mut ribbon = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut ribbon.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::StylusWheel), Some(300.0));
|
||||
}
|
||||
let out = stroke_pieces(&doc, &ribbon, &bp, &wheeled(1.0, 0.0));
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
|
||||
for st in &others {
|
||||
let h = bounds(&stroke_pieces(&doc, &ribbon, &bp, st)).height();
|
||||
assert!(near(h, 7.0, 1e-6), "{st:?}: {h}");
|
||||
}
|
||||
// A definition keeps the mode by name.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "stylusWheel", "width_max": 300.0},
|
||||
]));
|
||||
assert!(matches!(&lib[0].kind, BrushKind::Art(a) if a.width_mode == Some(Variation::StylusWheel)));
|
||||
}
|
||||
|
||||
/// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel
|
||||
/// rotation (degrees counter-clockwise), each the same all along it where given.
|
||||
fn posed(tilt: Option<f64>, bearing: Option<f64>, rotation: Option<f64>) -> StrokeLayer {
|
||||
@@ -1611,7 +1669,7 @@ fn bearing_and_rotation_turn_the_nib() {
|
||||
#[test]
|
||||
fn pen_modes_without_a_recording_draw_the_value_itself() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] {
|
||||
let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) };
|
||||
let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height();
|
||||
@@ -1658,7 +1716,7 @@ fn a_mouse_stroke_draws_pen_modes_as_pressure_did() {
|
||||
};
|
||||
let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure));
|
||||
assert!(!calli_before.is_empty() && !scatter_before.is_empty());
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] {
|
||||
assert_eq!(calli(mode), calli_before, "{mode:?}");
|
||||
assert_eq!(scattered(mode), scatter_before, "{mode:?}");
|
||||
}
|
||||
@@ -1726,8 +1784,12 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)]))
|
||||
);
|
||||
// Modes are saved by name.
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"]));
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v)));
|
||||
assert_eq!(
|
||||
serde_json::to_value(Variation::ALL).unwrap(),
|
||||
serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"])
|
||||
);
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id()));
|
||||
assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel));
|
||||
}
|
||||
|
||||
/// Junk definitions and pressure never panic and never draw non-finite art.
|
||||
|
||||
@@ -198,14 +198,24 @@ pub fn export(doc: &Document, opts: &HpglOptions) -> Result<HpglOutput, String>
|
||||
Ok(export_regions(doc, opts, &[opts.region])?.pop().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// An error unless a plot can cover `region`: its corners are finite and it has a width and a
|
||||
/// height (either corner may come first).
|
||||
pub fn check_region(region: Rect) -> Result<(), String> {
|
||||
let r = region.abs();
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err("the export region is empty".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the visible art of `doc` over each of `regions` as an HP-GL plot, one per region, as
|
||||
/// [`export`] does with `opts.region`. The plots share one pen numbering, so a color is the same
|
||||
/// pen in each, and one point budget.
|
||||
pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> Result<Vec<HpglOutput>, String> {
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) {
|
||||
return Err("the export region is empty".into());
|
||||
for r in regions {
|
||||
check_region(*r)?;
|
||||
}
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if !TOLERANCE_RANGE.contains(&opts.tolerance) {
|
||||
return Err("the curve tolerance must be from 0.01 to 10 points".into());
|
||||
}
|
||||
|
||||
+25
-5
@@ -185,6 +185,15 @@ pub struct ColorSettings {
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
/// Profile Mismatches: Ask When Opening. Off by default, as in settings saved without it.
|
||||
#[serde(default)]
|
||||
pub ask_mismatch_open: bool,
|
||||
/// Profile Mismatches: Ask When Pasting.
|
||||
#[serde(default)]
|
||||
pub ask_mismatch_paste: bool,
|
||||
/// Missing Profiles: Ask When Opening.
|
||||
#[serde(default)]
|
||||
pub ask_missing_open: bool,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
@@ -196,6 +205,9 @@ impl Default for ColorSettings {
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
ask_mismatch_open: false,
|
||||
ask_mismatch_paste: false,
|
||||
ask_missing_open: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -589,10 +601,11 @@ impl Cms {
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
/// Working Space). RGB converts directly from profile to profile, with this context's
|
||||
/// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB
|
||||
/// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it
|
||||
/// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey
|
||||
/// and Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
@@ -612,9 +625,16 @@ impl Cms {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
// Absolute colorimetry starts from the inks' absolute Lab, paper color included and
|
||||
// without black-point compensation; the other intents from the Lab they display as.
|
||||
let source_lab = || match (&self.cmyk, intent) {
|
||||
(CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks),
|
||||
(_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)),
|
||||
_ => self.cmyk_display_lab(inks),
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
_ => dest.lab_to_cmyk(source_lab(), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
|
||||
@@ -459,6 +459,23 @@ fn policies_parse_and_default_in_saved_settings() {
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// The three Ask boxes are off by default and in settings saved before they existed, and save
|
||||
/// under their own keys.
|
||||
#[test]
|
||||
fn ask_boxes_default_off_and_save() {
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert!(!old.ask_mismatch_open && !old.ask_mismatch_paste && !old.ask_missing_open);
|
||||
let st = ColorSettings::default();
|
||||
assert!(!st.ask_mismatch_open && !st.ask_mismatch_paste && !st.ask_missing_open);
|
||||
let saved = serde_json::to_value(ColorSettings { ask_mismatch_paste: true, ..Default::default() }).unwrap();
|
||||
assert_eq!(saved["askMismatchOpen"], false);
|
||||
assert_eq!(saved["askMismatchPaste"], true);
|
||||
assert_eq!(saved["askMissingOpen"], false);
|
||||
let back: ColorSettings = serde_json::from_value(saved).unwrap();
|
||||
assert!(back.ask_mismatch_paste);
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
@@ -478,3 +495,48 @@ fn convert_into_keeps_the_appearance() {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
|
||||
/// With black-point compensation on, Generic CMYK displays its press black as black, so dark inks
|
||||
/// converted out of it keep that appearance: into Device CMYK, and into another document whose
|
||||
/// CMYK space is also Generic CMYK.
|
||||
#[test]
|
||||
fn convert_into_keeps_compensated_dark_inks() {
|
||||
let generic = cms();
|
||||
let device = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
|
||||
for ink in [
|
||||
Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 },
|
||||
Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 },
|
||||
Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 },
|
||||
] {
|
||||
for dest in [&device, &other_generic] {
|
||||
let moved = generic.convert_into(dest, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }), "{ink:?} → {moved:?}");
|
||||
let d = delta_e2000(generic.lab(&ink), dest.lab(&moved));
|
||||
assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color
|
||||
/// included, no black-point compensation): into another document whose CMYK space is also Generic
|
||||
/// CMYK, the paper, dark inks and mid tones keep their absolute appearance.
|
||||
#[test]
|
||||
fn absolute_cmyk_conversion_keeps_the_absolute_appearance() {
|
||||
let generic = cms();
|
||||
let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
|
||||
let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) {
|
||||
(CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]),
|
||||
_ => panic!("Generic CMYK inks expected, not {ink:?}"),
|
||||
};
|
||||
for ink in [
|
||||
Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 },
|
||||
Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 },
|
||||
Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 },
|
||||
Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 },
|
||||
] {
|
||||
let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric);
|
||||
let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved));
|
||||
assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}");
|
||||
}
|
||||
}
|
||||
@@ -176,18 +176,33 @@ impl Harmony {
|
||||
|
||||
/// The rule's colours in the base colour's model, the base colour itself first.
|
||||
pub fn apply(self, base: Color) -> Vec<Color> {
|
||||
let [h, s, v] = base.to_hsb();
|
||||
std::iter::once(base)
|
||||
.chain(self.tones()[1..].iter().map(|tone| {
|
||||
let rest = self.apply_hsb(base.to_hsb()).into_iter().skip(1);
|
||||
std::iter::once(base).chain(rest.map(|[h, s, v]| keep_model(base, Color::from_hsb(h, s, v)))).collect()
|
||||
}
|
||||
|
||||
/// The rule's colours as HSB from base HSB `hsb`, the base first: hue in degrees from 0 to 360,
|
||||
/// saturation and brightness from 0 to 1. A gray base keeps its hue, so the colours keep their
|
||||
/// places around a hue wheel.
|
||||
pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> {
|
||||
self.tones()
|
||||
.iter()
|
||||
.map(|tone| {
|
||||
let b = match tone.bright {
|
||||
Bright::Times(f) => v * f,
|
||||
Bright::Contrast => contrast(v),
|
||||
};
|
||||
keep_model(base, Color::from_hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)))
|
||||
}))
|
||||
[(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or
|
||||
/// Monochromatic), so that each can sit on a hue ring apart from the others.
|
||||
pub fn hues_differ(self) -> bool {
|
||||
let turns: Vec<f32> = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect();
|
||||
turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b))
|
||||
}
|
||||
|
||||
/// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or
|
||||
/// darker variations of it that fill the remaining places (the rule's first colours get them
|
||||
/// first). The base colour comes first, every colour in its model.
|
||||
@@ -409,6 +424,34 @@ mod tests {
|
||||
assert_eq!(Harmony::parse("square"), None);
|
||||
}
|
||||
|
||||
/// A rule's HSB colours match the colours `apply` gives, and a gray base keeps its hue, so its
|
||||
/// colours turn around the hue ring from it.
|
||||
#[test]
|
||||
fn hsb_colours_match_and_keep_a_grays_hue() {
|
||||
for h in Harmony::ALL {
|
||||
let base = Color::rgb8(230, 120, 40);
|
||||
let hsb = h.apply_hsb(base.to_hsb());
|
||||
let colors = h.apply(base);
|
||||
assert_eq!(hsb.len(), colors.len(), "{}", h.label());
|
||||
for (a, c) in hsb.iter().zip(&colors).skip(1) {
|
||||
assert_eq!(Color::from_hsb(a[0], a[1], a[2]).to_hex(), c.to_hex(), "{}", h.label());
|
||||
}
|
||||
}
|
||||
let gray = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]);
|
||||
assert_eq!(gray.iter().map(|c| c[0]).collect::<Vec<_>>(), [40.0, 160.0, 280.0]);
|
||||
assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360");
|
||||
}
|
||||
|
||||
/// Fifteen rules give every colour its own hue; the six that repeat a hue are left out.
|
||||
#[test]
|
||||
fn rules_whose_colours_all_have_their_own_hue() {
|
||||
let differ: Vec<Harmony> = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect();
|
||||
assert_eq!(differ.len(), 15);
|
||||
for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] {
|
||||
assert!(!h.hues_differ(), "{}", h.label());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_contrast_flips_brightness() {
|
||||
let light = Harmony::HighContrast.apply(Color::rgb(0.9, 0.8, 0.2));
|
||||
|
||||
@@ -127,8 +127,8 @@ impl Appearance {
|
||||
pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> {
|
||||
self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None })
|
||||
}
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes
|
||||
/// were drawn with stay with them.
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing, rotation and wheel its
|
||||
/// strokes were drawn with stay with them.
|
||||
pub fn without_pressure(mut self) -> Self {
|
||||
for it in &mut self.items {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
@@ -136,6 +136,7 @@ impl Appearance {
|
||||
s.tilt = None;
|
||||
s.bearing = None;
|
||||
s.rotation = None;
|
||||
s.wheel = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
|
||||
@@ -113,6 +113,11 @@ pub struct StrokeLayer {
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rotation: Option<AngleProfile>,
|
||||
/// Where the finger wheel of an airbrush pen was set along the stroke: 0 at one end of its
|
||||
/// travel to 1 at the other. Brushes with Stylus Wheel variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub wheel: Option<PressureProfile>,
|
||||
}
|
||||
|
||||
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
|
||||
@@ -187,6 +192,7 @@ impl StrokeLayer {
|
||||
tilt: None,
|
||||
bearing: None,
|
||||
rotation: None,
|
||||
wheel: None,
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
|
||||
@@ -130,8 +130,9 @@ impl WidthProfile {
|
||||
|
||||
/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1
|
||||
/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s
|
||||
/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter
|
||||
/// brushes with Pressure or Tilt variation read them; everything else ignores them.
|
||||
/// are. The pen's tilt and an airbrush pen's finger wheel are kept the same way
|
||||
/// ([`StrokeLayer::tilt`], [`StrokeLayer::wheel`]). Brushes with Pressure, Tilt or Stylus Wheel
|
||||
/// variation read them; everything else ignores them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PressureProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
|
||||
@@ -188,7 +188,7 @@ fn angle_profiles_join_samples_the_shorter_way_round() {
|
||||
#[test]
|
||||
fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap();
|
||||
for key in ["pressure", "tilt", "bearing", "rotation"] {
|
||||
for key in ["pressure", "tilt", "bearing", "rotation", "wheel"] {
|
||||
assert!(json.get(key).is_none(), "{key}");
|
||||
}
|
||||
let st: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
@@ -199,19 +199,21 @@ fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample());
|
||||
assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None);
|
||||
// The pen's tilt, bearing and rotation load, save and stay behind the same way.
|
||||
// The pen's tilt, bearing, rotation and wheel load, save and stay behind the same way.
|
||||
let posed = StrokeLayer {
|
||||
tilt: Some(PressureProfile::sample()),
|
||||
bearing: Some(AngleProfile::sample()),
|
||||
rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }),
|
||||
wheel: Some(PressureProfile { points: vec![(0.0, 0.25), (1.0, 0.75)] }),
|
||||
..back
|
||||
};
|
||||
assert_eq!(serde_json::to_value(&posed).unwrap()["wheel"], serde_json::json!({"points": [[0.0, 0.25], [1.0, 0.75]]}));
|
||||
let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap();
|
||||
assert_eq!(again, posed);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
*ap.stroke_mut().unwrap() = posed;
|
||||
let st = ap.without_pressure().stroke().cloned().unwrap();
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None));
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation, st.wheel), (None, None, None, None, None));
|
||||
}
|
||||
|
||||
/// The Lens profile's widths at its middle, a quarter of the way along and past its end.
|
||||
|
||||
+52
-9
@@ -6,7 +6,7 @@
|
||||
//! tool clicked.
|
||||
//! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ),
|
||||
//! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt,
|
||||
//! bearing and rotation that brushes read interpolate; what can't
|
||||
//! bearing, rotation and wheel that brushes read interpolate; what can't
|
||||
//! (caps, joins, brushes, fonts, symbols, text content) switches halfway.
|
||||
//! - **Groups** pair their children in stacking order; the children one group has more of grow
|
||||
//! out of the other group's centre. Compound paths stay compound paths.
|
||||
@@ -429,8 +429,8 @@ fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Opt
|
||||
}
|
||||
|
||||
/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width
|
||||
/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of
|
||||
/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway).
|
||||
/// profile and the pen pressure, tilt, bearing, rotation and wheel its brush reads into `o` (a
|
||||
/// copy of the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway).
|
||||
fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
|
||||
let tf = t as f32;
|
||||
o.paint = lerp_paint(&x.paint, &y.paint, tf);
|
||||
@@ -444,6 +444,7 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
|
||||
o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t);
|
||||
o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t);
|
||||
o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t);
|
||||
o.wheel = lerp_pressure(x.wheel.as_ref(), y.wheel.as_ref(), t);
|
||||
}
|
||||
|
||||
/// Interpolate appearance stacks: item by item when their structure matches, else the top fill
|
||||
@@ -755,9 +756,9 @@ fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
|
||||
}
|
||||
|
||||
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
|
||||
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
|
||||
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
|
||||
/// they are.
|
||||
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing, rotation and wheel, its
|
||||
/// dashes, a gradient along the path or across it (whose sides swap when reversed). Its arrowheads
|
||||
/// stay as they are.
|
||||
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
@@ -805,7 +806,7 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
|
||||
let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l));
|
||||
p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect();
|
||||
}
|
||||
for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() {
|
||||
for p in [&mut s.pressure, &mut s.tilt, &mut s.wheel].into_iter().flatten() {
|
||||
let out = reoriented(&p.points, o, |f| p.at(f), same, same);
|
||||
p.points = out;
|
||||
}
|
||||
@@ -842,8 +843,8 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing,
|
||||
/// rotation and wheel then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
@@ -3014,6 +3015,48 @@ mod tests {
|
||||
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stylus_wheel_recording_turns_with_the_gradient_and_dashes_of_its_stroke() {
|
||||
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
|
||||
let mut ap = Appearance::default();
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
edit(s);
|
||||
}
|
||||
Node::path(NodeId(1), path, ap)
|
||||
};
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
|
||||
let wheel = |s: &StrokeLayer, f: f64| s.wheel.as_ref().map_or(PressureProfile::MID, |p| p.at(f));
|
||||
let light = |s: &StrokeLayer, u: f32| match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::<f32>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
let recorded = |s: &mut StrokeLayer| {
|
||||
s.wheel = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false });
|
||||
};
|
||||
// An open key clicked at its last anchor: the wheel runs the other way with the gradient
|
||||
// along it, and the dashes are read from its end.
|
||||
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false));
|
||||
let key = keyed(line(100.0), &recorded);
|
||||
let s = stroke(&Lerp::new(&keyed(line(0.0), &|_| {}), &key, (None, Some(1))).at(1.0));
|
||||
assert!((wheel(&s, 0.0) - 1.0).abs() < 1e-9 && wheel(&s, 1.0).abs() < 1e-9, "{:?}", s.wheel);
|
||||
assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{:?}", s.paint);
|
||||
assert_ne!(s.dash, stroke(&key).dash, "the dashes turn too");
|
||||
// A closed key started half way round starts its wheel recording there, stepping where its
|
||||
// own start was, as its gradient does.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
let key = keyed(square(100.0), &recorded);
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0));
|
||||
assert!((wheel(&s, 0.25) - 0.75).abs() < 1e-9 && (wheel(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.wheel);
|
||||
assert!((light(&s, 0.25) - 0.75).abs() < 0.02 && (light(&s, 0.75) - 2.25).abs() < 0.02, "{:?}", s.paint);
|
||||
// Half way through, a key without a recording counts as the wheel half way.
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(0.5));
|
||||
assert!((wheel(&s, 0.25) - 0.625).abs() < 1e-9, "{:?}", s.wheel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() {
|
||||
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
|
||||
|
||||
@@ -35,6 +35,7 @@ impl Document {
|
||||
char_styles,
|
||||
para_styles,
|
||||
composite_fonts,
|
||||
kinsoku_sets,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
@@ -96,6 +97,7 @@ impl Document {
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *composite_fonts == other.composite_fonts
|
||||
&& *kinsoku_sets == other.kinsoku_sets
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
@@ -221,6 +223,7 @@ impl Document {
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
composite_fonts: Default::default(),
|
||||
kinsoku_sets: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
+65
-41
@@ -2106,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)?
|
||||
@@ -2127,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();
|
||||
@@ -2142,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))
|
||||
@@ -2164,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
|
||||
@@ -2173,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() {
|
||||
@@ -2192,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() {
|
||||
@@ -2209,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()))
|
||||
}
|
||||
@@ -2271,12 +2292,16 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// 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>, whole_compounds: bool, outline: bool) -> bool {
|
||||
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),
|
||||
@@ -2287,25 +2312,26 @@ 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, 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, whole_compounds) || painted_touches(n, s, r))
|
||||
!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),
|
||||
@@ -2334,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) {
|
||||
@@ -2351,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);
|
||||
}
|
||||
@@ -2374,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);
|
||||
}
|
||||
}
|
||||
@@ -2420,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod corners;
|
||||
pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod flare;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
@@ -137,7 +138,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
@@ -217,6 +218,10 @@ pub struct Document {
|
||||
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
|
||||
pub composite_fonts: Shared<Vec<CompositeFont>>,
|
||||
/// Type › Kinsoku Shori Settings…: the custom Kinsoku Shori sets defined in the document, by
|
||||
/// name. A paragraph using one holds a copy of it ([`ParaStyle::kinsoku_set`]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec", deserialize_with = "text::read_kinsoku_sets")]
|
||||
pub kinsoku_sets: Shared<Vec<KinsokuSet>>,
|
||||
/// Threaded text: area-type frames one story flows through, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub text_threads: Vec<Vec<NodeId>>,
|
||||
|
||||
+37
-1
@@ -113,6 +113,19 @@ impl Document {
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.kinsoku_sets, &newer.kinsoku_sets, |k| {
|
||||
vec_bytes(k)
|
||||
+ k.iter()
|
||||
.map(|s: &crate::KinsokuSet| {
|
||||
s.name.capacity()
|
||||
+ vec_bytes(&s.cannot_start)
|
||||
+ vec_bytes(&s.cannot_end)
|
||||
+ vec_bytes(&s.hanging)
|
||||
+ vec_bytes(&s.inseparable)
|
||||
+ s.inseparable.iter().map(String::capacity).sum::<usize>()
|
||||
})
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
});
|
||||
@@ -271,6 +284,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>();
|
||||
@@ -353,7 +367,8 @@ pub fn appearance_heap_bytes(a: &Appearance) -> usize {
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern))
|
||||
+ s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ [&s.pressure, &s.tilt, &s.wheel].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::<usize>()
|
||||
+ [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::<usize>()
|
||||
+ s.brush.as_ref().map_or(0, String::capacity)
|
||||
}
|
||||
_ => 0,
|
||||
@@ -424,6 +439,27 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pen_recording_of_a_stroke_counts() {
|
||||
use crate::{AngleProfile, PressureProfile};
|
||||
let plain = Appearance::default_art();
|
||||
let base = appearance_heap_bytes(&plain);
|
||||
let ramp = || PressureProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 0.5)).collect() };
|
||||
let turn = || AngleProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 10.0)).collect() };
|
||||
for i in 0..5 {
|
||||
let mut a = plain.clone();
|
||||
let s = a.stroke_mut().unwrap();
|
||||
match i {
|
||||
0 => s.pressure = Some(ramp()),
|
||||
1 => s.tilt = Some(ramp()),
|
||||
2 => s.bearing = Some(turn()),
|
||||
3 => s.rotation = Some(turn()),
|
||||
_ => s.wheel = Some(ramp()),
|
||||
}
|
||||
assert!(appearance_heap_bytes(&a) >= base + 100 * size_of::<(f64, f64)>(), "recording {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_copy_keeps_nothing_of_its_own() {
|
||||
let d = doc_with_rects(10);
|
||||
|
||||
@@ -10,8 +10,9 @@ use super::{Node, PathData};
|
||||
pub struct NodeExtras {
|
||||
/// Opacity mask (Transparency panel). Its art lives here, outside the layer tree.
|
||||
pub mask: Option<Box<OpacityMask>>,
|
||||
/// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows
|
||||
/// them; `view` is its [`crate::TraceView`] id, absent for the tracing result).
|
||||
/// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace
|
||||
/// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and
|
||||
/// `split` the Split view's divider, [`crate::TraceView::split_of`]).
|
||||
pub trace: Option<Box<serde_json::Value>>,
|
||||
/// Object → Text Wrap: area type below this object (in the same layer) flows around it.
|
||||
pub wrap: Option<crate::text::TextWrap>,
|
||||
@@ -41,6 +42,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 +104,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,
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
|
||||
mod area;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod kinsoku_set;
|
||||
mod object;
|
||||
mod para_style;
|
||||
mod runs;
|
||||
@@ -25,6 +26,8 @@ pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
|
||||
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Type › Kinsoku Shori Settings…: a custom Kinsoku Shori set, saved with the document. Its four
|
||||
//! categories hold the characters that may not start a line, those that may not end one, the
|
||||
//! hanging punctuation that Burasagari lets stand outside a line, and the inseparable sequences
|
||||
//! that Bunri-Kinshi keeps on one line. A paragraph that uses a set holds a copy of it
|
||||
//! ([`super::ParaStyle::kinsoku_set`]).
|
||||
//!
|
||||
//! Behavior reference: the help page
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html>.
|
||||
//! The name rules and the limits are VectorCraft's own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The longest set name, in characters.
|
||||
pub const KINSOKU_NAME_MAX: usize = 128;
|
||||
/// The most custom sets a document keeps.
|
||||
pub const KINSOKU_SETS_MAX: usize = 256;
|
||||
/// The most characters one category holds (an inseparable sequence counts each of its characters).
|
||||
pub const KINSOKU_CATEGORY_MAX: usize = 4096;
|
||||
/// The fewest and most characters of an inseparable sequence.
|
||||
pub const KINSOKU_SEQUENCE: std::ops::RangeInclusive<usize> = 2..=16;
|
||||
/// The names of the built-in sets, which no custom set may take (in any case).
|
||||
pub const KINSOKU_BUILT_IN: [&str; 3] = ["None", "Hard", "Soft"];
|
||||
|
||||
/// A custom Kinsoku Shori set. Each list of characters is sorted and holds each character once;
|
||||
/// the inseparable sequences are sorted and unique.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(from = "KinsokuSetFile", into = "KinsokuSetFile")]
|
||||
pub struct KinsokuSet {
|
||||
pub name: String,
|
||||
/// Cannot Start Line: characters that never start a line.
|
||||
pub cannot_start: Vec<char>,
|
||||
/// Cannot End Line: characters that never end a line.
|
||||
pub cannot_end: Vec<char>,
|
||||
/// Hanging Punctuation: characters that Burasagari lets hang outside a line's end.
|
||||
pub hanging: Vec<char>,
|
||||
/// Bunri-Kinshi: sequences of characters that a line never breaks inside while Bunri-Kinshi is
|
||||
/// on.
|
||||
pub inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// [`KinsokuSet`] as saved: each category of single characters as one string.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct KinsokuSetFile {
|
||||
#[serde(default, deserialize_with = "read_name")]
|
||||
name: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_start: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_end: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
hanging: String,
|
||||
#[serde(default, deserialize_with = "read_sequences")]
|
||||
inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// The most characters of a name read from a file, spaces around it included; a longer name is
|
||||
/// not read.
|
||||
const NAME_READ_MAX: usize = KINSOKU_CATEGORY_MAX;
|
||||
/// The most characters of a category read from a file, before control and space characters are
|
||||
/// left out.
|
||||
const CATEGORY_READ_MAX: usize = KINSOKU_CATEGORY_MAX * 4;
|
||||
/// The longest inseparable sequence, as a constant for [`Capped`].
|
||||
const SEQUENCE_MAX: usize = *KINSOKU_SEQUENCE.end();
|
||||
|
||||
/// Text read from a file, copied up to `N` characters: a longer text keeps its first `N + 1`, which
|
||||
/// no rule that allows `N` takes, and is not copied whole.
|
||||
struct Capped<const N: usize>(String);
|
||||
|
||||
impl<'de, const N: usize> Deserialize<'de> for Capped<N> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Text<const N: usize>;
|
||||
impl<const N: usize> serde::de::Visitor<'_> for Text<N> {
|
||||
type Value = Capped<N>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("text")
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Capped<N>, E> {
|
||||
Ok(Capped(v.chars().take(N + 1).collect()))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Text::<N>)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's name as read from a file: empty, so not read, when it is longer than [`NAME_READ_MAX`].
|
||||
fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(name) = Capped::<NAME_READ_MAX>::deserialize(d)?;
|
||||
Ok(if name.chars().count() > NAME_READ_MAX { String::new() } else { name })
|
||||
}
|
||||
|
||||
/// A category of a set as read from a file: its first [`CATEGORY_READ_MAX`] characters.
|
||||
fn read_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(text) = Capped::<CATEGORY_READ_MAX>::deserialize(d)?;
|
||||
Ok(text.chars().take(CATEGORY_READ_MAX).collect())
|
||||
}
|
||||
|
||||
/// Reads a list, keeping the items `keep` keeps up to `max` of them and skipping the rest of a
|
||||
/// longer list without storing it.
|
||||
struct Kept<T, F>(usize, F, std::marker::PhantomData<T>);
|
||||
|
||||
impl<'de, T: Deserialize<'de>, F: FnMut(&T) -> bool> serde::de::Visitor<'de> for Kept<T, F> {
|
||||
type Value = Vec<T>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(mut self, mut seq: A) -> Result<Vec<T>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while out.len() < self.0 {
|
||||
match seq.next_element::<T>()? {
|
||||
Some(item) if (self.1)(&item) => out.push(item),
|
||||
Some(_) => {}
|
||||
None => return Ok(out),
|
||||
}
|
||||
}
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's inseparable sequences as read from a file: those [`KinsokuSet::takes_sequence`] takes,
|
||||
/// at most [`KINSOKU_CATEGORY_MAX`]. A text longer than a sequence is not copied whole.
|
||||
fn read_sequences<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
|
||||
let keep = |s: &Capped<SEQUENCE_MAX>| KinsokuSet::takes_sequence(&s.0);
|
||||
let kept = d.deserialize_seq(Kept(KINSOKU_CATEGORY_MAX, keep, std::marker::PhantomData))?;
|
||||
Ok(kept.into_iter().map(|Capped(s)| s).collect())
|
||||
}
|
||||
|
||||
impl From<KinsokuSet> for KinsokuSetFile {
|
||||
fn from(s: KinsokuSet) -> Self {
|
||||
Self {
|
||||
name: s.name,
|
||||
cannot_start: s.cannot_start.into_iter().collect(),
|
||||
cannot_end: s.cannot_end.into_iter().collect(),
|
||||
hanging: s.hanging.into_iter().collect(),
|
||||
inseparable: s.inseparable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<KinsokuSetFile> for KinsokuSet {
|
||||
/// A set read from a file keeps what a set can hold: its name trimmed, or no name when
|
||||
/// [`KinsokuSet::clean_name`] refuses it; each category's characters sorted and unique, without
|
||||
/// control or space characters, up to [`KINSOKU_CATEGORY_MAX`]; and the inseparable sequences of
|
||||
/// [`KINSOKU_SEQUENCE`] characters, up to the same count of characters.
|
||||
fn from(f: KinsokuSetFile) -> Self {
|
||||
let chars = |s: &str| s.chars().filter(|&c| KinsokuSet::takes_char(c)).take(KINSOKU_CATEGORY_MAX * 4).collect::<Vec<char>>();
|
||||
let mut set = KinsokuSet {
|
||||
name: KinsokuSet::clean_name(&f.name).unwrap_or_default(),
|
||||
cannot_start: chars(&f.cannot_start),
|
||||
cannot_end: chars(&f.cannot_end),
|
||||
hanging: chars(&f.hanging),
|
||||
inseparable: f.inseparable,
|
||||
};
|
||||
set.normalize();
|
||||
set.cannot_start.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.cannot_end.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.hanging.truncate(KINSOKU_CATEGORY_MAX);
|
||||
let mut total = 0;
|
||||
set.inseparable.retain(|s| {
|
||||
total += s.chars().count();
|
||||
total <= KINSOKU_CATEGORY_MAX
|
||||
});
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's custom sets as read from a file: each set with a name, the first set of each name
|
||||
/// (in any case), at most [`KINSOKU_SETS_MAX`]; the sets past those are skipped without being
|
||||
/// stored.
|
||||
pub(crate) fn read_sets<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::Shared<Vec<KinsokuSet>>, D::Error> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let keep = move |s: &KinsokuSet| !s.name.is_empty() && seen.insert(s.name.to_lowercase());
|
||||
Ok(crate::Shared::new(d.deserialize_seq(Kept(KINSOKU_SETS_MAX, keep, std::marker::PhantomData))?))
|
||||
}
|
||||
|
||||
impl KinsokuSet {
|
||||
/// Do `a` and `b` name the same set: equal in any case?
|
||||
pub fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// The set of `sets` (a document's custom sets) named `name`, in any case.
|
||||
pub fn named<'a>(sets: &'a [KinsokuSet], name: &str) -> Option<&'a KinsokuSet> {
|
||||
sets.iter().find(|s| Self::same_name(&s.name, name))
|
||||
}
|
||||
|
||||
/// `name` trimmed, when it can name a custom set: not empty, at most [`KINSOKU_NAME_MAX`]
|
||||
/// characters, without control characters, and none of [`KINSOKU_BUILT_IN`] in any case.
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let ok = !name.is_empty()
|
||||
&& name.chars().count() <= KINSOKU_NAME_MAX
|
||||
&& !name.chars().any(char::is_control)
|
||||
&& !KINSOKU_BUILT_IN.iter().any(|b| Self::same_name(b, name));
|
||||
ok.then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// Can a category hold character `c`: not a control character nor a space?
|
||||
pub fn takes_char(c: char) -> bool {
|
||||
!c.is_control() && !c.is_whitespace()
|
||||
}
|
||||
|
||||
/// Can `s` be an inseparable sequence: [`KINSOKU_SEQUENCE`] characters that
|
||||
/// [`Self::takes_char`] takes?
|
||||
pub fn takes_sequence(s: &str) -> bool {
|
||||
KINSOKU_SEQUENCE.contains(&s.chars().count()) && s.chars().all(Self::takes_char)
|
||||
}
|
||||
|
||||
/// Sort each category and keep each character or sequence once.
|
||||
pub fn normalize(&mut self) {
|
||||
for list in [&mut self.cannot_start, &mut self.cannot_end, &mut self.hanging] {
|
||||
list.sort_unstable();
|
||||
list.dedup();
|
||||
}
|
||||
self.inseparable.sort_unstable();
|
||||
self.inseparable.dedup();
|
||||
}
|
||||
|
||||
/// Why this set can't be used, if it can't: a name [`Self::clean_name`] refuses, a character
|
||||
/// [`Self::takes_char`] refuses, a sequence [`Self::takes_sequence`] refuses, or a category of
|
||||
/// more than [`KINSOKU_CATEGORY_MAX`] characters.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!(
|
||||
"`{}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)",
|
||||
self.name
|
||||
));
|
||||
}
|
||||
for (key, list) in [("cannotStart", &self.cannot_start), ("cannotEnd", &self.cannot_end), ("hanging", &self.hanging)] {
|
||||
if list.len() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("{key}: at most {KINSOKU_CATEGORY_MAX} characters"));
|
||||
}
|
||||
if let Some(c) = list.iter().find(|&&c| !Self::takes_char(c)) {
|
||||
return Err(format!("{key}: U+{:04X} is a control or space character", u32::from(*c)));
|
||||
}
|
||||
}
|
||||
if let Some(s) = self.inseparable.iter().find(|s| !Self::takes_sequence(s)) {
|
||||
return Err(format!(
|
||||
"inseparable: `{s}` must be {} to {} characters, none of them control or space characters",
|
||||
KINSOKU_SEQUENCE.start(),
|
||||
KINSOKU_SEQUENCE.end()
|
||||
));
|
||||
}
|
||||
if self.inseparable.iter().map(|s| s.chars().count()).sum::<usize>() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// May `c` not start a line?
|
||||
pub fn cannot_start(&self, c: char) -> bool {
|
||||
self.cannot_start.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` not end a line?
|
||||
pub fn cannot_end(&self, c: char) -> bool {
|
||||
self.cannot_end.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` hang outside a line's end (Burasagari)?
|
||||
pub fn hangs(&self, c: char) -> bool {
|
||||
self.hanging.binary_search(&c).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::text::{Kinsoku, ParaStyle};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A set is saved with each category as one string and read back as it was; a paragraph saves
|
||||
/// its copy of the set beside Hard, and a paragraph saved without one reads with none.
|
||||
#[test]
|
||||
fn kinsoku_sets_are_saved_with_the_paragraphs_that_use_them() {
|
||||
let mut set = KinsokuSet {
|
||||
name: "Tight".into(),
|
||||
cannot_start: "」。、".chars().collect(),
|
||||
cannot_end: vec!['「'],
|
||||
hanging: vec!['、', '。'],
|
||||
inseparable: vec!["——".into(), "あいう".into()],
|
||||
};
|
||||
set.normalize();
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved, json!({"name": "Tight", "cannotStart": "、。」", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——", "あいう"]}));
|
||||
assert_eq!(serde_json::from_value::<KinsokuSet>(saved).unwrap(), set);
|
||||
let p = ParaStyle { kinsoku_set: Some(Arc::new(set.clone())), ..ParaStyle::default() };
|
||||
let v = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(v["kinsoku_set"]["name"], "Tight");
|
||||
assert!(v.get("kinsoku").is_none(), "Hard, the default, is left out");
|
||||
let back: ParaStyle = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(back.kinsoku_set.as_deref(), Some(&set));
|
||||
assert_eq!((back.kinsoku, back.kinsoku_name(), back.kinsoku_on()), (Kinsoku::Hard, "Tight", true));
|
||||
let old: ParaStyle = serde_json::from_value(json!({"justify": "Left", "kinsoku": "soft"})).unwrap();
|
||||
assert_eq!((old.kinsoku_set, old.kinsoku), (None, Kinsoku::Soft));
|
||||
assert!(serde_json::to_value(ParaStyle::default()).unwrap().get("kinsoku_set").is_none());
|
||||
}
|
||||
|
||||
/// A set read from a file keeps only what a set can hold: each character once, sorted, without
|
||||
/// control or space characters, at most 4096 to a category, and sequences of 2 to 16
|
||||
/// characters; a category left out is empty. Only the start of a longer text is read.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_from_a_file_keep_what_a_set_can_hold() {
|
||||
let long: String = (0x4E00..0x4E00 + 5000).filter_map(char::from_u32).collect();
|
||||
let v = json!({
|
||||
"name": "Odd",
|
||||
"cannotStart": "ccba \t\u{0}a",
|
||||
"cannotEnd": long,
|
||||
"inseparable": ["a", "ab", "ab", "a b", "abcdefghijklmnopq", "abcdefghijklmnop"],
|
||||
});
|
||||
let set: KinsokuSet = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(set.cannot_start, ['a', 'b', 'c']);
|
||||
assert_eq!(set.cannot_end.len(), KINSOKU_CATEGORY_MAX);
|
||||
assert!(set.hanging.is_empty());
|
||||
assert_eq!(set.inseparable, ["ab", "abcdefghijklmnop"]);
|
||||
assert!(set.check().is_ok());
|
||||
let empty: KinsokuSet = serde_json::from_value(json!({})).unwrap();
|
||||
assert!(empty.check().is_err(), "a set needs a name");
|
||||
// Only the start of a long text is read: a category's first 16384 characters, a name of at
|
||||
// most 4096 characters, spaces included, and a sequence's first 17.
|
||||
let spaces = " ".repeat(CATEGORY_READ_MAX);
|
||||
let text = format!(
|
||||
r#"{{"name": "{}Tight", "hanging": "{spaces}、", "cannotEnd": "、", "inseparable": ["{}あ"]}}"#,
|
||||
" ".repeat(NAME_READ_MAX),
|
||||
"あ".repeat(100)
|
||||
);
|
||||
let set: KinsokuSet = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!((set.name.as_str(), set.hanging.len(), set.cannot_end.len(), set.inseparable.len()), ("", 0, 1, 0));
|
||||
let set: KinsokuSet = serde_json::from_str(&format!(r#"{{"name": "{}Tight"}}"#, " ".repeat(NAME_READ_MAX - 5))).unwrap();
|
||||
assert_eq!(set.name, "Tight");
|
||||
}
|
||||
|
||||
/// A set read from a file under a name a custom set can't take (a built-in name, a blank one)
|
||||
/// is not read: a paragraph holding it keeps its Kinsoku Set, so it doesn't show as Hard while
|
||||
/// composing by other characters, and a document's list drops it. The list also keeps the
|
||||
/// first set of each name in any case, and a name read with spaces around it is trimmed. A
|
||||
/// paragraph's set read beside None or Soft is not read either.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_under_names_a_set_cannot_take_are_dropped() {
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": "Hard", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set, p.kinsoku), (None, Kinsoku::Hard));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku": "none", "kinsoku_set": {"name": "Tight", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set.is_none(), p.kinsoku_name()), (true, "None"));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": " Tight ", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!(p.kinsoku_name(), "Tight");
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
v["kinsoku_sets"] = json!([{"name": "soft"}, {"name": " "}, {"name": "Tight", "cannotEnd": "「"}, {"name": "TIGHT"}, {"name": "Loose"}]);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
let names: Vec<&str> = d.kinsoku_sets.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Tight", "Loose"]);
|
||||
assert_eq!(d.kinsoku_sets[0].cannot_end, ['「']);
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
// The sets past the limit are skipped unread: one that isn't a set at all doesn't fail the
|
||||
// file.
|
||||
let mut list: Vec<serde_json::Value> = (0..KINSOKU_SETS_MAX + 5).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
list.push(json!("not a set"));
|
||||
v["kinsoku_sets"] = json!(list);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(d.kinsoku_sets.len(), KINSOKU_SETS_MAX);
|
||||
let past: Vec<String> = (0..KINSOKU_CATEGORY_MAX + 1).map(|i| format!("あ{i}")).chain(["x".to_string()]).collect();
|
||||
let mut seqs: Vec<serde_json::Value> = past.iter().map(|s| json!(s)).collect();
|
||||
seqs.push(json!(7));
|
||||
let set: KinsokuSet = serde_json::from_value(json!({"name": "Long", "inseparable": seqs})).unwrap();
|
||||
assert!(set.check().is_ok());
|
||||
}
|
||||
|
||||
/// A name is trimmed, 1 to 128 characters without control characters, and never None, Hard or
|
||||
/// Soft in any case; names match in any case.
|
||||
#[test]
|
||||
fn kinsoku_set_names_are_checked() {
|
||||
assert_eq!(KinsokuSet::clean_name(" Tight "), Some("Tight".into()));
|
||||
for bad in ["", " ", "hard", "SOFT", "None", "a\u{7}b", &"x".repeat(KINSOKU_NAME_MAX + 1)] {
|
||||
assert_eq!(KinsokuSet::clean_name(bad), None, "{bad:?}");
|
||||
}
|
||||
assert!(KinsokuSet::clean_name(&"漢".repeat(KINSOKU_NAME_MAX)).is_some());
|
||||
assert!(KinsokuSet::same_name("Tight", "tIGHT"));
|
||||
let sets = [KinsokuSet { name: "Tight".into(), ..Default::default() }];
|
||||
assert!(KinsokuSet::named(&sets, "TIGHT").is_some() && KinsokuSet::named(&sets, "Loose").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::char_style::CharStyle;
|
||||
use super::kinsoku_set::KinsokuSet;
|
||||
use super::tabs_lists::{ParaList, TabStop};
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
@@ -256,14 +259,18 @@ pub struct ParaStyle {
|
||||
/// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top
|
||||
/// of one line's ideographic em box to the next.
|
||||
pub leading_model: LeadingModel,
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
|
||||
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): the Kinsoku Set's hanging
|
||||
/// punctuation ending a line may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
|
||||
/// punctuation on, which opens with [`Burasagari::Forced`].
|
||||
pub burasagari: Burasagari,
|
||||
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
|
||||
/// line.
|
||||
pub kinsoku: Kinsoku,
|
||||
/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) chosen in Kinsoku Set: a copy of
|
||||
/// the document's set of that name, which takes the place of [`Self::kinsoku`]. A paragraph
|
||||
/// with one keeps [`Kinsoku::Hard`] in `kinsoku`, which builds without custom sets read.
|
||||
pub kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
|
||||
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
|
||||
pub kinsoku_type: KinsokuShoriType,
|
||||
@@ -310,6 +317,21 @@ impl ParaStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does kinsoku apply: a custom set, or a Kinsoku Set other than None?
|
||||
pub fn kinsoku_on(&self) -> bool {
|
||||
self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None
|
||||
}
|
||||
|
||||
/// The name Kinsoku Set shows: the custom set's, or None, Hard or Soft.
|
||||
pub fn kinsoku_name(&self) -> &str {
|
||||
match (&self.kinsoku_set, self.kinsoku) {
|
||||
(Some(set), _) => &set.name,
|
||||
(None, Kinsoku::None) => "None",
|
||||
(None, Kinsoku::Hard) => "Hard",
|
||||
(None, Kinsoku::Soft) => "Soft",
|
||||
}
|
||||
}
|
||||
|
||||
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
|
||||
/// list at a level past the first, [`ParaList::level_indent`] more.
|
||||
pub fn laid_out_left_indent(&self) -> f64 {
|
||||
@@ -373,6 +395,8 @@ struct ParaStyleFile {
|
||||
burasagari: Burasagari,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku: Kinsoku,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -415,6 +439,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -443,6 +468,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -475,6 +501,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -483,6 +510,11 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
korean_line_break_anywhere,
|
||||
..
|
||||
} = f;
|
||||
// A set whose saved name can't name a custom set (None, Hard or Soft, say) is read as no set:
|
||||
// the paragraph keeps its Kinsoku Set. A paragraph with a custom set keeps Hard, so one read
|
||||
// with None or Soft (a paragraph style written before custom sets, applied over one) has no
|
||||
// custom set.
|
||||
let kinsoku_set = kinsoku_set.filter(|s| !s.name.is_empty() && kinsoku == Kinsoku::Hard);
|
||||
Self {
|
||||
justify,
|
||||
left_indent,
|
||||
@@ -502,6 +534,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -604,19 +637,21 @@ pub enum KinsokuShoriType {
|
||||
PushOutOnly,
|
||||
}
|
||||
|
||||
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
|
||||
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
|
||||
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
|
||||
/// as None / Regular / Force.
|
||||
/// Hanging punctuation (burasagari): hanging punctuation ending a line stands outside the line's
|
||||
/// measure, in the space its punctuation spacing gives it (half width with Line-end Punctuation
|
||||
/// Half Width). With the built-in Kinsoku Sets that is an East Asian comma or full stop
|
||||
/// (、。,.、。), and closing brackets and Latin punctuation don't hang; a custom Kinsoku Set hangs
|
||||
/// the characters in its hanging category. Shown as None / Regular / Force.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Burasagari {
|
||||
/// A comma or full stop that doesn't fit goes to the next line with the character before it.
|
||||
#[default]
|
||||
None,
|
||||
/// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside.
|
||||
/// Hanging punctuation that doesn't fit hangs outside the line; punctuation that fits stays
|
||||
/// inside.
|
||||
Standard,
|
||||
/// A comma or full stop ending a line always hangs, and the rest of the line fills the measure.
|
||||
/// Hanging punctuation ending a line always hangs, and the rest of the line fills the measure.
|
||||
Forced,
|
||||
}
|
||||
|
||||
|
||||
+54
-6
@@ -20,11 +20,18 @@ pub enum TraceView {
|
||||
OutlinesWithSource,
|
||||
/// Only the source image.
|
||||
Source,
|
||||
/// The source image on the part of the image left of a divider across it, and the traced
|
||||
/// shapes everywhere else ([`TraceView::split_of`]).
|
||||
Split,
|
||||
}
|
||||
|
||||
/// Where the Split view's divider is when the `trace` settings name no valid position: across the
|
||||
/// middle of the source image.
|
||||
pub const DEFAULT_TRACE_SPLIT: f64 = 0.5;
|
||||
|
||||
impl TraceView {
|
||||
/// Panel order.
|
||||
pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source];
|
||||
pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split];
|
||||
|
||||
/// The id used in command params and in the saved `trace` object.
|
||||
pub fn id(self) -> &'static str {
|
||||
@@ -34,6 +41,7 @@ impl TraceView {
|
||||
Self::Outlines => "outlines",
|
||||
Self::OutlinesWithSource => "outlinesWithSourceImage",
|
||||
Self::Source => "sourceImage",
|
||||
Self::Split => "split",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,14 +56,21 @@ impl TraceView {
|
||||
trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the source image shows.
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source)
|
||||
/// The Split view's divider in `trace` settings: the fraction of the source image's width, from
|
||||
/// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when
|
||||
/// `split` is missing, not a number or outside 0 to 1).
|
||||
pub fn split_of(trace: &serde_json::Value) -> f64 {
|
||||
trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled.
|
||||
/// Whether the source image shows (in the Split view, on one side of the divider).
|
||||
pub fn shows_source(self) -> bool {
|
||||
matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes show filled (in the Split view, on one side of the divider).
|
||||
pub fn shows_result(self) -> bool {
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines)
|
||||
matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split)
|
||||
}
|
||||
|
||||
/// Whether the traced shapes' outlines show.
|
||||
@@ -69,6 +84,12 @@ impl Node {
|
||||
pub fn trace_view(&self) -> TraceView {
|
||||
self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The Split view's divider of an Image Trace object ([`TraceView::split_of`];
|
||||
/// [`DEFAULT_TRACE_SPLIT`] for anything else).
|
||||
pub fn trace_split(&self) -> f64 {
|
||||
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -89,6 +110,26 @@ mod tests {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"})));
|
||||
assert_eq!(g.trace_view(), TraceView::Result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
|
||||
let mut g = Node::group(crate::NodeId(1), vec![]);
|
||||
assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT);
|
||||
assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split));
|
||||
assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines());
|
||||
for (split, want) in [
|
||||
(serde_json::json!(0.25), 0.25),
|
||||
(serde_json::json!(0), 0.0),
|
||||
(serde_json::json!(1), 1.0),
|
||||
(serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!(1.5), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT),
|
||||
(serde_json::Value::Null, DEFAULT_TRACE_SPLIT),
|
||||
] {
|
||||
g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!(g.trace_split(), want, "{split}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() {
|
||||
use crate::{Appearance, Document, ImageObject, NodeId, NodeKind};
|
||||
@@ -132,6 +173,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The Split view measures the whole image wherever the divider is, so the selection box
|
||||
// stays put while the divider moves.
|
||||
for split in [0.0, 0.01, 1.0] {
|
||||
let want = Rect::new(0.0, 0.0, 200.0, 200.0);
|
||||
group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split})));
|
||||
assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}");
|
||||
}
|
||||
group.extras_mut().trace = None;
|
||||
assert_eq!(
|
||||
group.geometric_bounds(),
|
||||
|
||||
+66
-5
@@ -81,6 +81,21 @@ impl Unit {
|
||||
Unit::Ha => "H",
|
||||
}
|
||||
}
|
||||
/// Whether this unit is a physical measurement unit (not points or pixels).
|
||||
pub fn is_physical(self) -> bool {
|
||||
self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha)
|
||||
}
|
||||
/// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG
|
||||
/// (`mm`, `cm`, `in`, `pc`).
|
||||
pub fn svg_suffix(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Unit::Millimeters => Some("mm"),
|
||||
Unit::Centimeters => Some("cm"),
|
||||
Unit::Inches => Some("in"),
|
||||
Unit::Picas => Some("pc"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Unit::Points => "Points",
|
||||
@@ -157,12 +172,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(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
@@ -215,6 +235,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 +408,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.
|
||||
|
||||
@@ -210,15 +210,15 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (the swept side is surface 1, the only one; in a group, the side of the member with the longest profile; a map of another surface draws nothing), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the middle of the side unrolled flat, around the axis), y: pt (-1000000..1000000, 0; along the profile), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the art wraps around the side and is drawn where its outside faces the viewer; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults, the surface numbering and the limits are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"mapArt":[],"mapShade":false,"mapInvisible":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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,
|
||||
@@ -106,6 +108,10 @@ pub use solids::{
|
||||
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 solids::{
|
||||
MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, MapSurface, SurfaceKind, SurfaceMap, map_surfaces_at,
|
||||
map_surfaces_with, surface_maps, takes_map_art, with_surface_map,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
pub use trap::TRAP;
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -113,7 +113,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
|
||||
/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with
|
||||
/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them.
|
||||
fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
pub(crate) fn options_of(id: &str, p: &Value) -> Revolve {
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::options(p)
|
||||
} else {
|
||||
@@ -141,6 +141,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul
|
||||
/// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`.
|
||||
pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_params_of(id, p)?;
|
||||
validate_map_symbols(doc, id, p)?;
|
||||
let n = &*resolve_for(doc, n, "Revolve", false)?;
|
||||
let effects = &n.appearance.effects;
|
||||
// The profile is measured before the object's one Revolve, hidden or shown.
|
||||
@@ -215,7 +216,7 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op
|
||||
|
||||
/// The member of a group whose side takes the group's graphics: the first with the longest
|
||||
/// profile among those with a fill or stroke.
|
||||
fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
|
||||
pub(crate) fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
|
||||
shapes
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -237,6 +238,20 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
/// appearance item `target` of `n` ([`validate_item_of`]).
|
||||
/// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of
|
||||
/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic), or past the
|
||||
/// limits of art unrolled onto its side, its only surface.
|
||||
fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> {
|
||||
match doc.filter(|_| id == CLASSIC_REVOLVE) {
|
||||
Some(doc) => {
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
// The side is surface 1, laid out about the origin; a map past it draws nothing.
|
||||
crate::solids::graphics::validate_unrolled_symbols(doc, p, &|surface| (surface == 1).then_some(Point::ZERO))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
|
||||
validate_item_of(None, n, REVOLVE, p, target, index)
|
||||
@@ -252,6 +267,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V
|
||||
return validate_in(doc, n, id, p);
|
||||
}
|
||||
validate_params_of(id, p)?;
|
||||
validate_map_symbols(doc, id, p)?;
|
||||
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
if !has_two_anchors(&path) {
|
||||
@@ -334,7 +350,7 @@ fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&Appea
|
||||
|
||||
/// `options` with one number of samples for every curve of `shapes`, the members of one group: the
|
||||
/// members share Revolve's limits.
|
||||
fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
|
||||
pub(crate) fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, String> {
|
||||
let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?;
|
||||
Ok(Revolve { curve_samples: Some(samples), ..options })
|
||||
}
|
||||
@@ -463,10 +479,12 @@ fn group_shadow(
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last
|
||||
/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them
|
||||
/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). With
|
||||
/// `hide`, a Revolve (Classic) surface without mapped art leaves its faces out, as Invisible
|
||||
/// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces
|
||||
/// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`],
|
||||
/// [`sealed_runs`]) in the order it draws them; and whether the faces were left out.
|
||||
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
@@ -480,7 +498,8 @@ fn surface(
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool)> {
|
||||
hide: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool, bool)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
@@ -500,7 +519,23 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false));
|
||||
// Mapped art goes on the side, the surface's one numbered surface. Its paints' copies
|
||||
// count with the graphics', and art past the limits is left out.
|
||||
let map_art = crate::solids::graphics::map_art::MapArt::of(doc, &fx.id, &p);
|
||||
let layout = map_art.as_ref().and_then(|_| {
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(path, b, options)?;
|
||||
let side = vectorcraft_three_d::SolidSurface { kind: vectorcraft_three_d::SurfaceKind::Side, width, height, center: None };
|
||||
Some(crate::solids::graphics::map_art::SolidLayout { first: 0, surfaces: vec![side], ends: None })
|
||||
});
|
||||
let mut budget = crate::solids::graphics::map_art::MapBudget::default();
|
||||
let mapped = map_art.as_ref().zip(layout.as_ref()).map(|(art, layout)| crate::solids::classic::Mapped {
|
||||
art,
|
||||
layout,
|
||||
budget: &mut budget,
|
||||
copies: &mut copies.graphics,
|
||||
});
|
||||
let (art, hidden, _) = crate::solids::classic::surface(n, &facets, &paint, (opacity, blend), &p, mapped, hide);
|
||||
return Some((drawn, art, kept, false, hidden));
|
||||
}
|
||||
let colored = colored(&options);
|
||||
let (faces, kept) = if cast {
|
||||
@@ -632,7 +667,7 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group, kept, seal))
|
||||
Some((keys, group, kept, seal, false))
|
||||
}
|
||||
|
||||
/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal`
|
||||
@@ -722,8 +757,8 @@ fn object_surface(
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
|
||||
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast, false)
|
||||
.map(|(_, art, kept, seal, _)| (sealed_surface(n.id, art, seal), kept))
|
||||
}
|
||||
|
||||
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
|
||||
@@ -1155,22 +1190,42 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
|
||||
// Revolve (Classic)'s mapped art goes on that member's side too.
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let mapped = (fx.id == REVOLVE && !crate::solids::mapped_graphics(&p).is_empty())
|
||||
|| (fx.id == CLASSIC_REVOLVE && !crate::solids::surface_maps(&p).is_empty());
|
||||
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
// Member `k`'s surface, its faces left out with `hide`, with its opacity and blending mode;
|
||||
// `None` for a member with no fill or stroke.
|
||||
let member = |k: usize, s: &Profile, hide: bool, copies: &mut Copies| {
|
||||
let item = surface_item(&s.items)?;
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let options = Revolve { fill_rule: s.rule, ..options };
|
||||
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
Some((opacity, blend, surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, copies, cast, hide)))
|
||||
};
|
||||
// With Invisible Geometry the other members leave their faces out too, once the mapped art on
|
||||
// the longest member's side has left that member's faces out, so it is built first.
|
||||
let invisible = fx.id == CLASSIC_REVOLVE && doc.is_some() && p.get(crate::solids::MAP_INVISIBLE).and_then(Value::as_bool).unwrap_or(false);
|
||||
let mut first = None;
|
||||
if let Some(l) = longest.filter(|_| invisible)
|
||||
&& let Some(s) = shapes.get(l)
|
||||
{
|
||||
first = member(l, s, false, &mut copies);
|
||||
}
|
||||
let hide = matches!(first, Some((_, _, Some((_, _, _, _, true)))));
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let built = if longest == Some(k) && first.is_some() { first.take() } else { member(k, s, hide, &mut copies) };
|
||||
let Some((opacity, blend, built)) = built else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
let (depths, art, faces, seal, _) = built?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
seals.push(seal);
|
||||
@@ -1870,8 +1925,9 @@ mod tests {
|
||||
let path = n.path_data().unwrap();
|
||||
let fx = n.appearance.effects.first().unwrap();
|
||||
let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap());
|
||||
let (_, art, _, seal) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap();
|
||||
let (_, art, _, seal, _) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false, false)
|
||||
.unwrap();
|
||||
(art, seal)
|
||||
}
|
||||
|
||||
@@ -2129,7 +2185,7 @@ mod tests {
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
assert!(kept.iter().all(Option::is_some), "{id} {params}");
|
||||
@@ -2165,7 +2221,7 @@ mod tests {
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
use serde_json::Value;
|
||||
use vectorcraft_three_d::Revolve;
|
||||
|
||||
use crate::solids::graphics::map_art;
|
||||
|
||||
pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve";
|
||||
|
||||
/// The numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
@@ -23,19 +25,28 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"];
|
||||
const FLAGS: [&str; 5] = ["cap", "lightBehind", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE];
|
||||
|
||||
/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge,
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces.
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces. With
|
||||
/// mapped art its side is laid out for it.
|
||||
pub(crate) fn options(p: &Value) -> Revolve {
|
||||
Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) }
|
||||
Revolve {
|
||||
shade: false,
|
||||
smooth_shading: false,
|
||||
lights: None,
|
||||
light_color: [1.0; 3],
|
||||
map_surface: !map_art::surface_maps(p).is_empty(),
|
||||
..super::revolve_options(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares
|
||||
/// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false,
|
||||
/// and the surface and shading color are named.
|
||||
/// the surface and shading color are named, and `mapArt` holds valid maps.
|
||||
pub(crate) fn validate(p: &Value) -> Result<(), String> {
|
||||
crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)
|
||||
crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)?;
|
||||
map_art::validate(CLASSIC_REVOLVE, p)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+236
-27
@@ -24,6 +24,10 @@ mod source;
|
||||
pub(crate) use source::{resolve, resolve_for};
|
||||
|
||||
pub(crate) mod graphics;
|
||||
pub use graphics::map_art::{
|
||||
MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, SurfaceMap, surface_maps, takes_map_art, with_surface_map,
|
||||
};
|
||||
use graphics::map_art::{MapArt, MapBudget, SolidLayout};
|
||||
pub use graphics::{
|
||||
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
|
||||
@@ -32,6 +36,7 @@ pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
|
||||
fitting as graphic_fitting_scale, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use vectorcraft_three_d::SurfaceKind;
|
||||
|
||||
pub(crate) mod shadow;
|
||||
|
||||
@@ -180,6 +185,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
|
||||
both_sides: flag(p, "bevelBothSides", false),
|
||||
}),
|
||||
hidden: false,
|
||||
map_surfaces: false,
|
||||
map_surface: false,
|
||||
}
|
||||
}
|
||||
@@ -431,11 +437,22 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
/// ([`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.
|
||||
/// included. On Extrude & Bevel (Classic), the art Map Art places on walls and bevels must also fit
|
||||
/// ([`graphics::validate_unrolled_symbols`]). 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);
|
||||
// Map Art unrolls its art onto walls and bevels; the caps draw it as it is.
|
||||
if id == CLASSIC_EXTRUDE && !surface_maps(p).is_empty() {
|
||||
let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(p) };
|
||||
let unrolled: Vec<Option<Point>> = parts
|
||||
.iter()
|
||||
.flat_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default())
|
||||
.map(|s| (!matches!(s.kind, SurfaceKind::End(_))).then(|| graphics::map_art::flat_center(&s)))
|
||||
.collect();
|
||||
graphics::validate_unrolled_symbols(doc, p, &|surface| surface.checked_sub(1).and_then(|k| unrolled.get(k).copied().flatten()))?;
|
||||
}
|
||||
if side_carrier(id, p, &parts, bounds).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1924,8 +1941,11 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
|
||||
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
|
||||
}
|
||||
}
|
||||
let art =
|
||||
if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) };
|
||||
let art = if classic {
|
||||
classic::surface(n, &f, &paint, (opacity, blend), &p, None, false).0
|
||||
} else {
|
||||
surface(n, f, &paint, opacity, blend, colored, false)
|
||||
};
|
||||
out.push((s.scopes.as_slice(), Arc::new(art)));
|
||||
}
|
||||
}
|
||||
@@ -1939,15 +1959,28 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
|
||||
let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None };
|
||||
let mut solids = vec![];
|
||||
let mut built = vec![];
|
||||
// With mapped art, each solid's place among the object's numbered surfaces: the surfaces are
|
||||
// counted through the parts in order, those of a part whose solid is left out too.
|
||||
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
|
||||
let mut layouts: Vec<SolidLayout> = vec![];
|
||||
let mut surfaces_before = 0usize;
|
||||
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() {
|
||||
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
|
||||
let item: &AppearanceItem = item;
|
||||
let layout = map_art.as_ref().map(|_| {
|
||||
let options = classic_extrude_options(&p);
|
||||
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
|
||||
let first = surfaces_before;
|
||||
surfaces_before += surfaces.len();
|
||||
SolidLayout { first, surfaces, ends: Some((bounds, options, view_options(&p))) }
|
||||
});
|
||||
match f {
|
||||
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
return None;
|
||||
}
|
||||
Ok(Some((f, faces))) => {
|
||||
solids.push((item, *opacity, *scopes, f, *member));
|
||||
layouts.extend(layout);
|
||||
built.push(faces);
|
||||
}
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws, and
|
||||
@@ -2035,6 +2068,34 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
|
||||
let split =
|
||||
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
|
||||
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
|
||||
// The classic surfaces of the solids, with mapped art when the effect has maps. When the art of
|
||||
// any solid is past the limits the object's maps share, every solid draws without mapped art.
|
||||
let mut classic_arts = if classic {
|
||||
let draw = |with_art: bool, copies: &mut usize| {
|
||||
let mut budget = MapBudget::default();
|
||||
let mut dropped = false;
|
||||
let mut arts = Vec::with_capacity(solids.len());
|
||||
for (k, (item, member, _, f, _)) in solids.iter().enumerate() {
|
||||
let (paint, opacity, blend) = paint_of(item, *member);
|
||||
let mapped = map_art.as_ref().filter(|_| with_art).zip(layouts.get(k)).map(|(art, layout)| classic::Mapped {
|
||||
art,
|
||||
layout,
|
||||
budget: &mut budget,
|
||||
copies: &mut *copies,
|
||||
});
|
||||
let (art, _, left_out) = classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false);
|
||||
dropped |= left_out;
|
||||
arts.push(art);
|
||||
}
|
||||
(arts, dropped)
|
||||
};
|
||||
let mut used = paint_bytes;
|
||||
let (arts, dropped) = draw(map_art.is_some(), &mut used);
|
||||
if dropped { draw(false, &mut paint_bytes).0 } else { arts }
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
.into_iter();
|
||||
// Which surfaces lie over an underlay of their facets, in one order or whole
|
||||
// ([`in_one_order`], [`underlaid_surface`]).
|
||||
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
|
||||
@@ -2061,7 +2122,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
|
||||
};
|
||||
let drawn = parts.iter().any(|p| !p.is_empty());
|
||||
let art = if classic {
|
||||
classic::surface(n, f, &paint, opacity, blend, &p)
|
||||
classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![]))
|
||||
} else {
|
||||
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)
|
||||
@@ -2391,28 +2452,7 @@ pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option<usize>,
|
||||
/// 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())?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
(fx, shapes)
|
||||
} else {
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
match item {
|
||||
None => {
|
||||
let (index, fx) = pick(&n.appearance.effects)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
Some(k) => {
|
||||
let it = n.appearance.items.get(k)?;
|
||||
let (index, fx) = pick(it.effects())?;
|
||||
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
|
||||
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
}
|
||||
};
|
||||
let (fx, shapes) = picked(n, item, pick)?;
|
||||
Some((fx.clone(), shapes))
|
||||
}
|
||||
|
||||
@@ -2459,6 +2499,175 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
|
||||
})
|
||||
}
|
||||
|
||||
/// One numbered surface of a 3D object that takes Map Art: what it is, its size laid out flat in
|
||||
/// points, whether the viewer sees any of it, and the edges of its outline on the page.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MapSurface {
|
||||
pub kind: SurfaceKind,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub visible: bool,
|
||||
pub outline: Vec<[Point; 2]>,
|
||||
}
|
||||
|
||||
/// The numbered surfaces of the 3D effect at `index` of the effects of `n` (on the object itself
|
||||
/// with `item` `None`, else on its fill or stroke `item`), which must be an Extrude & Bevel
|
||||
/// (Classic) or Revolve (Classic), shown or hidden, in the order Map Art numbers them from 1.
|
||||
/// `None` for any other effect, and when the object's art can't be built.
|
||||
pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<Vec<MapSurface>> {
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
let (fx, shapes) = picked(n, item, &|fx: &[Effect]| fx.get(index).filter(|e| takes_map_art(&e.id)).map(|e| (index, e)))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let b = union_bounds(&shapes)?;
|
||||
// The edges of `facets` on each local surface of `surfaces`, in one pass over the facets: every
|
||||
// edge of an end, and the edges of the cells that lie along the sides of the flat surface.
|
||||
let seen = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet]| -> Vec<Vec<[Point; 2]>> {
|
||||
let mut edges: Vec<Vec<[Point; 2]>> = vec![vec![]; surfaces.len()];
|
||||
// Each surface laid out flat, and how near a point must be to its side to lie along it.
|
||||
let frames: Vec<(Rect, f64)> = surfaces
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let flat = match s.kind {
|
||||
SurfaceKind::Side => Rect::new(-s.width / 2.0, -s.height / 2.0, s.width / 2.0, s.height / 2.0),
|
||||
_ => Rect::new(0.0, 0.0, s.width, s.height),
|
||||
};
|
||||
(flat, (s.width.max(s.height) * 1e-6).max(1e-9))
|
||||
})
|
||||
.collect();
|
||||
let ends: Vec<(usize, PlanarFace)> = surfaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(k, s)| match s.kind {
|
||||
SurfaceKind::End(end) => Some((k, end)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for f in facets.iter().filter(|f| !f.away) {
|
||||
if let Some(at) = f.end {
|
||||
for &(k, end) in &ends {
|
||||
if end == at
|
||||
&& let Some(out) = edges.get_mut(k)
|
||||
{
|
||||
for c in &f.contours {
|
||||
out.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(cell) = f.cell.as_deref().filter(|c| c.uv.len() == c.page.len()) else { continue };
|
||||
let k = cell.surface;
|
||||
// A facet of an end adds to an end's surface only its own edges, above.
|
||||
if f.end.is_some() && surfaces.get(k).is_some_and(|s| matches!(s.kind, SurfaceKind::End(_))) {
|
||||
continue;
|
||||
}
|
||||
let (Some(&(flat, near)), Some(out)) = (frames.get(k), edges.get_mut(k)) else { continue };
|
||||
let count = cell.uv.len();
|
||||
for i in 0..count {
|
||||
let j = (i + 1) % count;
|
||||
let (Some(a), Some(c)) = (cell.uv.get(i), cell.uv.get(j)) else { continue };
|
||||
let along = |at: f64, of: fn(&Point) -> f64| (of(a) - at).abs() <= near && (of(c) - at).abs() <= near;
|
||||
let on_side = along(flat.x0, |p| p.x) || along(flat.x1, |p| p.x) || along(flat.y0, |p| p.y) || along(flat.y1, |p| p.y);
|
||||
if let (true, Some(from), Some(to)) = (on_side, cell.page.get(i), cell.page.get(j)) {
|
||||
out.push([*from, *to]);
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
};
|
||||
let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec<MapSurface>| {
|
||||
for (s, outline) in surfaces.iter().zip(seen(surfaces, facets)) {
|
||||
out.push(MapSurface { kind: s.kind, width: s.width, height: s.height, visible: !outline.is_empty(), outline });
|
||||
}
|
||||
};
|
||||
let mut out = vec![];
|
||||
if fx.id == crate::CLASSIC_REVOLVE {
|
||||
// Revolve (Classic) has one surface: its side, in a group that of the member with the
|
||||
// longest profile. A group's members share one sampling of their curves, and a group past
|
||||
// those shared limits has no surface.
|
||||
let mut options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) };
|
||||
if is_container(n) {
|
||||
options = crate::revolve::shared_options(&shapes, options).ok()?;
|
||||
}
|
||||
let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?;
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?;
|
||||
let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }];
|
||||
let facets = vectorcraft_three_d::revolve_facets(&shape.path, b, options).unwrap_or_default();
|
||||
listed(&surfaces, &facets, &mut out);
|
||||
return Some(out);
|
||||
}
|
||||
let (parts, bounds) = solid_parts(&shapes, b);
|
||||
let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) };
|
||||
let view = view_options(&p);
|
||||
// The faces of the solids count together against the limit the art draws within.
|
||||
let mut kept = 0usize;
|
||||
for (_, _, area, rule, _, _) in &parts {
|
||||
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
|
||||
let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default();
|
||||
kept = kept.saturating_add(facets.len());
|
||||
if kept > MAX_OBJECT_FACES {
|
||||
return None;
|
||||
}
|
||||
listed(&surfaces, &facets, &mut out);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`map_surfaces_at`] for `n` as it is with 3D effect `id` and parameters `p` among the effects of
|
||||
/// the object itself (`item` `None`) or of its fill or stroke `item`: in place of the effect at
|
||||
/// `index` when that is an effect `id`, else of the last effect `id` there, or after those effects
|
||||
/// when there is none. A dialog lists the surfaces of the effect it edits with this, whether or not
|
||||
/// its preview has changed the object.
|
||||
pub fn map_surfaces_with(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
(item, index): (Option<usize>, Option<usize>),
|
||||
id: &str,
|
||||
p: &Value,
|
||||
) -> Option<Vec<MapSurface>> {
|
||||
let mut n = n.clone();
|
||||
let effects = n.appearance.effects_mut(item)?;
|
||||
let at = index.filter(|&k| effects.get(k).is_some_and(|e| e.id == id)).or_else(|| effects.iter().rposition(|e| e.id == id));
|
||||
let index = match at {
|
||||
Some(index) => {
|
||||
effects.get_mut(index)?.params = p.clone();
|
||||
index
|
||||
}
|
||||
None => {
|
||||
effects.push(crate::new_effect(id, p)?);
|
||||
effects.len() - 1
|
||||
}
|
||||
};
|
||||
map_surfaces_at(doc, &n, item, index)
|
||||
}
|
||||
|
||||
/// The 3D effect `pick` finds in the effects of `n` (resolved) or of its `item`, with the shapes
|
||||
/// it builds from: the members of a group or layer, or the object's own profile after the geometry
|
||||
/// effects before the 3D effect.
|
||||
fn picked<'n>(n: &'n Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(&'n Effect, Vec<Profile>)> {
|
||||
Some(if is_container(n) {
|
||||
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
|
||||
let mut shapes = members(n, "").ok()?;
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
(fx, shapes)
|
||||
} else {
|
||||
let (path, rule) = profile(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
match item {
|
||||
None => {
|
||||
let (index, fx) = pick(&n.appearance.effects)?;
|
||||
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
|
||||
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
Some(k) => {
|
||||
let it = n.appearance.items.get(k)?;
|
||||
let (index, fx) = pick(it.effects())?;
|
||||
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
|
||||
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
|
||||
pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> {
|
||||
graphics::art_bounds(doc, name)
|
||||
|
||||
@@ -9,6 +9,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
|
||||
|
||||
use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout};
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude";
|
||||
@@ -51,10 +52,21 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
..Bevel::default()
|
||||
}),
|
||||
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
|
||||
// The numbered surfaces are laid out only for an effect that maps art onto them.
|
||||
map_surfaces: !map_art::surface_maps(p).is_empty(),
|
||||
..Extrude::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The mapped art of one solid for [`surface`]: the effect's maps, the solid's place among the
|
||||
/// object's numbered surfaces, and the limits the object's mapped art shares.
|
||||
pub(crate) struct Mapped<'a, 'd> {
|
||||
pub(crate) art: &'a MapArt<'d>,
|
||||
pub(crate) layout: &'a SolidLayout,
|
||||
pub(crate) budget: &'a mut MapBudget,
|
||||
pub(crate) copies: &'a mut usize,
|
||||
}
|
||||
|
||||
/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces
|
||||
/// keep their paint and only the highlight lightens them).
|
||||
fn shading_color(p: &Value) -> Option<Color> {
|
||||
@@ -102,13 +114,15 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"];
|
||||
const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE];
|
||||
|
||||
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
|
||||
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color.
|
||||
/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and
|
||||
/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid
|
||||
/// maps.
|
||||
pub fn validate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)
|
||||
validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?;
|
||||
map_art::validate(CLASSIC_EXTRUDE, p)
|
||||
}
|
||||
|
||||
/// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only).
|
||||
@@ -261,66 +275,67 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's
|
||||
/// coverage; without a placement of its own, it is placed once on all the faces
|
||||
/// ([`crate::lighting::opaque_surface_paint`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
///
|
||||
/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the
|
||||
/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight,
|
||||
/// and Invisible Geometry leaves the faces out: a face is then a group of its art alone. Wireframe
|
||||
/// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid
|
||||
/// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws.
|
||||
///
|
||||
/// Returns the group, whether its faces were left out, and whether `mapped` art was left out past
|
||||
/// the limits.
|
||||
pub(crate) fn surface(
|
||||
n: &Node,
|
||||
facets: &[Facet],
|
||||
source: &Paint,
|
||||
(opacity, blend): (f32, BlendMode),
|
||||
p: &Value,
|
||||
mapped: Option<Mapped<'_, '_>>,
|
||||
hide: bool,
|
||||
) -> (Node, bool, bool) {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let overprint = black_overprint(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(facets)) };
|
||||
let paint = &paint;
|
||||
// The mapped art of each facet, and whether the faces themselves are left out. Art past the
|
||||
// limits is left out, and the faces draw; the copies and the points of art left out do not
|
||||
// count against the art of later solids.
|
||||
let (mut parts, invisible, dropped) = match mapped.filter(|_| !wire) {
|
||||
Some(m) => {
|
||||
let shaded_as = |f: &Facet, c: Color| {
|
||||
let (tone, spec) = shading.tone(f.normal, &lights);
|
||||
shaded(c, tone, spec, shade)
|
||||
};
|
||||
let (mut used, mut budget) = (*m.copies, m.budget.clone());
|
||||
match m.art.parts(n.id, facets, m.layout, &shaded_as, &mut budget, &mut used) {
|
||||
Some(parts) => {
|
||||
(*m.copies, *m.budget) = (used, budget);
|
||||
(parts, m.art.invisible, false)
|
||||
}
|
||||
None => (vec![], false, true),
|
||||
}
|
||||
}
|
||||
None => (vec![], hide && !wire, false),
|
||||
};
|
||||
let children = facets
|
||||
.into_iter()
|
||||
.map(|face| {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, face)| {
|
||||
let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default();
|
||||
if !art.is_empty() || invisible {
|
||||
let drawn = (!invisible).then(|| Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint)));
|
||||
return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect()));
|
||||
}
|
||||
if wire {
|
||||
// A wire edge is drawn as a seam is: a round-joined stroke of the paint.
|
||||
let edge = crate::lighting::seam_stroke(paint.clone(), WIRE);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() }));
|
||||
}
|
||||
let (tone, spec) = shading.tone(face.normal, &lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(&face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }));
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
|
||||
vec![
|
||||
AppearanceItem::Fill(FillLayer::new(paint.clone())),
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
}
|
||||
// Gradients and patterns keep their paint, darkened by a layer of the shading color
|
||||
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
|
||||
// layers cover the whole face, transparent pattern cells included.
|
||||
None => {
|
||||
let mut items = vec![
|
||||
AppearanceItem::Fill(FillLayer::new(paint.clone())),
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
];
|
||||
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
|
||||
if let Some(color) = color.filter(|_| share > 0.0) {
|
||||
let mut layer = FillLayer::new(Paint::solid(color));
|
||||
layer.opacity = share as f32;
|
||||
items.push(AppearanceItem::Fill(layer));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
};
|
||||
Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }))
|
||||
Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint))
|
||||
})
|
||||
.collect();
|
||||
let mut group = Node::group(n.id, children);
|
||||
@@ -331,5 +346,61 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0));
|
||||
group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true)));
|
||||
}
|
||||
group
|
||||
(group, invisible, dropped)
|
||||
}
|
||||
|
||||
/// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency),
|
||||
/// filled in the paint shaded by the face's tone and highlight under `lights`, toward shading
|
||||
/// color `shade`. With `preserve` (Preserve Spot Colors), a color linked to a swatch is drawn as
|
||||
/// [`linked_face`] draws it. With `overprint` (Black Overprint), the face is drawn as
|
||||
/// [`overprinted_face`] draws it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn shaded_face(
|
||||
n: &Node,
|
||||
face: &Facet,
|
||||
paint: &Paint,
|
||||
shading: &ClassicShading,
|
||||
lights: &[([f64; 3], f64)],
|
||||
shade: Option<Color>,
|
||||
preserve: bool,
|
||||
overprint: bool,
|
||||
) -> Node {
|
||||
let (tone, spec) = shading.tone(face.normal, lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Node::path(n.id, face.path(), Appearance { items, ..Default::default() });
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
}
|
||||
// Gradients and patterns keep their paint, darkened by a layer of the shading color
|
||||
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
|
||||
// layers cover the whole face, transparent pattern cells included.
|
||||
None => {
|
||||
let mut items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))];
|
||||
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
|
||||
if let Some(color) = color.filter(|_| share > 0.0) {
|
||||
let mut layer = FillLayer::new(Paint::solid(color));
|
||||
layer.opacity = share as f32;
|
||||
items.push(AppearanceItem::Fill(layer));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
};
|
||||
Node::path(n.id, face.path(), Appearance { items, ..Default::default() })
|
||||
}
|
||||
@@ -170,6 +170,8 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
|
||||
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
|
||||
/// the front. Only Extrude & Bevel takes graphics on its side.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
// Map Art's maps are checked with the graphics: an effect that takes none refuses them.
|
||||
map_art::validate(id, p)?;
|
||||
let list = match p.get(GRAPHICS) {
|
||||
None => return Ok(()),
|
||||
Some(Value::Array(list)) => list,
|
||||
@@ -200,21 +202,23 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol
|
||||
/// was deleted may stay.
|
||||
pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> {
|
||||
let kept = old.map(mapped_graphics).unwrap_or_default();
|
||||
mapped_graphics(p)
|
||||
.into_iter()
|
||||
.map(|g| g.symbol)
|
||||
.find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name))
|
||||
let names = |p: &Value| -> Vec<String> {
|
||||
mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)).collect()
|
||||
};
|
||||
let kept = old.map(names).unwrap_or_default();
|
||||
names(p).into_iter().find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.contains(name))
|
||||
}
|
||||
|
||||
/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol
|
||||
/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as
|
||||
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once.
|
||||
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. The symbols Map
|
||||
/// Art places count with the graphics.
|
||||
pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 };
|
||||
let mut elements = 0usize;
|
||||
for g in mapped_graphics(p) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol));
|
||||
for name in names {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue };
|
||||
let pieces = pieces_of(doc, symbol)?;
|
||||
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
|
||||
if elements > MAX_ELEMENTS {
|
||||
@@ -224,6 +228,30 @@ pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does the art Map Art in `p` places on the surfaces that `unrolled` gives a flat center for (by
|
||||
/// number, from 1; [`map_art::flat_center`]), with the symbols of `doc`, fit the limits as a wall, a
|
||||
/// bevel or Revolve's side draws it: each map's art placed about that center at its scale, cut into
|
||||
/// straight pieces, at most [`MAX_ELEMENTS`] points together and within reach? A map whose symbol
|
||||
/// `doc` does not have is not counted.
|
||||
pub fn validate_unrolled_symbols(doc: &Document, p: &Value, unrolled: &dyn Fn(usize) -> Option<Point>) -> Result<(), String> {
|
||||
const TOO_COMPLEX: &str = "The graphics are too complex: simplify the symbols' art";
|
||||
let mut points = 0usize;
|
||||
for m in map_art::surface_maps(p) {
|
||||
let Some(center) = unrolled(m.surface) else { continue };
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == m.symbol) else { continue };
|
||||
let pieces = pieces_of(doc, symbol)?;
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
let place = m.placement(bounds, center, false);
|
||||
for piece in &pieces {
|
||||
straight_pieces(&(place * piece.path.to_bezpath()), &mut points).ok_or(TOO_COMPLEX)?;
|
||||
}
|
||||
if points > MAX_ELEMENTS {
|
||||
return Err(TOO_COMPLEX.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path elements `path` draws when each curve draws `curve` elements, before curves near the
|
||||
/// eye are split further: one for each straight line, move and close.
|
||||
fn drawn_elements(path: &PathData, curve: usize) -> usize {
|
||||
@@ -844,7 +872,12 @@ pub(crate) fn surface_parts<F: SurfaceFace>(
|
||||
for k in near {
|
||||
let Some(piece) = pieces.get(k) else { continue };
|
||||
let mut path = BezPath::new();
|
||||
// Each contour is cut only where its own bounds reach the triangle.
|
||||
// Each contour is cut only where its own bounds reach the triangle. Each bounds test
|
||||
// counts as one point cut, whether or not the contour reaches it.
|
||||
cut_points = cut_points.saturating_add(piece.boxes.len());
|
||||
if cut_points > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) {
|
||||
if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 {
|
||||
continue;
|
||||
@@ -1225,9 +1258,11 @@ pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> {
|
||||
std::iter::once(&appearance.effects)
|
||||
.chain(appearance.items.iter().map(AppearanceItem::effects))
|
||||
.flatten()
|
||||
.filter(|e| takes_graphics(&e.id))
|
||||
.flat_map(|e| mapped_graphics(&e.params))
|
||||
.map(|g| g.symbol)
|
||||
.filter(|e| takes_graphics(&e.id) || map_art::takes_map_art(&e.id))
|
||||
.flat_map(|e| {
|
||||
let graphics = mapped_graphics(&e.params).into_iter().map(|g| g.symbol).filter(|_| takes_graphics(&e.id));
|
||||
graphics.chain(map_art::surface_maps(&e.params).into_iter().map(|m| m.symbol).filter(|_| map_art::takes_map_art(&e.id)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1247,8 +1282,15 @@ pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str,
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
lists.push(effects);
|
||||
lists.extend(items.iter_mut().map(AppearanceItem::effects_mut));
|
||||
for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) {
|
||||
if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) {
|
||||
for e in lists.into_iter().flatten() {
|
||||
let key = if takes_graphics(&e.id) {
|
||||
GRAPHICS
|
||||
} else if map_art::takes_map_art(&e.id) {
|
||||
map_art::MAP_ART
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Value::Array(list)) = e.params.get_mut(key) {
|
||||
for g in list.iter_mut() {
|
||||
if g.get("symbol").and_then(Value::as_str) == Some(from) {
|
||||
g["symbol"] = json!(to);
|
||||
@@ -1294,6 +1336,9 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
#[path = "map_art.rs"]
|
||||
pub(crate) mod map_art;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_graphics.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
//! Map Art: the art of a document symbol mapped onto the numbered surfaces of Extrude & Bevel
|
||||
//! (Classic) and Revolve (Classic).
|
||||
//!
|
||||
//! The effect keeps its maps in its `mapArt` parameter, each `{surface, symbol, x, y, scaleX,
|
||||
//! scaleY, rotation}`: the surface's number (from 1), the symbol's name, the offset of the art's
|
||||
//! center from the center of the surface laid out flat (points, x to the right and y down as the
|
||||
//! surface is seen from outside the solid), its size as a share of the symbol's own, and its turn
|
||||
//! (degrees, counterclockwise). `mapShade` shades the mapped art with its surface, and
|
||||
//! `mapInvisible` draws the mapped art without the solid's faces.
|
||||
//!
|
||||
//! The surfaces of Extrude & Bevel (Classic) are numbered through its solids in the order they are
|
||||
//! built, each solid's as [`vectorcraft_three_d::extrude_surfaces`] lists them. Revolve (Classic)
|
||||
//! has one surface, its swept side (in a group, the side of the member with the longest profile).
|
||||
//! A map whose number is past the object's surfaces draws nothing.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect};
|
||||
use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View};
|
||||
|
||||
use super::{
|
||||
MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, SURFACE_TOLERANCE, Unrolled, counterclockwise, map_path, pieces_of,
|
||||
straight_pieces, takes_seam, triangle_map,
|
||||
};
|
||||
|
||||
/// The effect parameter that holds the maps.
|
||||
pub const MAP_ART: &str = "mapArt";
|
||||
|
||||
/// The effect parameter of Shade Artwork.
|
||||
pub const MAP_SHADE: &str = "mapShade";
|
||||
|
||||
/// The effect parameter of Invisible Geometry.
|
||||
pub const MAP_INVISIBLE: &str = "mapInvisible";
|
||||
|
||||
/// The most surfaces of one 3D effect that carry a map.
|
||||
pub const MAX_MAPS: usize = 64;
|
||||
|
||||
/// The highest surface number a map may name.
|
||||
pub const MAX_MAP_SURFACE: usize = 100_000;
|
||||
|
||||
/// The error for maps on a 3D effect that takes none.
|
||||
pub const MAP_ART_NOT_TAKEN: &str = "Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)";
|
||||
|
||||
/// The symbol mapped onto one numbered surface of a 3D object.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SurfaceMap {
|
||||
/// The surface's number, from 1.
|
||||
pub surface: usize,
|
||||
pub symbol: String,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
/// Percent of the symbol's own width.
|
||||
pub scale_x: f64,
|
||||
/// Percent of the symbol's own height.
|
||||
pub scale_y: f64,
|
||||
/// Degrees, counterclockwise.
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl SurfaceMap {
|
||||
pub fn to_value(&self) -> Value {
|
||||
json!({
|
||||
"surface": self.surface,
|
||||
"symbol": self.symbol,
|
||||
"x": self.x,
|
||||
"y": self.y,
|
||||
"scaleX": self.scale_x,
|
||||
"scaleY": self.scale_y,
|
||||
"rotation": self.rotation,
|
||||
})
|
||||
}
|
||||
|
||||
/// The map `v` describes. `surface` and `symbol` are required: the offsets and the rotation
|
||||
/// default to 0 and the scales to 100.
|
||||
pub fn from_value(v: &Value) -> Result<Self, String> {
|
||||
let Value::Object(m) = v else { return Err(format!("each of `{MAP_ART}` must be an object")) };
|
||||
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "surface" | "symbol" | "x" | "y" | "scaleX" | "scaleY" | "rotation")) {
|
||||
return Err(format!("`{MAP_ART}` entries take surface, symbol, x, y, scaleX, scaleY and rotation, not `{k}`"));
|
||||
}
|
||||
let surface = m
|
||||
.get("surface")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_MAP_SURFACE).contains(n))
|
||||
.ok_or_else(|| format!("each of `{MAP_ART}` needs `surface`, a whole number from 1 to {MAX_MAP_SURFACE}"))?;
|
||||
let symbol = match m.get("symbol") {
|
||||
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
|
||||
_ => return Err(format!("each of `{MAP_ART}` needs `symbol`, the name of a symbol")),
|
||||
};
|
||||
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
|
||||
match m.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && (lo..=hi).contains(n))
|
||||
.ok_or_else(|| format!("`{MAP_ART}` {key} must be a number from {lo} to {hi}")),
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
surface,
|
||||
symbol,
|
||||
x: number("x", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?,
|
||||
y: number("y", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?,
|
||||
scale_x: number("scaleX", 100.0, super::SCALE_RANGE)?,
|
||||
scale_y: number("scaleY", 100.0, super::SCALE_RANGE)?,
|
||||
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the symbol's art goes on the flat surface, for art whose bounds are `art` on a
|
||||
/// surface with center `center`. With `mirrored` (the back cap) x runs to the right as the
|
||||
/// surface is seen from behind the solid.
|
||||
pub fn placement(&self, art: Rect, center: Point, mirrored: bool) -> Affine {
|
||||
let place = Affine::translate((center.x + self.x, center.y + self.y))
|
||||
* Affine::rotate(-self.rotation.to_radians())
|
||||
* Affine::scale_non_uniform(self.scale_x / 100.0, self.scale_y / 100.0)
|
||||
* Affine::translate(-art.center().to_vec2());
|
||||
if mirrored {
|
||||
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
|
||||
} else {
|
||||
place
|
||||
}
|
||||
}
|
||||
|
||||
/// The scales (percent) at which art with bounds `art`, turned by the map's rotation, fills a
|
||||
/// surface `width` by `height` points: Scale to Fit. `None` for art or a surface with no area.
|
||||
pub fn fitting_scales(&self, art: Rect, (width, height): (f64, f64)) -> Option<(f64, f64)> {
|
||||
let (w, h) = (art.width(), art.height());
|
||||
if w <= 0.0 || h <= 0.0 || width <= 0.0 || height <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// The box of the art turned by the rotation, at its own size.
|
||||
let (sin, cos) = self.rotation.to_radians().sin_cos();
|
||||
let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs());
|
||||
let clamp = |v: f64| v.clamp(super::SCALE_RANGE.0, super::SCALE_RANGE.1);
|
||||
if sin.abs() < 1e-9 || cos.abs() < 1e-9 {
|
||||
// Square to the surface, each side takes its own scale.
|
||||
let (sx, sy) = if cos.abs() >= 0.5 { (width / w, height / h) } else { (height / w, width / h) };
|
||||
return Some((clamp(sx * 100.0), clamp(sy * 100.0)));
|
||||
}
|
||||
let fit = (width / bw).min(height / bh);
|
||||
Some((clamp(fit * 100.0), clamp(fit * 100.0)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D effects that take Map Art: Extrude & Bevel (Classic) and Revolve (Classic).
|
||||
pub fn takes_map_art(id: &str) -> bool {
|
||||
id == super::super::CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE
|
||||
}
|
||||
|
||||
/// The maps in parameters `p`, leaving out entries that are not valid and, of two maps of one
|
||||
/// surface, the later one (a file may hold anything; commands check every entry with
|
||||
/// [`validate`]).
|
||||
pub fn surface_maps(p: &Value) -> Vec<SurfaceMap> {
|
||||
let Some(Value::Array(list)) = p.get(MAP_ART) else { return vec![] };
|
||||
let mut seen = HashSet::new();
|
||||
list.iter().filter_map(|v| SurfaceMap::from_value(v).ok()).filter(|m| seen.insert(m.surface)).take(MAX_MAPS).collect()
|
||||
}
|
||||
|
||||
/// Are the maps in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel (Classic) and
|
||||
/// Revolve (Classic) take maps, at most [`MAX_MAPS`] of them, one for a surface.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
let list = match p.get(MAP_ART) {
|
||||
None => return Ok(()),
|
||||
Some(Value::Array(list)) => list,
|
||||
Some(_) => return Err(format!("`{MAP_ART}` must be an array")),
|
||||
};
|
||||
if list.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !takes_map_art(id) {
|
||||
return Err(MAP_ART_NOT_TAKEN.into());
|
||||
}
|
||||
if list.len() > MAX_MAPS {
|
||||
return Err(format!("`{MAP_ART}` takes at most {MAX_MAPS} maps"));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for v in list {
|
||||
let m = SurfaceMap::from_value(v)?;
|
||||
if !seen.insert(m.surface) {
|
||||
return Err(format!("`{MAP_ART}` maps surface {} more than once", m.surface));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `p` with the map of surface `surface` replaced by `map`, or removed with `None`. The maps stay
|
||||
/// in the order of their surfaces.
|
||||
pub fn with_surface_map(p: &Value, surface: usize, map: Option<&SurfaceMap>) -> Value {
|
||||
let mut maps: Vec<SurfaceMap> = surface_maps(p).into_iter().filter(|m| m.surface != surface).collect();
|
||||
maps.extend(map.cloned());
|
||||
maps.sort_by_key(|m| m.surface);
|
||||
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
|
||||
out.insert(MAP_ART.into(), Value::Array(maps.iter().map(SurfaceMap::to_value).collect()));
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// One solid's place among its object's numbered surfaces: the index of its first surface, its
|
||||
/// surfaces, and for a solid with planar ends the bounds, options and view it was built with.
|
||||
pub(crate) struct SolidLayout {
|
||||
pub(crate) first: usize,
|
||||
pub(crate) surfaces: Vec<SolidSurface>,
|
||||
pub(crate) ends: Option<(Rect, Extrude, View)>,
|
||||
}
|
||||
|
||||
/// What the mapped art of one object has drawn so far, against the limits its maps share.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct MapBudget {
|
||||
elements: usize,
|
||||
/// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`].
|
||||
input: usize,
|
||||
/// The points the maps' art draws on the faces, against [`MAX_SURFACE_POINTS`].
|
||||
points: usize,
|
||||
cuts: usize,
|
||||
}
|
||||
|
||||
/// The maps of one 3D effect, with the document whose symbols they place.
|
||||
pub(crate) struct MapArt<'a> {
|
||||
doc: &'a Document,
|
||||
maps: Vec<SurfaceMap>,
|
||||
/// Shade Artwork: the mapped art takes the shading of its surface.
|
||||
pub(crate) shade: bool,
|
||||
/// Invisible Geometry: only the mapped art is drawn.
|
||||
pub(crate) invisible: bool,
|
||||
}
|
||||
|
||||
impl<'a> MapArt<'a> {
|
||||
/// The maps of 3D effect `id` with parameters `p`. `None` without a document, for an effect
|
||||
/// that takes no maps and for one that has none.
|
||||
pub(crate) fn of(doc: Option<&'a Document>, id: &str, p: &Value) -> Option<Self> {
|
||||
let maps = surface_maps(p);
|
||||
let flag = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false);
|
||||
(takes_map_art(id) && !maps.is_empty()).then_some(Self { doc: doc?, maps, shade: flag(MAP_SHADE), invisible: flag(MAP_INVISIBLE) })
|
||||
}
|
||||
|
||||
fn map_of(&self, index: usize) -> Option<&SurfaceMap> {
|
||||
self.maps.iter().find(|m| m.surface == index + 1)
|
||||
}
|
||||
|
||||
/// The mapped art that falls on each of `facets`, one solid's facets in drawing order, for an
|
||||
/// object with id `id`: for each facet, the nodes to draw right after it. Only facets turned
|
||||
/// toward the viewer carry art. `shade` gives a color as its facet shades it, for Shade
|
||||
/// Artwork. A map whose symbol the document does not have, or whose art is past the limits of
|
||||
/// a graphic's art, draws nothing. `None` when the art is past the limits the maps of one
|
||||
/// object share, or the copies of its paints take `copies` past the object's allowance: the
|
||||
/// solid then draws without mapped art.
|
||||
pub(crate) fn parts(
|
||||
&self,
|
||||
id: NodeId,
|
||||
facets: &[Facet],
|
||||
layout: &SolidLayout,
|
||||
shade: &dyn Fn(&Facet, Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Vec<Arc<Node>>>> {
|
||||
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; facets.len()];
|
||||
let mut flat: HashMap<usize, Vec<Unrolled>> = HashMap::new();
|
||||
for (f, parts) in facets.iter().zip(out.iter_mut()) {
|
||||
if f.away {
|
||||
continue;
|
||||
}
|
||||
let recolor = |c: Color| if self.shade { shade(f, c) } else { c };
|
||||
if let Some(end) = f.end {
|
||||
let Some(local) = layout.surfaces.iter().position(|s| s.kind == SurfaceKind::End(end)) else { continue };
|
||||
let (Some(m), Some(center)) = (self.map_of(layout.first + local), layout.surfaces.get(local).and_then(|s| s.center)) else {
|
||||
continue;
|
||||
};
|
||||
let Some((bounds, options, view)) = layout.ends else { continue };
|
||||
let Some(map) = vectorcraft_three_d::extrude_face_map(bounds, options, view, end) else { continue };
|
||||
parts.extend(self.end_art(id, m, (end, &map), center, f, &recolor, budget, copies)?);
|
||||
} else if let Some(cell) = f.cell.as_deref() {
|
||||
let (Some(m), Some(surface)) = (self.map_of(layout.first + cell.surface), layout.surfaces.get(cell.surface)) else { continue };
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = flat.entry(cell.surface) {
|
||||
e.insert(self.unrolled(m, surface, budget)?);
|
||||
}
|
||||
let Some(pieces) = flat.get(&cell.surface) else { continue };
|
||||
parts.extend(cell_art(id, pieces, cell, f, &recolor, budget, copies)?);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The art of map `m` on planar end `end` of a solid, drawn on its facet `f` through `map`,
|
||||
/// for an end whose bounds have center `center`: one clipping group, as a graphic on a cap is
|
||||
/// drawn. `None` past the limits.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn end_art(
|
||||
&self,
|
||||
id: NodeId,
|
||||
m: &SurfaceMap,
|
||||
(end, map): (PlanarFace, &FaceMap),
|
||||
center: Point,
|
||||
f: &Facet,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Arc<Node>>> {
|
||||
let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) };
|
||||
let Ok(pieces) = pieces_of(self.doc, symbol) else { return Some(vec![]) };
|
||||
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) };
|
||||
let place = m.placement(bounds, center, end == PlanarFace::Back);
|
||||
let affine = map.local_affine(center).filter(|_| map.is_affine());
|
||||
// Gradients follow the end's map as it is near the art's center, or near the middle of the
|
||||
// part in front of the eye when the center is not.
|
||||
let local = map.local_affine(place * bounds.center()).or_else(|| {
|
||||
let part = map.mapped_part(place.transform_rect_bbox(bounds))?;
|
||||
let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2());
|
||||
map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64))
|
||||
});
|
||||
let Some(local) = local else { return Some(vec![]) };
|
||||
let gradient_map = local * place;
|
||||
let mut children = vec![];
|
||||
for piece in pieces {
|
||||
let placed = piece.path.transformed(place);
|
||||
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
|
||||
let before = budget.elements;
|
||||
if before.saturating_add(least) > MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
let room = MAX_ELEMENTS - before;
|
||||
let mut rule = piece.rule;
|
||||
let mapped = match map_path(&placed, map, affine, room) {
|
||||
Err(NotMapped::Behind) => {
|
||||
// Part of it is at or behind the eye: the part in front is drawn.
|
||||
let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue };
|
||||
let Some(&first) = part.first() else { continue };
|
||||
let mut front = BezPath::new();
|
||||
front.move_to(first);
|
||||
part.iter().skip(1).for_each(|p| front.line_to(*p));
|
||||
front.close_path();
|
||||
let cut = vectorcraft_pathops::boolean(
|
||||
&placed,
|
||||
piece.rule,
|
||||
&PathData::from_bezpath(&front),
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
);
|
||||
rule = FillRule::NonZero;
|
||||
map_path(&cut, map, affine, room)
|
||||
}
|
||||
done => done,
|
||||
};
|
||||
let mapped = match mapped {
|
||||
Ok(mapped) => mapped,
|
||||
Err(NotMapped::Full) => return None,
|
||||
Err(NotMapped::Behind) => continue,
|
||||
};
|
||||
budget.elements = before.saturating_add(mapped.elements().len());
|
||||
if !crate::revolve::paint_copies_add(copies, 1, &piece.paint) {
|
||||
return None;
|
||||
}
|
||||
children.push(Arc::new(piece_node(id, piece.paint, (piece.opacity, piece.blend), (mapped, rule), gradient_map, recolor, None)));
|
||||
}
|
||||
if children.is_empty() {
|
||||
return Some(vec![]);
|
||||
}
|
||||
// An end's holes are contours of the same path wound against its outline, so turning the
|
||||
// whole path keeps them holes under the nonzero rule.
|
||||
let mut outline = f.path().to_bezpath();
|
||||
if vectorcraft_geom::kurbo::Shape::area(&outline) < 0.0 {
|
||||
outline = outline.reverse_subpaths();
|
||||
}
|
||||
let clip = Node::path(id, PathData::from_bezpath(&outline), Appearance::default());
|
||||
Some(vec![Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))])
|
||||
}
|
||||
|
||||
/// The areas of map `m`'s symbol placed on `surface` laid out flat, cut into straight pieces.
|
||||
/// Empty for a symbol the document does not have or whose art is past the limits of a
|
||||
/// graphic's art. `None` when the pieces of the object's maps take more than
|
||||
/// [`MAX_ELEMENTS`] points together.
|
||||
fn unrolled(&self, m: &SurfaceMap, surface: &SolidSurface, budget: &mut MapBudget) -> Option<Vec<Unrolled>> {
|
||||
let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) };
|
||||
let Ok(art) = pieces_of(self.doc, symbol) else { return Some(vec![]) };
|
||||
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) };
|
||||
let place = m.placement(bounds, flat_center(surface), false);
|
||||
let mut pieces = vec![];
|
||||
for piece in art {
|
||||
let placed = place * piece.path.to_bezpath();
|
||||
let mut polygons = straight_pieces(&placed, &mut budget.input)?;
|
||||
polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite()));
|
||||
let boxes: Vec<Rect> = polygons.iter().filter_map(|polygon| box_of(polygon)).collect();
|
||||
let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue };
|
||||
pieces.push(Unrolled {
|
||||
polygons,
|
||||
boxes,
|
||||
bounds,
|
||||
rule: piece.rule,
|
||||
paint: piece.paint,
|
||||
opacity: piece.opacity,
|
||||
blend: piece.blend,
|
||||
place,
|
||||
});
|
||||
}
|
||||
Some(pieces)
|
||||
}
|
||||
}
|
||||
|
||||
/// The center of `surface` laid out flat, which a map's offset is measured from: the middle of a
|
||||
/// wall or a bevel, whose flat coordinates start at its corner, and the origin of Revolve's side,
|
||||
/// whose flat coordinates start at its middle.
|
||||
pub fn flat_center(surface: &SolidSurface) -> Point {
|
||||
match surface.kind {
|
||||
SurfaceKind::Side => Point::ZERO,
|
||||
SurfaceKind::End(_) => surface.center.unwrap_or(Point::ZERO),
|
||||
SurfaceKind::Wall | SurfaceKind::Bevel => Point::new(surface.width / 2.0, surface.height / 2.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn box_of(points: &[Point]) -> Option<Rect> {
|
||||
points.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// A map from a region of a flat surface onto the page.
|
||||
enum Mapper {
|
||||
Affine(Affine),
|
||||
/// The projective map that takes the rectangle with corner `origin` and size `size` onto a
|
||||
/// quadrilateral: `rows` are its coefficients on the unit square.
|
||||
Quad {
|
||||
origin: Point,
|
||||
size: (f64, f64),
|
||||
rows: [f64; 8],
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapper {
|
||||
fn at(&self, p: Point) -> Point {
|
||||
match self {
|
||||
Mapper::Affine(a) => *a * p,
|
||||
Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => {
|
||||
let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1);
|
||||
let w = g * u + h * v + 1.0;
|
||||
Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The point of the flat surface this map takes to `p` on the page. `None` where there is none.
|
||||
fn back(&self, p: Point) -> Option<Point> {
|
||||
let q = match self {
|
||||
Mapper::Affine(a) => a.inverse() * p,
|
||||
Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => {
|
||||
// x (g u + h v + 1) = a u + b v + c, and the same for y, solved for u and v.
|
||||
let (m00, m01, r0) = (a - g * p.x, b - h * p.x, p.x - c);
|
||||
let (m10, m11, r1) = (d - g * p.y, e - h * p.y, p.y - f);
|
||||
let det = m00 * m11 - m01 * m10;
|
||||
let (u, v) = ((r0 * m11 - m01 * r1) / det, (m00 * r1 - r0 * m10) / det);
|
||||
Point::new(origin.x + u * size.0, origin.y + v * size.1)
|
||||
}
|
||||
};
|
||||
q.is_finite().then_some(q)
|
||||
}
|
||||
|
||||
/// The affine map nearest this one around `p`, for gradients and patterns.
|
||||
fn local(&self, p: Point, step: f64) -> Affine {
|
||||
match self {
|
||||
Mapper::Affine(a) => *a,
|
||||
Mapper::Quad { .. } => {
|
||||
let (o, x, y) = (self.at(p), self.at(Point::new(p.x + step, p.y)), self.at(Point::new(p.x, p.y + step)));
|
||||
let (dx, dy) = ((x - o) / step, (y - o) / step);
|
||||
Affine::new([dx.x, dx.y, dy.x, dy.y, o.x - dx.x * p.x - dy.x * p.y, o.y - dx.y * p.x - dy.y * p.y])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The projective map of `cell`, a cell whose flat corners are those of an upright rectangle, in
|
||||
/// order along its edge nearest the origin and back: exact for a flat wall under a perspective. `None`
|
||||
/// for any other cell and for a quadrilateral the map turns inside out.
|
||||
fn quad_mapper(cell: &MapCell) -> Option<(Vec<Point>, Mapper)> {
|
||||
let [mut u0, mut u1, mut u2, mut u3] = <[Point; 4]>::try_from(cell.uv.as_slice()).ok()?;
|
||||
let [mut p0, mut p1, mut p2, mut p3] = <[Point; 4]>::try_from(cell.page.as_slice()).ok()?;
|
||||
// A cell whose first edge runs from right to left is read from its other end.
|
||||
if u1.x < u0.x {
|
||||
(u0, u1, u2, u3) = (u1, u0, u3, u2);
|
||||
(p0, p1, p2, p3) = (p1, p0, p3, p2);
|
||||
}
|
||||
let size = (u1.x - u0.x, u3.y - u0.y);
|
||||
let upright = u1.y == u0.y && u2.x == u1.x && u2.y == u3.y && u3.x == u0.x && size.0 > 1e-9 && size.1 > 1e-9;
|
||||
if !upright {
|
||||
return None;
|
||||
}
|
||||
let (dx1, dx2, sx) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x);
|
||||
let (dy1, dy2, sy) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y);
|
||||
let den = dx1 * dy2 - dx2 * dy1;
|
||||
let scale = dx1.abs() + dx2.abs() + dy1.abs() + dy2.abs();
|
||||
if den.is_nan() || den.abs() <= 1e-12 * scale * scale {
|
||||
return None;
|
||||
}
|
||||
let (g, h) = ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den);
|
||||
let rows = [p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x, p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y, g, h];
|
||||
let inside = g + 1.0 > 1e-6 && h + 1.0 > 1e-6 && g + h + 1.0 > 1e-6;
|
||||
(inside && rows.iter().all(|v| v.is_finite())).then(|| (vec![u0, u1, u2, u3], Mapper::Quad { origin: u0, size, rows }))
|
||||
}
|
||||
|
||||
/// The regions of `cell` on its flat surface, each a convex polygon wound as [`clip_convex`] reads
|
||||
/// it, with its map onto the page: the whole of an upright rectangle ([`quad_mapper`]), else the
|
||||
/// triangles the cell is cut into.
|
||||
fn regions(cell: &MapCell) -> Vec<(Vec<Point>, Mapper)> {
|
||||
if let Some(quad) = quad_mapper(cell) {
|
||||
return vec![quad];
|
||||
}
|
||||
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
|
||||
triangles
|
||||
.iter()
|
||||
.filter_map(|corners| {
|
||||
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
|
||||
let (uv, page) = (pick(&cell.uv)?, pick(&cell.page)?);
|
||||
Some((counterclockwise(&uv)?.to_vec(), Mapper::Affine(triangle_map(&uv, &page)?)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for
|
||||
/// each of its edges), wound so that its inside is on the positive side of each edge.
|
||||
fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec<Point> {
|
||||
let mut out = polygon.to_vec();
|
||||
for (k, &a) in window.iter().enumerate() {
|
||||
let Some(&b) = window.get((k + 1) % window.len()) else { continue };
|
||||
let side = |p: Point| (b - a).cross(p - a);
|
||||
let input = std::mem::take(&mut out);
|
||||
for (i, &p) in input.iter().enumerate() {
|
||||
let Some(&q) = input.get((i + 1) % input.len()) else { continue };
|
||||
let (sp, sq) = (side(p), side(q));
|
||||
if sp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (sp >= 0.0) != (sq >= 0.0) {
|
||||
out.push(p.lerp(q, sp / (sp - sq)));
|
||||
}
|
||||
}
|
||||
if out.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far `p` lies outside the convex `polygon`, wound with its inside on the positive side of each
|
||||
/// edge, across the edges for which `counts` holds: 0 or less when it lies inside them.
|
||||
fn beyond(polygon: &[Point], p: Point, counts: &dyn Fn(Point, Point) -> bool) -> f64 {
|
||||
let mut most = f64::NEG_INFINITY;
|
||||
for (k, &a) in polygon.iter().enumerate() {
|
||||
let Some(&b) = polygon.get((k + 1) % polygon.len()) else { continue };
|
||||
let length = (b - a).hypot();
|
||||
if length > 0.0 && counts(a, b) {
|
||||
most = most.max(-(b - a).cross(p - a) / length);
|
||||
}
|
||||
}
|
||||
most
|
||||
}
|
||||
|
||||
/// `regions` of `cell` ([`regions`]) with the edges they share with the cell's own outline moved out
|
||||
/// on the flat surface, far enough that their maps reach the outline of facet `f` where its curved
|
||||
/// edges bow out of the cell: each outline point is taken back onto the flat surface through the
|
||||
/// region's own map. The edge between two triangles stays, so the regions do not overlap. A region
|
||||
/// moves out at most four times the size of the cell, and one whose projective map would turn
|
||||
/// inside out where it reaches stays as it is. Without a curved outline, or where the outline stays
|
||||
/// inside the cell, the regions are returned unchanged.
|
||||
fn reaching_outline(regions: Vec<(Vec<Point>, Mapper)>, cell: &MapCell, f: &Facet) -> Vec<(Vec<Point>, Mapper)> {
|
||||
let Some(outline) = f.outline.as_ref() else { return regions };
|
||||
let Some(uv) = box_of(&cell.uv) else { return regions };
|
||||
// The cell on the page, wound with its inside on the positive side of each edge.
|
||||
let mut around = cell.page.clone();
|
||||
let turn: f64 = around.iter().zip(around.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum();
|
||||
if turn < 0.0 {
|
||||
around.reverse();
|
||||
}
|
||||
// The points of the outline that lie outside the cell on the page, or near enough that the
|
||||
// curve between them may: the curve strays from its flattened points by up to the tolerance,
|
||||
// so each point counts as the corners of a square of that half width around it.
|
||||
let mut out = vec![];
|
||||
let outline = outline.to_bezpath();
|
||||
let t = SURFACE_TOLERANCE;
|
||||
vectorcraft_geom::kurbo::flatten(outline.elements().iter().copied(), t, |el| {
|
||||
if let vectorcraft_geom::kurbo::PathEl::MoveTo(p) | vectorcraft_geom::kurbo::PathEl::LineTo(p) = el
|
||||
&& beyond(&around, p, &|_, _| true) > -2.0 * t
|
||||
{
|
||||
out.extend([(t, t), (t, -t), (-t, t), (-t, -t)].map(|(x, y)| p + vectorcraft_geom::Vec2::new(x, y)));
|
||||
}
|
||||
});
|
||||
if out.is_empty() {
|
||||
return regions;
|
||||
}
|
||||
let most = 4.0 * uv.width().hypot(uv.height());
|
||||
let on_outline = |a: Point, b: Point| {
|
||||
let at = |q: Point| cell.uv.iter().position(|u| *u == q);
|
||||
let count = cell.uv.len();
|
||||
matches!((at(a), at(b)), (Some(i), Some(j)) if (i + 1) % count == j || (j + 1) % count == i)
|
||||
};
|
||||
regions
|
||||
.into_iter()
|
||||
.map(|(window, mapper)| {
|
||||
let reach = out.iter().filter_map(|p| mapper.back(*p)).map(|q| beyond(&window, q, &on_outline)).fold(0.0f64, f64::max);
|
||||
if reach <= 0.0 {
|
||||
return (window, mapper);
|
||||
}
|
||||
// A little past the farthest point, so the cut to the outline meets it.
|
||||
let reach = (reach * 1.01 + 1e-9).min(most);
|
||||
let grown = grown_window(&window, reach, &on_outline);
|
||||
let holds = match &mapper {
|
||||
Mapper::Affine(_) => true,
|
||||
Mapper::Quad { origin, size, rows } => grown.iter().all(|p| {
|
||||
let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1);
|
||||
rows[6] * u + rows[7] * v + 1.0 > 1e-6
|
||||
}),
|
||||
};
|
||||
(if holds && grown.len() == window.len() { grown } else { window }, mapper)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The convex `window`, wound as [`clip_convex`] reads it, with each edge for which `moves` holds
|
||||
/// moved out by `by`, and its corners where the moved edges meet.
|
||||
fn grown_window(window: &[Point], by: f64, moves: &dyn Fn(Point, Point) -> bool) -> Vec<Point> {
|
||||
let count = window.len();
|
||||
// Each edge as a point on its line and its direction, moved out where it moves.
|
||||
let lines: Vec<(Point, vectorcraft_geom::Vec2)> = (0..count)
|
||||
.filter_map(|k| {
|
||||
let (a, b) = (*window.get(k)?, *window.get((k + 1) % count)?);
|
||||
let d = b - a;
|
||||
let length = d.hypot();
|
||||
let out = if moves(a, b) && length > 0.0 { vectorcraft_geom::Vec2::new(d.y, -d.x) * (by / length) } else { vectorcraft_geom::Vec2::ZERO };
|
||||
Some((a + out, d))
|
||||
})
|
||||
.collect();
|
||||
(0..count)
|
||||
.filter_map(|k| {
|
||||
let ((p1, d1), (p2, d2)) = (*lines.get((k + count - 1) % count)?, *lines.get(k)?);
|
||||
let den = d1.cross(d2);
|
||||
if den.abs() <= 1e-12 * d1.hypot() * d2.hypot() {
|
||||
return Some(p2);
|
||||
}
|
||||
let t = (p2 - p1).cross(d2) / den;
|
||||
let p = p1 + d1 * t;
|
||||
p.is_finite().then_some(p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet
|
||||
/// `f`, drawn on the page. `None` past the limits.
|
||||
fn cell_art(
|
||||
id: NodeId,
|
||||
pieces: &[Unrolled],
|
||||
cell: &MapCell,
|
||||
f: &Facet,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
budget: &mut MapBudget,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Arc<Node>>> {
|
||||
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
|
||||
return Some(vec![]);
|
||||
}
|
||||
let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) };
|
||||
// A facet cut after it was built, or one whose edges follow the profile's curves, draws only the
|
||||
// part of the art inside its own outline, which the regions reach where it bows out of the cell.
|
||||
let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page);
|
||||
let regions = if whole { regions(cell) } else { reaching_outline(regions(cell), cell, f) };
|
||||
let within = regions.iter().filter_map(|(w, _)| box_of(w)).fold(reach, |a, b| a.union(b));
|
||||
let apart = |b: &Rect| b.x1 < within.x0 || b.x0 > within.x1 || b.y1 < within.y0 || b.y0 > within.y1;
|
||||
let mut out = vec![];
|
||||
for piece in pieces.iter().filter(|p| !apart(&p.bounds)) {
|
||||
// Each contour's bounds test counts as one point cut, whether or not the contour reaches
|
||||
// the cell.
|
||||
budget.cuts = budget.cuts.saturating_add(piece.boxes.len());
|
||||
if budget.cuts > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
let near: Vec<&Vec<Point>> = piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)).map(|(p, _)| p).collect();
|
||||
let mut path = BezPath::new();
|
||||
for (window, mapper) in ®ions {
|
||||
for polygon in &near {
|
||||
budget.cuts = budget.cuts.saturating_add(polygon.len());
|
||||
if budget.cuts > MAX_SURFACE_CUTS {
|
||||
return None;
|
||||
}
|
||||
let cut = clip_convex(polygon, window);
|
||||
let Some((first, rest)) = cut.split_first() else { continue };
|
||||
path.move_to(mapper.at(*first));
|
||||
rest.iter().for_each(|q| path.line_to(mapper.at(*q)));
|
||||
path.close_path();
|
||||
budget.points = budget.points.saturating_add(cut.len());
|
||||
}
|
||||
}
|
||||
if budget.points > MAX_SURFACE_POINTS {
|
||||
return None;
|
||||
}
|
||||
if path.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (path, rule) = if whole {
|
||||
(path, piece.rule)
|
||||
} else {
|
||||
let cut = vectorcraft_pathops::boolean(
|
||||
&PathData::from_bezpath(&path),
|
||||
piece.rule,
|
||||
&f.path(),
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
);
|
||||
(cut.to_bezpath(), FillRule::NonZero)
|
||||
};
|
||||
if path.elements().is_empty() || !path.elements().iter().all(el_is_finite) {
|
||||
continue;
|
||||
}
|
||||
let seam = takes_seam(piece);
|
||||
if !crate::revolve::paint_copies_add(copies, 1 + usize::from(seam), &piece.paint) {
|
||||
return None;
|
||||
}
|
||||
// Gradients and patterns follow the cell's map as it is at the cell's middle.
|
||||
let middle = reach.center();
|
||||
let local = regions.first().map_or(Affine::IDENTITY, |(_, m)| m.local(middle, (reach.width().max(reach.height()) * 1e-3).max(1e-6)));
|
||||
let node = piece_node(
|
||||
id,
|
||||
piece.paint.clone(),
|
||||
(piece.opacity, piece.blend),
|
||||
(path, rule),
|
||||
local * piece.place,
|
||||
recolor,
|
||||
seam.then_some(SURFACE_SEAM),
|
||||
);
|
||||
out.push(Arc::new(node));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn el_is_finite(el: &vectorcraft_geom::kurbo::PathEl) -> bool {
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
match *el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => p.is_finite(),
|
||||
PathEl::QuadTo(a, p) => a.is_finite() && p.is_finite(),
|
||||
PathEl::CurveTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(),
|
||||
PathEl::ClosePath => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// One painted area of mapped art on the page: `path` filled under `rule` with `paint`, its
|
||||
/// gradients and pattern tiles placed through `gradient_map`, its colors through `recolor`, and
|
||||
/// with `seam` a stroke of that width in the same paint over the seams between neighboring parts.
|
||||
fn piece_node(
|
||||
id: NodeId,
|
||||
mut paint: Paint,
|
||||
(opacity, blend): (f32, vectorcraft_doc::color::BlendMode),
|
||||
(path, rule): (BezPath, FillRule),
|
||||
gradient_map: Affine,
|
||||
recolor: &dyn Fn(Color) -> Color,
|
||||
seam: Option<f64>,
|
||||
) -> Node {
|
||||
if let Paint::Pattern { xf, .. } = &mut paint {
|
||||
*xf = gradient_map * *xf;
|
||||
}
|
||||
let mut fill = FillLayer::new(paint);
|
||||
fill.opacity = opacity;
|
||||
fill.blend = blend;
|
||||
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
|
||||
appearance.transform_gradients(gradient_map);
|
||||
for item in appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Fill(f) = item {
|
||||
// Pattern tiles keep their colors: the document's pattern draws them.
|
||||
vectorcraft_doc::recolor::map_paint(&mut f.paint, recolor);
|
||||
}
|
||||
}
|
||||
if let (Some(width), Some(AppearanceItem::Fill(f))) = (seam, appearance.items.first()) {
|
||||
let mut stroke = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), width);
|
||||
stroke.join = vectorcraft_doc::LineJoin::Round;
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
}
|
||||
let mut node = Node::path(id, PathData::from_bezpath(&path), appearance);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
|
||||
*r = rule;
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_map_art.rs"]
|
||||
mod tests;
|
||||
@@ -776,6 +776,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
|
||||
end: None,
|
||||
surface: None,
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
cell: 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.
|
||||
|
||||
@@ -186,6 +186,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() {
|
||||
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 }),
|
||||
cell: None,
|
||||
}
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Symbol;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::super::super::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, MapSurface, map_surfaces_at, solid_art_in, validate_three_d_at_in, validate_three_d_in};
|
||||
use super::*;
|
||||
use crate::CLASSIC_REVOLVE;
|
||||
|
||||
const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
|
||||
const GREEN: Color = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
|
||||
const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 };
|
||||
|
||||
fn square(id: u64, r: Rect, c: Color) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A document with symbol "Mark", a red 10 × 10 square, and symbol "Corner", 30 × 30: a red square
|
||||
/// at its top left, a blue one to the right of it and a green one below it.
|
||||
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), RED)) });
|
||||
let corner = Node::group(
|
||||
NodeId(0),
|
||||
vec![
|
||||
Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), RED)),
|
||||
Arc::new(square(0, Rect::new(20.0, 0.0, 30.0, 10.0), BLUE)),
|
||||
Arc::new(square(0, Rect::new(0.0, 20.0, 10.0, 30.0), GREEN)),
|
||||
],
|
||||
);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Corner".into(), art: Arc::new(corner) });
|
||||
d
|
||||
}
|
||||
|
||||
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
|
||||
/// straight on with No Shading.
|
||||
fn object(id: &str, params: Value) -> Node {
|
||||
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "surface": "none"});
|
||||
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), Color::rgb(0.5, 0.5, 0.5));
|
||||
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
/// The paths of `art` filled with color `c`, in drawing order.
|
||||
fn filled(art: &Node, c: Color) -> Vec<PathData> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let fill = n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color(),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if fill.is_some_and(|f| f.to_rgb().iter().zip(c.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4))
|
||||
&& let Some(p) = n.path_data()
|
||||
{
|
||||
out.push(p.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn bounds_of(paths: &[PathData]) -> Rect {
|
||||
paths.iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
fn close(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)
|
||||
}
|
||||
|
||||
fn surfaces(n: &Node) -> Vec<MapSurface> {
|
||||
map_surfaces_at(Some(&document()), n, None, 0).unwrap()
|
||||
}
|
||||
|
||||
/// Which way round the "Corner" symbol reads in `art`: positive when its blue square is to the
|
||||
/// right of its red one and its green one below, as the symbol is drawn, at any turn; negative
|
||||
/// when it is mirrored.
|
||||
fn handedness(art: &Node) -> f64 {
|
||||
let at = |c: Color| bounds_of(&filled(art, c)).center();
|
||||
(at(BLUE) - at(RED)).cross(at(GREEN) - at(RED))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() {
|
||||
let kinds = |n: &Node| surfaces(n).iter().map(|s| s.kind).collect::<Vec<_>>();
|
||||
let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back));
|
||||
let solid = object(CLASSIC_EXTRUDE, json!({}));
|
||||
assert_eq!(kinds(&solid), [vec![front, back], vec![SurfaceKind::Wall; 4]].concat());
|
||||
// Each wall runs from corner to corner of the square and is as deep as the solid.
|
||||
for wall in surfaces(&solid).iter().skip(2) {
|
||||
assert!((wall.width - 100.0).abs() < 1e-6 && (wall.height - 50.0).abs() < 1e-6, "{wall:?}");
|
||||
}
|
||||
assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"cap": false}))), vec![SurfaceKind::Wall; 4]);
|
||||
let beveled = object(CLASSIC_EXTRUDE, json!({"bevel": "classic"}));
|
||||
assert_eq!(kinds(&beveled), [vec![front, back], vec![SurfaceKind::Wall; 4], vec![SurfaceKind::Bevel; 4]].concat());
|
||||
// With no depth the art is a plane, which has its front only.
|
||||
assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"depth": 0}))), vec![front]);
|
||||
// An outline with no corner has one wall.
|
||||
let mut round = Node::path(NodeId(7), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
round.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({})).unwrap());
|
||||
assert_eq!(kinds(&round), vec![front, back, SurfaceKind::Wall]);
|
||||
// Revolve (Classic) has its side, and Rotate (Classic) takes no maps.
|
||||
assert_eq!(kinds(&object(CLASSIC_REVOLVE, json!({}))), vec![SurfaceKind::Side]);
|
||||
assert_eq!(map_surfaces_at(Some(&document()), &object(CLASSIC_ROTATE, json!({})), None, 0), None);
|
||||
// Seen straight on, only the front cap is turned toward the viewer.
|
||||
let seen: Vec<bool> = surfaces(&solid).iter().map(|s| s.visible).collect();
|
||||
assert_eq!(seen, [true, false, false, false, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bevel_as_deep_as_the_solid_leaves_no_walls_and_its_bevels_take_their_maps() {
|
||||
let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back));
|
||||
let solid = |maps: Value| object(CLASSIC_EXTRUDE, json!({"depth": 10, "bevel": "classic", "bevelHeight": 10, "mapArt": maps}));
|
||||
let kinds: Vec<SurfaceKind> = surfaces(&solid(json!([]))).iter().map(|s| s.kind).collect();
|
||||
assert_eq!(kinds, [vec![front, back], vec![SurfaceKind::Bevel; 4]].concat());
|
||||
// Seen straight on, the front bevels draw the art mapped onto them.
|
||||
let bevels: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
let art = solid_art_in(Some(&document()), &solid(json!(bevels))).unwrap();
|
||||
assert!(!filled(&art, RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() {
|
||||
let d = document();
|
||||
let map = |m: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": [m]}))).unwrap();
|
||||
// Without a map nothing red is drawn.
|
||||
assert!(filled(&solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({}))).unwrap(), RED).is_empty());
|
||||
// The art's center is at the center of the cap, its size the symbol's own.
|
||||
let centered = filled(&map(json!({"surface": 1, "symbol": "Mark"})), RED);
|
||||
assert!(close(bounds_of(¢ered), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds_of(¢ered));
|
||||
// An offset moves it, and each scale sizes one side.
|
||||
let moved = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 10, "y": -5, "scaleX": 200, "scaleY": 300})), RED);
|
||||
assert!(close(bounds_of(&moved), Rect::new(50.0, 30.0, 70.0, 60.0)), "{:?}", bounds_of(&moved));
|
||||
// A quarter turn swaps the sides.
|
||||
let turned = filled(&map(json!({"surface": 1, "symbol": "Mark", "scaleX": 200, "rotation": 90})), RED);
|
||||
assert!(close(bounds_of(&turned), Rect::new(45.0, 40.0, 55.0, 60.0)), "{:?}", bounds_of(&turned));
|
||||
// The art is clipped to the cap.
|
||||
let past = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 50})), RED);
|
||||
assert_eq!(past.len(), 1);
|
||||
let art = map(json!({"surface": 1, "symbol": "Mark", "x": 50}));
|
||||
let mut clipped = false;
|
||||
art.walk(&mut |n| clipped |= matches!(&n.kind, NodeKind::Group { clip: true, .. }));
|
||||
assert!(clipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_a_side_wall_reads_the_right_way_round_from_outside() {
|
||||
let d = document();
|
||||
let all_walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect();
|
||||
for turn in [-90.0, 90.0] {
|
||||
// Seen from one side, one wall faces the viewer: it alone carries its map.
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": turn, "mapArt": all_walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
assert_eq!(filled(&art, RED).len(), 1, "one wall is seen at {turn}");
|
||||
// The wall is 100 along the outline and 50 deep: the art keeps its size at its middle.
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "{whole:?}");
|
||||
assert!((whole.center().x - 50.0).abs() < 1e-6 && (whole.center().y - 50.0).abs() < 1e-6, "{whole:?}");
|
||||
assert!(handedness(&art) > 0.0, "the art is mirrored at {turn}");
|
||||
}
|
||||
// The walls seen from above and below read the right way round too.
|
||||
for turn in [-90.0, 90.0] {
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationX": turn, "mapArt": all_walls}));
|
||||
assert!(handedness(&solid_art_in(Some(&d), &n).unwrap()) > 0.0, "the art is mirrored at {turn}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_beside_a_bevel_is_laid_out_at_its_own_length() {
|
||||
let d = document();
|
||||
// A bevel 10 wide added around the square sets each wall 10 out, so each wall is 120 long; a
|
||||
// bevel takes the length of the wall it sits above. Carved in, the walls are the square's own.
|
||||
for (inside, length) in [(false, 120.0), (true, 100.0)] {
|
||||
let solid = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside}));
|
||||
for side in surfaces(&solid).iter().skip(2) {
|
||||
assert!((side.width - length).abs() < 1e-6, "inside {inside}: {side:?}");
|
||||
}
|
||||
// Seen from one side, the art on the wall that faces the viewer keeps its size.
|
||||
let walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside, "rotationY": 90, "mapArt": walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "inside {inside}: {whole:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
// The facet's top edge follows a curve that bows into the quad, down to y = 2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.curve_to((10.0 / 3.0, 8.0 / 3.0), (20.0 / 3.0, 8.0 / 3.0), (10.0, 0.0));
|
||||
curved.line_to((10.0, 10.0));
|
||||
curved.line_to((0.0, 10.0));
|
||||
curved.close_path();
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: Some(PathData::from_bezpath(&curved)),
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() };
|
||||
let whole = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
let art = Unrolled {
|
||||
polygons: vec![quad],
|
||||
boxes: vec![whole],
|
||||
bounds: whole,
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let (mut budget, mut copies) = (MapBudget::default(), 0);
|
||||
let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap();
|
||||
let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum();
|
||||
let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs();
|
||||
assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
// The facet's top edge follows a curve that bows out of the quad, up to y = -2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.curve_to((10.0 / 3.0, -8.0 / 3.0), (20.0 / 3.0, -8.0 / 3.0), (10.0, 0.0));
|
||||
curved.line_to((10.0, 10.0));
|
||||
curved.line_to((0.0, 10.0));
|
||||
curved.close_path();
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: Some(PathData::from_bezpath(&curved)),
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
|
||||
// Art that covers the facet and more.
|
||||
let cover = vec![Point::new(-5.0, -5.0), Point::new(15.0, -5.0), Point::new(15.0, 15.0), Point::new(-5.0, 15.0)];
|
||||
let whole = Rect::new(-5.0, -5.0, 15.0, 15.0);
|
||||
let art = Unrolled {
|
||||
polygons: vec![cover],
|
||||
boxes: vec![whole],
|
||||
bounds: whole,
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let (mut budget, mut copies) = (MapBudget::default(), 0);
|
||||
let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap();
|
||||
let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum();
|
||||
let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs();
|
||||
assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() {
|
||||
let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
let facet = Facet {
|
||||
contours: vec![quad.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
rgb_gradient: None,
|
||||
outline: None,
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: None,
|
||||
surface: None,
|
||||
cell: None,
|
||||
};
|
||||
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
|
||||
// Small contours on either side of the cell: the piece's bounds reach across it, but no
|
||||
// contour's own bounds do.
|
||||
let polygons: Vec<Vec<Point>> = (0..2000)
|
||||
.map(|k| {
|
||||
let x = if k % 2 == 0 { -1000.0 } else { 1000.0 };
|
||||
vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0)]
|
||||
})
|
||||
.collect();
|
||||
let boxes: Vec<Rect> = polygons.iter().filter_map(|p| box_of(p)).collect();
|
||||
let art = Unrolled {
|
||||
polygons,
|
||||
boxes,
|
||||
bounds: Rect::new(-1000.0, 0.0, 1001.0, 1.0),
|
||||
rule: FillRule::NonZero,
|
||||
paint: Paint::solid(RED),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
place: Affine::IDENTITY,
|
||||
};
|
||||
let mut budget = MapBudget { cuts: MAX_SURFACE_CUTS - 10, ..MapBudget::default() };
|
||||
assert!(cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() {
|
||||
let d = document();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 2, "symbol": "Corner"}]}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
// Only the back cap is seen, and it carries its own map's art.
|
||||
assert_eq!(filled(&art, RED).len(), 1);
|
||||
assert_eq!((filled(&art, BLUE).len(), filled(&art, GREEN).len()), (1, 1));
|
||||
assert!(handedness(&art) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_past_the_shared_limits_leaves_out_the_mapped_art_of_every_solid() {
|
||||
let mut d = document();
|
||||
// A zigzag of half the straight sides one 3D effect's mapped art may draw.
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
for i in 1..=MAX_ELEMENTS / 2 {
|
||||
b.line_to((i as f64 * 0.00005, (i % 2) as f64));
|
||||
}
|
||||
b.close_path();
|
||||
let half = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(half) });
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
// A group of two squares: the first solid's front is surface 1, the second's surface 7.
|
||||
let art = |maps: Value, invisible: bool| {
|
||||
let members =
|
||||
vec![Arc::new(square(8, Rect::new(0.0, 0.0, 100.0, 100.0), gray)), Arc::new(square(9, Rect::new(200.0, 0.0, 300.0, 100.0), gray))];
|
||||
let mut g = Node::group(NodeId(7), members);
|
||||
let p = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "mapInvisible": invisible, "mapArt": maps});
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &p).unwrap());
|
||||
solid_art_in(Some(&d), &g).unwrap()
|
||||
};
|
||||
// One solid's art fits.
|
||||
assert!(!filled(&art(json!([{"surface": 1, "symbol": "Half"}]), false), RED).is_empty());
|
||||
// Both together are past the limit: no solid draws its art, and with Invisible Geometry every
|
||||
// solid's faces draw.
|
||||
let both = json!([{"surface": 1, "symbol": "Half"}, {"surface": 7, "symbol": "Half"}]);
|
||||
assert!(filled(&art(both.clone(), false), RED).is_empty());
|
||||
let hidden = art(both, true);
|
||||
assert!(filled(&hidden, RED).is_empty());
|
||||
let faces = bounds_of(&filled(&hidden, gray));
|
||||
assert!(faces.x0 < 1.0 && faces.x1 > 299.0, "{faces:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_under_a_perspective_maps_its_art_whole() {
|
||||
let d = document();
|
||||
let all_walls: Vec<Value> = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
let n = object(CLASSIC_EXTRUDE, json!({"rotationY": -60, "perspectiveAngle": 90, "mapArt": all_walls}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
// The wall is one flat face: the square maps onto it as one four-cornered area, not as two
|
||||
// pieces that meet along the face's diagonal.
|
||||
let marks = filled(&art, RED);
|
||||
assert_eq!(marks.len(), 1);
|
||||
let mark = &marks[0];
|
||||
assert_eq!((mark.subpaths.len(), mark.subpaths[0].anchors.len()), (1, 4), "{mark:?}");
|
||||
// Nearer the viewer the square's side is longer.
|
||||
let side = |i: usize| mark.subpaths[0].anchors[i].p.distance(mark.subpaths[0].anchors[(i + 1) % 4].p);
|
||||
let uneven = (side(0) - side(2)).abs().max((side(1) - side(3)).abs());
|
||||
assert!(uneven > 0.05, "{} {} {} {}", side(0), side(1), side(2), side(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shade_artwork_and_invisible_geometry_change_what_is_drawn() {
|
||||
let d = document();
|
||||
let params = |extra: Value| {
|
||||
let mut p = json!({"surface": "diffuse", "rotationY": -60, "lightIntensity": 0, "ambient": 20, "mapArt": [{"surface": 1, "symbol": "Mark"}]});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, p)).unwrap()
|
||||
};
|
||||
// Unshaded, the art keeps its own color on a shaded face.
|
||||
assert_eq!(filled(¶ms(json!({})), RED).len(), 1);
|
||||
// Shaded, it darkens toward black with its face.
|
||||
let shaded = params(json!({"mapShade": true}));
|
||||
assert!(filled(&shaded, RED).is_empty());
|
||||
let mut darkest = 1.0f32;
|
||||
shaded.walk(&mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item
|
||||
&& let Some([r, g, b]) = f.paint.color().map(|c| c.to_rgb())
|
||||
&& g < 1e-4
|
||||
&& b < 1e-4
|
||||
&& r > 0.0
|
||||
{
|
||||
darkest = darkest.min(r);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(darkest < 0.999, "the art is as dark as its face: {darkest}");
|
||||
// With Invisible Geometry only the art is drawn.
|
||||
let count = |art: &Node| {
|
||||
let mut paths = 0;
|
||||
art.walk(&mut |n| paths += usize::from(n.path_data().is_some() && !n.appearance.items.is_empty()));
|
||||
paths
|
||||
};
|
||||
assert!(count(¶ms(json!({}))) > 1);
|
||||
assert_eq!(count(¶ms(json!({"mapInvisible": true}))), 1);
|
||||
// Without a map Invisible Geometry leaves the solid as it is, and Wireframe draws no art.
|
||||
let plain = object(CLASSIC_EXTRUDE, json!({"mapInvisible": true}));
|
||||
assert!(count(&solid_art_in(Some(&d), &plain).unwrap()) > 0);
|
||||
assert!(filled(¶ms(json!({"surface": "wireframe"})), RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_past_the_surfaces_draws_nothing_and_a_missing_symbol_is_left_out() {
|
||||
let d = document();
|
||||
let art = |maps: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": maps}))).unwrap();
|
||||
assert!(filled(&art(json!([{"surface": 7, "symbol": "Mark"}])), RED).is_empty());
|
||||
assert!(filled(&art(json!([{"surface": 1, "symbol": "Gone"}])), RED).is_empty());
|
||||
// A hollow solid's first surface is its first wall, so the cap's map draws nothing there.
|
||||
let hollow = object(CLASSIC_EXTRUDE, json!({"cap": false, "mapArt": [{"surface": 1, "symbol": "Mark"}]}));
|
||||
assert!(filled(&solid_art_in(Some(&d), &hollow).unwrap(), RED).is_empty());
|
||||
assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Gone"}]})), Some("Gone".to_string()));
|
||||
assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance() {
|
||||
let d = document();
|
||||
let art = MapArt::of(Some(&d), CLASSIC_EXTRUDE, &json!({"mapArt": [{"surface": 3, "symbol": "Mark"}]})).unwrap();
|
||||
let wall = SolidSurface { kind: SurfaceKind::Wall, width: 100.0, height: 50.0, center: None };
|
||||
// Earlier surfaces drew more points on their faces than one symbol may take cut into pieces.
|
||||
let mut budget = MapBudget { points: MAX_ELEMENTS + 1, ..MapBudget::default() };
|
||||
let pieces = art.unrolled(&art.maps[0], &wall, &mut budget).expect("the symbol is cut into pieces");
|
||||
assert_eq!(pieces.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() {
|
||||
let d = document();
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 0.0));
|
||||
b.line_to((100.0, 100.0));
|
||||
let path = PathData::from_bezpath(&b);
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let n = Node::path(NodeId(7), path.clone(), Appearance::basic(Paint::None, gray.clone(), 1.0));
|
||||
let p = crate::merged_params(
|
||||
CLASSIC_REVOLVE,
|
||||
&json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}),
|
||||
);
|
||||
let art = MapArt::of(Some(&d), CLASSIC_REVOLVE, &p).unwrap();
|
||||
let bounds = path.bounds().unwrap();
|
||||
let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(CLASSIC_REVOLVE, &p) };
|
||||
let (width, height) = vectorcraft_three_d::revolve_surface_size(&path, bounds, options).unwrap();
|
||||
let layout = SolidLayout { first: 0, surfaces: vec![SolidSurface { kind: SurfaceKind::Side, width, height, center: None }], ends: None };
|
||||
let facets = vectorcraft_three_d::revolve_facets(&path, bounds, options).unwrap();
|
||||
// The side's art, with the copies of its paint and its points counted from `copies` and
|
||||
// `budget` already used.
|
||||
let draw = |copies: &mut usize, budget: &mut MapBudget| {
|
||||
let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies };
|
||||
let blend = vectorcraft_doc::color::BlendMode::Normal;
|
||||
crate::solids::classic::surface(&n, &facets, &gray, (1.0, blend), &p, Some(mapped), false).0
|
||||
};
|
||||
let (mut copies, mut budget) = (0, MapBudget::default());
|
||||
assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty());
|
||||
assert!(copies > 0 && budget != MapBudget::default());
|
||||
// With the allowance used up, the art is left out, and so are the copies and the points it
|
||||
// would have taken.
|
||||
let full = crate::revolve::MAX_PAINT_COPIES;
|
||||
let (mut copies, mut budget) = (full, MapBudget::default());
|
||||
assert!(filled(&draw(&mut copies, &mut budget), RED).is_empty());
|
||||
assert_eq!(copies, full);
|
||||
assert_eq!(budget, MapBudget::default());
|
||||
}
|
||||
|
||||
fn missing(d: &Document, p: &Value) -> Option<String> {
|
||||
super::super::missing_symbol(d, p, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_classic_wraps_its_map_around_the_side() {
|
||||
let d = document();
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((100.0, 0.0));
|
||||
b.line_to((100.0, 100.0));
|
||||
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0));
|
||||
let view =
|
||||
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Corner"}]});
|
||||
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &view).unwrap());
|
||||
let art = crate::revolve_art_in(Some(&d), &n).unwrap();
|
||||
// The art is drawn at the middle of the side that faces the viewer, the right way round.
|
||||
assert!(!filled(&art, RED).is_empty());
|
||||
assert!(handedness(&art) > 0.0);
|
||||
let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat());
|
||||
assert!((whole.center().y - 50.0).abs() < 1.0, "{whole:?}");
|
||||
// A map of another surface draws nothing.
|
||||
n.appearance.effects[0].params["mapArt"] = json!([{"surface": 2, "symbol": "Corner"}]);
|
||||
assert!(filled(&crate::revolve_art_in(Some(&d), &n).unwrap(), RED).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() {
|
||||
let d = document();
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
let line = |id: u64, x: f64, height: f64| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 0.0));
|
||||
b.line_to((x, height));
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0)))
|
||||
};
|
||||
// The map goes on the side of the longer member; the shorter one has none.
|
||||
let art = |extra: Value| {
|
||||
let mut p =
|
||||
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let mut g = Node::group(NodeId(7), vec![line(8, 100.0, 100.0), line(9, 140.0, 30.0)]);
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &p).unwrap());
|
||||
crate::revolve_art_in(Some(&d), &g).unwrap()
|
||||
};
|
||||
let shown = art(json!({}));
|
||||
assert!(!filled(&shown, RED).is_empty() && !filled(&shown, gray).is_empty());
|
||||
let hidden = art(json!({"mapInvisible": true}));
|
||||
assert!(!filled(&hidden, RED).is_empty());
|
||||
assert!(filled(&hidden, gray).is_empty(), "no member's faces are drawn");
|
||||
// On Wireframe the members are drawn as they are without a map.
|
||||
let wire = art(json!({"mapInvisible": true, "surface": "wireframe"}));
|
||||
let mut strokes = 0;
|
||||
wire.walk(&mut |n| strokes += usize::from(n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_)))));
|
||||
assert!(strokes > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revolved_group_past_its_shared_limits_lists_no_surface() {
|
||||
let gray = Color::rgb(0.5, 0.5, 0.5);
|
||||
// Profiles of five anchors each; one alone fits Revolve's limits.
|
||||
let profile = |id: u64, x: f64| {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((x, 0.0));
|
||||
for i in 1..5 {
|
||||
b.line_to((x + f64::from(i % 2), f64::from(i) * 10.0));
|
||||
}
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0)))
|
||||
};
|
||||
let group = |count: u64| {
|
||||
let mut g = Node::group(NodeId(7), (0..count).map(|k| profile(k + 8, 100.0 + k as f64 * 0.01)).collect());
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap());
|
||||
g
|
||||
};
|
||||
let d = document();
|
||||
assert_eq!(map_surfaces_at(Some(&d), &group(2), None, 0).map(|s| s.len()), Some(1));
|
||||
// 4,000 of them together are past the anchors the members share.
|
||||
assert!(map_surfaces_at(Some(&d), &group(4000), None, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extruded_group_past_the_faces_of_one_object_lists_no_surface() {
|
||||
// Polygons of 1,000 corners: each solid alone has about 1,000 faces.
|
||||
let polygon = |id: u64, x: f64| {
|
||||
let mut b = BezPath::new();
|
||||
for i in 0..1000 {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 1000.0;
|
||||
let p = (x + 40.0 * a.cos(), 40.0 * a.sin());
|
||||
if i == 0 { b.move_to(p) } else { b.line_to(p) }
|
||||
}
|
||||
b.close_path();
|
||||
Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)))
|
||||
};
|
||||
let group = |count: u64| {
|
||||
let mut g = Node::group(NodeId(7), (0..count).map(|k| polygon(k + 8, k as f64 * 100.0)).collect());
|
||||
g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({"drawHiddenFaces": true})).unwrap());
|
||||
g
|
||||
};
|
||||
let d = document();
|
||||
assert!(map_surfaces_at(Some(&d), &group(2), None, 0).is_some());
|
||||
// 200 of them together have more faces than one object draws.
|
||||
assert!(map_surfaces_at(Some(&d), &group(200), None, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_maps_are_refused() {
|
||||
let d = document();
|
||||
let check = |id: &str, p: Value| {
|
||||
let n = object(id, json!({}));
|
||||
validate_three_d_in(Some(&d), &n, id, &crate::merged_params(id, &p))
|
||||
};
|
||||
assert_eq!(check(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 3, "symbol": "Mark", "scaleX": 50}]})), Ok(()));
|
||||
assert_eq!(check(CLASSIC_REVOLVE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}], "mapShade": true})), Ok(()));
|
||||
for (p, error) in [
|
||||
(json!({"mapArt": {}}), "`mapArt` must be an array"),
|
||||
(json!({"mapArt": [7]}), "each of `mapArt` must be an object"),
|
||||
(json!({"mapArt": [{"symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 0, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 1.5, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 100001, "symbol": "Mark"}]}), "needs `surface`"),
|
||||
(json!({"mapArt": [{"surface": 1}]}), "needs `symbol`"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "face": "front"}]}), "not `face`"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "scaleX": 0}]}), "scaleX must be a number from 1 to 10000"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "rotation": 361}]}), "rotation must be a number from -360 to 360"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark", "x": "left"}]}), "x must be a number"),
|
||||
(json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}]}), "maps surface 1 more than once"),
|
||||
(json!({"mapShade": 1}), "`mapShade` must be true or false"),
|
||||
(json!({"mapInvisible": "yes"}), "`mapInvisible` must be true or false"),
|
||||
] {
|
||||
for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] {
|
||||
let e = check(id, p.clone()).unwrap_err();
|
||||
assert!(e.contains(error), "{id} {p}: {e}");
|
||||
}
|
||||
}
|
||||
let many: Vec<Value> = (1..=65).map(|k| json!({"surface": k, "symbol": "Mark"})).collect();
|
||||
assert!(check(CLASSIC_EXTRUDE, json!({"mapArt": many})).unwrap_err().contains("at most 64 maps"));
|
||||
// Rotate (Classic) has no surface to map onto.
|
||||
let e = check(CLASSIC_ROTATE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})).unwrap_err();
|
||||
assert!(e.contains(MAP_ART_NOT_TAKEN), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() {
|
||||
let mut d = document();
|
||||
// A zigzag of more straight sides than one 3D effect's graphics may draw.
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((0.0, 0.0));
|
||||
for i in 1..=MAX_ELEMENTS {
|
||||
b.line_to((i as f64 * 0.001, (i % 2) as f64));
|
||||
}
|
||||
b.close_path();
|
||||
let dense = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(dense) });
|
||||
for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] {
|
||||
let p = crate::merged_params(id, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]}));
|
||||
let e = validate_three_d_in(Some(&d), &object(id, json!({})), id, &p).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{id}: {e}");
|
||||
}
|
||||
// On a fill, as on the object.
|
||||
let plain = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5));
|
||||
let p = crate::merged_params(CLASSIC_REVOLVE, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]}));
|
||||
let e = validate_three_d_at_in(Some(&d), &plain, CLASSIC_REVOLVE, &p, (Some(0), 0)).unwrap_err();
|
||||
assert!(e.contains("too complex"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapped_symbol_whose_curves_cut_into_too_many_pieces_is_refused() {
|
||||
let mut d = document();
|
||||
// Large circles: a few curves each, but many straight pieces once they are cut.
|
||||
let loops = |name: &str, count: usize| {
|
||||
let mut b = BezPath::new();
|
||||
for k in 0..count {
|
||||
let r = 1e5;
|
||||
let circle = vectorcraft_geom::kurbo::Circle::new((k as f64 * 2.1 * r, 0.0), r);
|
||||
b.extend(vectorcraft_geom::kurbo::Shape::path_elements(&circle, 0.1));
|
||||
}
|
||||
let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }
|
||||
};
|
||||
d.symbols.push(loops("Loop", 1));
|
||||
d.symbols.push(loops("Loops", 400));
|
||||
let check = |id: &str, surface: usize, symbol: &str| {
|
||||
let p = crate::merged_params(id, &json!({"mapArt": [{"surface": surface, "symbol": symbol}]}));
|
||||
validate_three_d_in(Some(&d), &object(id, json!({})), id, &p)
|
||||
};
|
||||
// Extrude & Bevel's surface 3 is a wall, and Revolve's surface 1 its side.
|
||||
for (id, surface) in [(CLASSIC_EXTRUDE, 3), (CLASSIC_REVOLVE, 1)] {
|
||||
assert_eq!(check(id, surface, "Loop"), Ok(()), "{id}");
|
||||
let e = check(id, surface, "Loops").unwrap_err();
|
||||
assert!(e.contains("too complex"), "{id}: {e}");
|
||||
}
|
||||
// A cap draws the curves as they are, without cutting them.
|
||||
assert_eq!(check(CLASSIC_EXTRUDE, 1, "Loops"), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_are_set_cleared_and_renamed_with_their_symbols() {
|
||||
let p = json!({"depth": 20});
|
||||
let map =
|
||||
|surface: usize, symbol: &str| SurfaceMap { surface, symbol: symbol.into(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 };
|
||||
let p = with_surface_map(&p, 4, Some(&map(4, "Mark")));
|
||||
let p = with_surface_map(&p, 2, Some(&map(2, "Corner")));
|
||||
let p = with_surface_map(&p, 4, Some(&map(4, "Corner")));
|
||||
// One map for a surface, in the order of the surfaces; the other parameters stay.
|
||||
assert_eq!(surface_maps(&p), vec![map(2, "Corner"), map(4, "Corner")]);
|
||||
assert_eq!(p["depth"], json!(20));
|
||||
assert_eq!(surface_maps(&with_surface_map(&p, 2, None)), vec![map(4, "Corner")]);
|
||||
// A file's maps: entries that are not valid and a surface's second map are left out.
|
||||
let loaded = json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}, {"surface": 0, "symbol": "Mark"}, 3]});
|
||||
assert_eq!(surface_maps(&loaded), vec![map(1, "Mark")]);
|
||||
// Renaming a symbol renames it in the maps of the effects that take them.
|
||||
let mut n = object(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]}));
|
||||
assert_eq!(super::super::graphic_symbols(&n), vec!["Mark".to_string()]);
|
||||
assert!(super::super::rename_graphic_symbol(&mut n, "Mark", "Logo"));
|
||||
assert_eq!(surface_maps(&n.appearance.effects[0].params)[0].symbol, "Logo");
|
||||
// Scale to Fit fills the surface: each side by its own scale when the art is square to it.
|
||||
assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)), Some((1000.0, 500.0)));
|
||||
let turned = SurfaceMap { rotation: 90.0, ..map(1, "Mark") };
|
||||
assert_eq!(turned.fitting_scales(Rect::new(0.0, 0.0, 10.0, 20.0), (100.0, 50.0)), Some((500.0, 500.0)));
|
||||
let aslant = SurfaceMap { rotation: 45.0, ..map(1, "Mark") };
|
||||
let (sx, sy) = aslant.fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)).unwrap();
|
||||
assert!((sx - sy).abs() < 1e-9 && (sx - 50.0 / (20.0 * 0.5f64.sqrt()) * 100.0).abs() < 1e-6, "{sx} {sy}");
|
||||
assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 0.0, 10.0), (100.0, 50.0)), None);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -47,6 +48,7 @@ mod info;
|
||||
pub(crate) mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
pub mod kinsokusets;
|
||||
pub(crate) mod layer;
|
||||
mod layerpanel;
|
||||
pub mod library;
|
||||
@@ -74,6 +76,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 +101,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 +325,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());
|
||||
@@ -331,8 +336,10 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(textstyles::specs());
|
||||
v.extend(fonts::specs());
|
||||
v.extend(compositefonts::specs());
|
||||
v.extend(kinsokusets::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 +389,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());
|
||||
@@ -874,10 +882,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`).
|
||||
@@ -901,6 +913,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;
|
||||
|
||||
@@ -911,6 +925,10 @@ pub use buildcmds::live_paint_gaps;
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to
|
||||
/// the selected ones).
|
||||
pub use brushsym::is_symbol_set;
|
||||
|
||||
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
|
||||
/// frame without running the command).
|
||||
pub use brushsym::current_symbol;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
//! circles, or three or more each joined the same way to the others within reach and united where
|
||||
//! the bridges connect, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge";
|
||||
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
|
||||
const RADIUS: f64 = 100.0;
|
||||
const RADII: (f64, f64) = (1.0, 1000.0);
|
||||
/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range.
|
||||
const GAPS: (f64, f64) = (0.0, 1000.0);
|
||||
/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between
|
||||
/// them: by default, and the range.
|
||||
const REACH: f64 = 10.0;
|
||||
const REACHES: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}",
|
||||
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let percent = given(p, "radius", Some(RADII), C)?;
|
||||
let gap = given(p, "gap", Some(GAPS), C)?;
|
||||
let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH);
|
||||
if percent.is_some() && gap.is_some() {
|
||||
// As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check.
|
||||
let (key, other) = ("radius", "gap");
|
||||
return Err(bad(C, format!("give `{key}` or `{other}`, not both")));
|
||||
}
|
||||
let arc = match gap {
|
||||
Some(gap) => pt::ArcRadius::Gap(gap),
|
||||
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
|
||||
};
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
// An id given twice is one circle.
|
||||
roots.sort_unstable();
|
||||
roots.dedup();
|
||||
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
|
||||
return Err(bad(C, "select at most 2000 circles to bridge"));
|
||||
}
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
@@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else {
|
||||
return Err(bad(C, "select two circles to bridge"));
|
||||
};
|
||||
let (below, above) = (*below, *above);
|
||||
let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0);
|
||||
let outline = match at(percent) {
|
||||
Ok(sp) => PathData::single(sp),
|
||||
Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")),
|
||||
// A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed.
|
||||
Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => {
|
||||
return Err(bad(C, "the circles are too far apart for this radius: raise the radius"));
|
||||
if circles.len() != roots.len() || circles.len() < 2 {
|
||||
return Err(bad(C, "select two or more circles to bridge"));
|
||||
}
|
||||
let only: Vec<pt::Circle> = circles.iter().map(|(_, c)| *c).collect();
|
||||
// Each shape: the circles it joins, in paint order, and its outline.
|
||||
let (shapes, alone): (Vec<(Vec<NodeId>, PathData)>, Vec<NodeId>) = match only.as_slice() {
|
||||
[a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) {
|
||||
Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]),
|
||||
Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())),
|
||||
},
|
||||
_ => {
|
||||
let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e {
|
||||
pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"),
|
||||
pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"),
|
||||
pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"),
|
||||
pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"),
|
||||
// Under the many-circle rules: a pair the largest radius or gap bridges on its own
|
||||
// can still have a neck too thin to unite among the others.
|
||||
pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)),
|
||||
pt::ManyError::Bad => bad(C, "select two or more circles to bridge"),
|
||||
})?;
|
||||
let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect();
|
||||
(shapes, roots_of(&circles, &made.alone))
|
||||
}
|
||||
Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")),
|
||||
Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")),
|
||||
};
|
||||
let id = s.edit(LABEL, |d, sel| {
|
||||
let id = if keep {
|
||||
// A copy of the upper circle (its appearance) with the outline as its path, right above
|
||||
// it; the circles stay as they are, live shapes included.
|
||||
// Fresh ids throughout, its opacity mask's art included.
|
||||
let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
let made = s.edit(LABEL, |d, sel| {
|
||||
let mut made = Vec::with_capacity(shapes.len());
|
||||
if keep {
|
||||
// A copy of each shape's topmost circle (its appearance) with the outline as its path,
|
||||
// right above it; the circles stay as they are, live shapes included. Fresh ids
|
||||
// throughout, an opacity mask's art included.
|
||||
let tops: Vec<NodeId> = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect();
|
||||
let mut beside = Beside::above(d, &tops);
|
||||
for ((_, outline), top) in shapes.into_iter().zip(tops) {
|
||||
let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?;
|
||||
let mut n = d.reid(&upper);
|
||||
if let NodeKind::Path { path, live, .. } = &mut n.kind {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(n.id);
|
||||
beside.put(d, top, vec![n])?;
|
||||
}
|
||||
let id = n.id;
|
||||
let mut beside = Beside::above(d, &[above]);
|
||||
beside.put(d, above, vec![n])?;
|
||||
beside.finish(d)?;
|
||||
id
|
||||
} else {
|
||||
// The upper circle becomes the outline (a plain path now) and the lower one goes.
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
|
||||
let mut gone = vec![];
|
||||
for (members, outline) in shapes {
|
||||
let Some((&top, rest)) = members.split_last() else { continue };
|
||||
if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) {
|
||||
*path = outline;
|
||||
*live = None;
|
||||
}
|
||||
made.push(top);
|
||||
gone.extend_from_slice(rest);
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
remove_each(d, &gone)?;
|
||||
}
|
||||
sel.set(made.iter().chain(&alone).copied());
|
||||
Ok(made)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::<Vec<_>>(), "alone": alone.iter().map(|id| id.0).collect::<Vec<_>>() });
|
||||
if let ([id], 2) = (made.as_slice(), only.len()) {
|
||||
out["id"] = json!(id.0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
|
||||
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
|
||||
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
|
||||
}
|
||||
|
||||
/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a
|
||||
/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would.
|
||||
fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError {
|
||||
let largest = match arc {
|
||||
pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0),
|
||||
pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1),
|
||||
};
|
||||
let would = e == pt::BridgeError::TooFar && bridges(largest);
|
||||
match (e, arc, would) {
|
||||
(pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"),
|
||||
(pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"),
|
||||
(pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or
|
||||
//! gap, many circles joined to their neighbors within reach, and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
@@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles");
|
||||
assert_eq!(r["alone"], json!([]));
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
|
||||
@@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}");
|
||||
}
|
||||
// Three circles: each two within reach are bridged, and one inside another is refused there too.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
|
||||
@@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
|
||||
fn grid(s: &mut Session) -> Vec<NodeId> {
|
||||
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
select(&mut s, &g);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not.
|
||||
let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place");
|
||||
assert_eq!(ids(&r["alone"]), []);
|
||||
assert_eq!(top_level(&s), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
// Its outline and a hole in each square of four circles, which no diagonal bridge fills.
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len());
|
||||
let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0;
|
||||
assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), g);
|
||||
// Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square.
|
||||
select(&mut s, &g);
|
||||
s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap();
|
||||
let outline = path(&s, g[8]);
|
||||
assert_eq!(outline.subpaths.len(), 1);
|
||||
assert!(inside(&outline, 112.0, 112.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() {
|
||||
let mut s = session();
|
||||
let g = grid(&mut s);
|
||||
let far = circle(&mut s, 300.0, 250.0, 10.0);
|
||||
let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)];
|
||||
let mut all = g.clone();
|
||||
all.extend([far, pair[0], pair[1]]);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::<Vec<_>>(), "reach": 5})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [g[8], pair[1]]);
|
||||
assert_eq!(ids(&r["alone"]), [far]);
|
||||
assert_eq!(top_level(&s), [g[8], far, pair[1]]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched");
|
||||
let mut selected = s.doc().unwrap().selection.objects.to_vec();
|
||||
selected.sort();
|
||||
let mut want = vec![g[8], pair[1], far];
|
||||
want.sort();
|
||||
assert_eq!(selected, want, "the shapes and the circle left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_each_shape_above_its_topmost_circle() {
|
||||
let mut s = session();
|
||||
let row: Vec<NodeId> = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect();
|
||||
let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)];
|
||||
s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap();
|
||||
let all: Vec<u64> = row.iter().chain(&other).map(|i| i.0).collect();
|
||||
let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap();
|
||||
let made = ids(&r["ids"]);
|
||||
assert_eq!(made.len(), 2);
|
||||
assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle");
|
||||
let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() {
|
||||
let area_with = |p: Value| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 124.0, 100.0, 10.0);
|
||||
let mut p = p;
|
||||
p["ids"] = json!([a.0, b.0]);
|
||||
let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
// Radius 10 plus a gap of 4 is 140% of 10.
|
||||
let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140})));
|
||||
assert!((gap - percent).abs() < 1e-9, "{gap} {percent}");
|
||||
assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_circle_and_gap_refusals() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 330.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both"));
|
||||
// Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers
|
||||
// 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010)
|
||||
// ≈ 285.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach"));
|
||||
// b and c are 60 apart: within a reach of 100, but too far for the default radius.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() {
|
||||
let mut s = session();
|
||||
// Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but
|
||||
// with a neck about 0.0007 pt wide, too thin to unite among three or more circles.
|
||||
let a = circle(&mut s, 20.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 111.65, 100.0, 10.0);
|
||||
let far = circle(&mut s, 380.0, 100.0, 10.0);
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_circles_or_bridges_are_refused() {
|
||||
let mut s = session();
|
||||
// 130 overlapping circles in a row: 8,385 pairs within reach.
|
||||
let row: Vec<u64> = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach"));
|
||||
let many: Vec<u64> = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect();
|
||||
assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_given_twice_is_one_circle() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0), "two circles, bridged");
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
|
||||
let mut s = session();
|
||||
// Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b,
|
||||
// within the default reach of 10).
|
||||
let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0));
|
||||
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
assert_eq!(ids(&r["ids"]), [b]);
|
||||
assert_eq!(ids(&r["alone"]), [c]);
|
||||
assert_eq!(top_level(&s), [b, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
@@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
s.execute("object.unlockAll", &json!({})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
|
||||
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
|
||||
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if sp.anchors.len() == 1
|
||||
&& let Some(only) = sp.anchors.first()
|
||||
{
|
||||
return pt::Outline::point(only.p).map_err(refusal);
|
||||
}
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
if a.is_point() && b.is_point() {
|
||||
return Err(bad(C, "select two closed paths"));
|
||||
}
|
||||
// A point goes first, so that each line runs from it to where it touches the path.
|
||||
let point = a.is_point() || b.is_point();
|
||||
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
// A point's external and internal tangents are the same lines: every kind keeps them.
|
||||
let keep = |t: &&pt::Tangent| {
|
||||
point
|
||||
|| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let (external_kept, internal_kept) = match (point, kinds) {
|
||||
(true, "internal") => (0, kept.len()),
|
||||
(true, _) => (kept.len(), 0),
|
||||
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
|
||||
};
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() && point {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds it.
|
||||
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
|
||||
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
|
||||
let mut s = session();
|
||||
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
|
||||
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
select(&mut s, &[oval, dot]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({"centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
|
||||
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
|
||||
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
|
||||
for sy in [1.0, -1.0] {
|
||||
let touch = c + Vec2::new(-8.0, sy * y);
|
||||
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
|
||||
}
|
||||
assert_eq!(r["centerline"], r["ids"][2]);
|
||||
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
|
||||
// Every `tangents` value gives the same two lines.
|
||||
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
|
||||
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
|
||||
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_below_the_path_still_starts_the_lines() {
|
||||
let mut s = session();
|
||||
// The point is drawn first, so it is the lower object and needs no swap.
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
let round = circle(&mut s, 300.0, 200.0, 50.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let p = Point::new(100.0, 200.0);
|
||||
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
|
||||
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
|
||||
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
|
||||
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
|
||||
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_or_inside_a_path_and_two_points() {
|
||||
let mut s = session();
|
||||
let round = circle(&mut s, 200.0, 200.0, 50.0);
|
||||
// On the circle: one line, centered on the point and as long as the circle is wide.
|
||||
let on = point(&mut s, 250.0, 200.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
|
||||
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// Inside: nothing changes, and the warning says why.
|
||||
let inside = point(&mut s, 210.0, 190.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Two points, or a point and an open path, are refused.
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -27,11 +27,15 @@ use crate::EngineError;
|
||||
/// Whether Reset Transformation changes a symbol instance.
|
||||
pub use symbols::reset_transformation_changes;
|
||||
|
||||
/// Whether an object is a symbol set.
|
||||
pub use symbols::is_symbol_set;
|
||||
|
||||
/// The Symbols panel's current symbol, as `symbol.list` answers it.
|
||||
pub use symbols::current_symbol;
|
||||
|
||||
mod brushes;
|
||||
mod dynamic;
|
||||
mod symbolism;
|
||||
mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
@@ -41,6 +45,7 @@ use brushes::{
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
use symbolism::symbol_set_density;
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
@@ -165,7 +170,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, 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}",
|
||||
"{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|stylusWheel 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°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; 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|stylusWheel 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°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), 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|stylusWheel, 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°; stylusWheel: width at one end of the finger wheel to width_max at the other; 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
|
||||
),
|
||||
@@ -220,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
@@ -338,7 +343,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select All Unused",
|
||||
[],
|
||||
None,
|
||||
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
|
||||
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics and Map Art maps on 3D objects (threeD.mapGraphic, threeD.mapArt), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
|
||||
has_doc,
|
||||
symbol_unused
|
||||
),
|
||||
@@ -357,16 +362,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Sprayer",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances)} spray instances into a symbol set → {id, count}",
|
||||
"{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
has_doc,
|
||||
symbol_spray
|
||||
),
|
||||
cmd!(
|
||||
"symbol.setDensity",
|
||||
"Symbol Set Density",
|
||||
[],
|
||||
None,
|
||||
"{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and every set then has density `to`, also one whose instances do not move (one instance, or each locked); a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves and every set already has density `to`. A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}",
|
||||
has_doc,
|
||||
symbol_set_density
|
||||
),
|
||||
cmd!(
|
||||
"symbol.adjust",
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
//! What the symbolism commands share: the Method and the Symbol Sprayer options of the Symbolism
|
||||
//! Tools Options, what an instance shows of the values the tools change ([`Look`]), the mean of
|
||||
//! those values under the brush ([`mean`]), and `symbol.setDensity`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::symbols::{instance_center, is_symbol_set, stored_natural_size};
|
||||
use super::{
|
||||
Affine, Document, EngineError, HALF, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids,
|
||||
};
|
||||
|
||||
/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Method {
|
||||
/// Gradually, in relation to the position of the pointer.
|
||||
UserDefined,
|
||||
/// Toward the mean of the instances under the brush.
|
||||
Average,
|
||||
/// By an amount that differs from instance to instance.
|
||||
Random,
|
||||
}
|
||||
|
||||
/// The `method` of `symbol.adjust` (User Defined when left out or null).
|
||||
pub(super) fn method_param(p: &Value, cmd: &str) -> Result<Method> {
|
||||
match p.get("method") {
|
||||
None | Some(Value::Null) => Ok(Method::UserDefined),
|
||||
Some(Value::String(s)) if s == "userDefined" => Ok(Method::UserDefined),
|
||||
Some(Value::String(s)) if s == "average" => Ok(Method::Average),
|
||||
Some(Value::String(s)) if s == "random" => Ok(Method::Random),
|
||||
Some(v) => Err(bad(cmd, format!("`method` must be userDefined, average or random, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Symbol Sprayer options: whether each value of a new instance is the average of the
|
||||
/// instances under the brush (true) or the User Defined value (false).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct SprayModes {
|
||||
pub scrunch: bool,
|
||||
pub size: bool,
|
||||
pub spin: bool,
|
||||
pub screen: bool,
|
||||
pub stain: bool,
|
||||
pub style: bool,
|
||||
}
|
||||
|
||||
impl SprayModes {
|
||||
/// Whether any value is an average.
|
||||
pub fn any_average(self) -> bool {
|
||||
self.scrunch || self.size || self.spin || self.screen || self.stain || self.style
|
||||
}
|
||||
}
|
||||
|
||||
/// The `attributes` of `symbol.spray`: `{scrunch?, size?, spin?, screen?, stain?, style?}`, each
|
||||
/// `average` (also when left out or null) or `userDefined`. Another key or value is an error.
|
||||
pub(super) fn spray_modes(p: &Value, cmd: &str) -> Result<SprayModes> {
|
||||
let mut m = SprayModes { scrunch: true, size: true, spin: true, screen: true, stain: true, style: true };
|
||||
let map = match p.get("attributes") {
|
||||
None | Some(Value::Null) => return Ok(m),
|
||||
Some(Value::Object(map)) => map,
|
||||
Some(v) => return Err(bad(cmd, format!("`attributes` must be an object, not {v}"))),
|
||||
};
|
||||
for (key, v) in map {
|
||||
let slot = match key.as_str() {
|
||||
"scrunch" => &mut m.scrunch,
|
||||
"size" => &mut m.size,
|
||||
"spin" => &mut m.spin,
|
||||
"screen" => &mut m.screen,
|
||||
"stain" => &mut m.stain,
|
||||
"style" => &mut m.style,
|
||||
_ => return Err(bad(cmd, format!("unknown attribute `{key}`"))),
|
||||
};
|
||||
*slot = match v {
|
||||
Value::Null => true,
|
||||
Value::String(s) if s == "average" => true,
|
||||
Value::String(s) if s == "userDefined" => false,
|
||||
v => return Err(bad(cmd, format!("attribute `{key}` must be average or userDefined, not {v}"))),
|
||||
};
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// How far apart the Symbol Sprayer keeps instances at Symbol Set Density `density` (1..10), as a
|
||||
/// share of the symbol's size: a denser set is packed closer.
|
||||
pub(super) fn spacing(density: f64) -> f64 {
|
||||
(1.15 - density * 0.1).max(0.1)
|
||||
}
|
||||
|
||||
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
|
||||
const SET_DENSITY_KEY: &str = "symbolSetDensity";
|
||||
|
||||
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
|
||||
fn set_density_of(d: &Document, set: NodeId) -> Option<f64> {
|
||||
d.unknown.get(SET_DENSITY_KEY)?.get(set.0.to_string())?.as_f64().filter(|v| (1.0..=10.0).contains(v))
|
||||
}
|
||||
|
||||
/// Record `density` as the Symbol Set Density of `sets`, and drop the records of ids that are no
|
||||
/// longer symbol sets.
|
||||
pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64) {
|
||||
let mut map = match d.unknown.get(SET_DENSITY_KEY) {
|
||||
Some(Value::Object(m)) => m.clone(),
|
||||
_ => serde_json::Map::new(),
|
||||
};
|
||||
for set in sets {
|
||||
map.insert(set.0.to_string(), json!(density));
|
||||
}
|
||||
map.retain(|k, _| k.parse::<u64>().ok().and_then(|id| d.node(NodeId(id))).is_some_and(is_symbol_set));
|
||||
if map.is_empty() {
|
||||
d.unknown.remove(SET_DENSITY_KEY);
|
||||
} else {
|
||||
d.unknown.insert(SET_DENSITY_KEY.into(), Value::Object(map));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a symbol instance shows of the values the symbolism tools change.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Look {
|
||||
pub center: Point,
|
||||
/// Its size on the page: the side of a square with its area, the same measure for every symbol.
|
||||
pub size: f64,
|
||||
/// Its rotation in radians.
|
||||
pub angle: f64,
|
||||
pub opacity: f64,
|
||||
/// The fill the Symbol Stainer or the Symbol Styler gave it, with its amount (0..1).
|
||||
pub fill: Option<(Paint, f64)>,
|
||||
}
|
||||
|
||||
/// The [`natural_side`] of each symbol measured so far in one command, so that one measure serves
|
||||
/// every instance of the symbol.
|
||||
pub(super) type Sides = HashMap<String, f64>;
|
||||
|
||||
/// The [`Look`] of instance `n` (None for another object, or an instance without a size).
|
||||
pub(super) fn look(d: &Document, n: &Node, sides: &mut Sides) -> Option<Look> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
|
||||
let [a, b, c, e, ..] = xf.as_coeffs();
|
||||
let natural = d.symbol_natural_xf(symbol).as_coeffs();
|
||||
let (sx, sy) = (natural[0].abs().max(1e-9), natural[3].abs().max(1e-9));
|
||||
let scale = ((a * e - b * c) / (sx * sy)).abs().sqrt();
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let side = match sides.get(symbol) {
|
||||
Some(side) => *side,
|
||||
None => *sides.entry(symbol.clone()).or_insert_with(|| natural_side(d, symbol)),
|
||||
};
|
||||
let size = scale * side;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some(Look {
|
||||
center: instance_center(n)?,
|
||||
size,
|
||||
angle: b.atan2(a),
|
||||
opacity: f64::from(n.opacity),
|
||||
fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The [`Look::size`] of an instance of symbol `name` at the symbol's own size. A symbol without a
|
||||
/// recorded size draws its art at the art's own size, so its art is measured.
|
||||
pub(super) fn natural_side(d: &Document, name: &str) -> f64 {
|
||||
let recorded = stored_natural_size(d, name).is_some_and(|(w, h)| w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0);
|
||||
// Each side's root first, so that a huge size does not overflow.
|
||||
let art = (!recorded).then(|| d.symbol_art_bounds(name)).flatten().map(|r| r.width().sqrt() * r.height().sqrt());
|
||||
if let Some(side) = art.filter(|s| s.is_finite() && *s > 0.0) {
|
||||
return side;
|
||||
}
|
||||
let natural = d.symbol_natural_xf(name).as_coeffs();
|
||||
2.0 * HALF * natural[0].abs().max(1e-9).sqrt() * natural[3].abs().max(1e-9).sqrt()
|
||||
}
|
||||
|
||||
/// The mean of the [`Look`]s of the instances under the brush.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Mean {
|
||||
/// The geometric mean of the sizes ([`Look::size`]).
|
||||
pub size: f64,
|
||||
/// The mean direction of the rotations.
|
||||
pub angle: f64,
|
||||
pub opacity: f64,
|
||||
/// The mean stain or style amount; an instance without one counts as 0.
|
||||
pub amount: f64,
|
||||
/// The stain or style of the instance nearest the brush's center that has one.
|
||||
pub paint: Option<Paint>,
|
||||
/// The middle of the instances.
|
||||
pub middle: Point,
|
||||
/// Their mean distance from [`Mean::middle`].
|
||||
pub reach: f64,
|
||||
/// The mean distance from each of them to the nearest of the others (None for one instance, or
|
||||
/// when not asked for).
|
||||
pub gap: Option<f64>,
|
||||
}
|
||||
|
||||
/// The x (`axis` 0) or y (`axis` 1) of `p`.
|
||||
fn coord(p: Point, axis: usize) -> f64 {
|
||||
if axis == 0 { p.x } else { p.y }
|
||||
}
|
||||
|
||||
/// Arrange `order` (indices into `pts`) as a k-d tree: the middle entry of each slice splits the
|
||||
/// rest by x at even depths and by y at odd ones, the smaller values before it.
|
||||
fn kd_build(order: &mut [usize], pts: &[Point], axis: usize) {
|
||||
if order.len() <= 1 {
|
||||
return;
|
||||
}
|
||||
let mid = order.len() / 2;
|
||||
let at = |i: &usize| pts.get(*i).map_or(0.0, |p| coord(*p, axis));
|
||||
order.select_nth_unstable_by(mid, |a, b| at(a).total_cmp(&at(b)));
|
||||
let (left, right) = order.split_at_mut(mid);
|
||||
kd_build(left, pts, 1 - axis);
|
||||
kd_build(right.get_mut(1..).unwrap_or_default(), pts, 1 - axis);
|
||||
}
|
||||
|
||||
/// The distance from `pts[i]` to the nearest of the others in k-d tree `order`, if nearer than
|
||||
/// `best`. Instances on top of each other end the search: none can be nearer.
|
||||
fn kd_nearest(order: &[usize], pts: &[Point], axis: usize, i: usize, best: &mut f64) {
|
||||
let (Some(&j), Some(&p)) = (order.get(order.len() / 2), pts.get(i)) else { return };
|
||||
let Some(&q) = pts.get(j) else { return };
|
||||
if j != i {
|
||||
*best = best.min(p.distance(q));
|
||||
}
|
||||
if *best == 0.0 {
|
||||
return;
|
||||
}
|
||||
let (left, right) = order.split_at(order.len() / 2);
|
||||
let right = right.get(1..).unwrap_or_default();
|
||||
let diff = coord(p, axis) - coord(q, axis);
|
||||
let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) };
|
||||
kd_nearest(near, pts, 1 - axis, i, best);
|
||||
// The other side holds nothing nearer than the split line.
|
||||
if diff.abs() < *best {
|
||||
kd_nearest(far, pts, 1 - axis, i, best);
|
||||
}
|
||||
}
|
||||
|
||||
/// For each of `looks`, the distance to the nearest of the others (infinite for one alone), found
|
||||
/// through a k-d tree of their centers.
|
||||
fn nearest_gaps(looks: &[&Look]) -> Vec<f64> {
|
||||
let pts: Vec<Point> = looks.iter().map(|l| l.center).collect();
|
||||
let mut order: Vec<usize> = (0..pts.len()).collect();
|
||||
kd_build(&mut order, &pts, 0);
|
||||
(0..pts.len())
|
||||
.map(|i| {
|
||||
let mut best = f64::INFINITY;
|
||||
kd_nearest(&order, &pts, 0, i, &mut best);
|
||||
best
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with
|
||||
/// [`Mean::gap`] when `with_gap` is set.
|
||||
pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
|
||||
if looks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = looks.len() as f64;
|
||||
let (mut log_size, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO);
|
||||
let mut paint: Option<(&Paint, f64)> = None;
|
||||
for l in looks {
|
||||
log_size += l.size.ln();
|
||||
sin += l.angle.sin();
|
||||
cos += l.angle.cos();
|
||||
opacity += l.opacity;
|
||||
middle += l.center.to_vec2();
|
||||
if let Some((p, o)) = &l.fill {
|
||||
amount += o;
|
||||
let far = l.center.distance(at);
|
||||
if paint.is_none_or(|(_, nearest)| far < nearest) {
|
||||
paint = Some((p, far));
|
||||
}
|
||||
}
|
||||
}
|
||||
let middle = (middle / n).to_point();
|
||||
// Rotations that cancel out have no mean direction: the first instance's stands for it.
|
||||
let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle };
|
||||
// One instance under the brush has no spacing there.
|
||||
let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::<f64>() / n);
|
||||
Some(Mean {
|
||||
size: (log_size / n).exp(),
|
||||
angle,
|
||||
opacity: opacity / n,
|
||||
amount: amount / n,
|
||||
paint: paint.map(|(p, _)| p.clone()),
|
||||
middle,
|
||||
reach: looks.iter().map(|l| l.center.distance(middle)).sum::<f64>() / n,
|
||||
gap,
|
||||
})
|
||||
}
|
||||
|
||||
/// `angle` (radians) brought into −π..π.
|
||||
pub(super) fn wrap_angle(angle: f64) -> f64 {
|
||||
let turn = std::f64::consts::TAU;
|
||||
let a = angle.rem_euclid(turn);
|
||||
if a > std::f64::consts::PI { a - turn } else { a }
|
||||
}
|
||||
|
||||
/// The instances of a symbol set by where they are, to find those under a brush without looking at
|
||||
/// every one for every point of a stroke.
|
||||
pub(super) struct Grid {
|
||||
cell: f64,
|
||||
looks: Vec<Look>,
|
||||
cells: HashMap<(i64, i64), Vec<usize>>,
|
||||
}
|
||||
|
||||
fn key(p: Point, cell: f64) -> (i64, i64) {
|
||||
((p.x / cell).floor() as i64, (p.y / cell).floor() as i64)
|
||||
}
|
||||
|
||||
/// The indices in the cell of `at`, then in the eight around it. Saturating: a point far out on the
|
||||
/// canvas has a key at the end of the range.
|
||||
fn around(cells: &HashMap<(i64, i64), Vec<usize>>, at: Point, cell: f64) -> impl Iterator<Item = usize> + '_ {
|
||||
let (cx, cy) = key(at, cell);
|
||||
let ring = (cx.saturating_sub(1)..=cx.saturating_add(1))
|
||||
.flat_map(move |x| (cy.saturating_sub(1)..=cy.saturating_add(1)).map(move |y| (x, y)))
|
||||
.filter(move |c| *c != (cx, cy));
|
||||
std::iter::once((cx, cy)).chain(ring).flat_map(move |c| cells.get(&c).into_iter().flatten().copied())
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// `looks` in cells `cell` points wide (the brush's radius).
|
||||
pub fn new(looks: Vec<Look>, cell: f64) -> Self {
|
||||
let cell = cell.max(1.0);
|
||||
let mut cells: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
for (i, l) in looks.iter().enumerate() {
|
||||
cells.entry(key(l.center, cell)).or_default().push(i);
|
||||
}
|
||||
Self { cell, looks, cells }
|
||||
}
|
||||
|
||||
/// The mean of the instances within `radius` (at most the cell width) of `at`, with
|
||||
/// [`Mean::gap`] when `with_gap` is set.
|
||||
pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option<Mean> {
|
||||
let near: Vec<&Look> =
|
||||
around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect();
|
||||
mean(&near, at, with_gap)
|
||||
}
|
||||
}
|
||||
|
||||
/// `symbol.setDensity {from, to, ids?|id?}`: space the instances of the selected symbol sets as
|
||||
/// Symbol Set Density `to` packs them, from the density each set was created at or last given
|
||||
/// (`from` for a set without one): each instance moves along the line from the middle of its set's
|
||||
/// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it.
|
||||
/// Every selected set then has density `to`, also one whose instances do not move. One undo step,
|
||||
/// and none when no instance moves and every set already has density `to`.
|
||||
pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.setDensity";
|
||||
let density = |key: &str| match p.get(key) {
|
||||
Some(v) => v.as_f64().filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| bad(C, format!("`{key}` must be a number from 1 to 10, not {v}"))),
|
||||
None => Err(bad(C, format!("missing `{key}`"))),
|
||||
};
|
||||
let (from, to) = (density("from")?, density("to")?);
|
||||
crate::cmd::edit::refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let named = named_ids(p)?;
|
||||
let ids: Vec<NodeId> = named.clone().unwrap_or_else(|| st.selection.objects.clone());
|
||||
if let Some(missing) = named.iter().flatten().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::Other(format!("no object {}", missing.0)));
|
||||
}
|
||||
let editable = d.editable();
|
||||
let mut sets: Vec<NodeId> = vec![];
|
||||
for id in ids {
|
||||
if d.node(id).is_some_and(is_symbol_set) && editable(id) && !sets.contains(&id) {
|
||||
sets.push(id);
|
||||
}
|
||||
}
|
||||
if sets.is_empty() {
|
||||
return Err(EngineError::Other("no symbol set selected".into()));
|
||||
}
|
||||
let mut moves: Vec<(NodeId, Vec2)> = vec![];
|
||||
let mut changed: Vec<NodeId> = vec![];
|
||||
for set in &sets {
|
||||
// A set packs from the density it was created at or last given, else from `from`.
|
||||
let own = set_density_of(d, *set);
|
||||
let ratio = spacing(to) / spacing(own.unwrap_or(from));
|
||||
// A set takes density `to` even when none of its instances moves (one instance, or each
|
||||
// locked or on top of the others), so a later change packs it from `to`.
|
||||
let restamp = own != Some(to);
|
||||
let centers: Vec<(NodeId, Point)> =
|
||||
d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect();
|
||||
if centers.len() < 2 {
|
||||
if restamp {
|
||||
changed.push(*set);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point();
|
||||
let before = moves.len();
|
||||
// A locked or hidden instance stays where it is.
|
||||
moves.extend(
|
||||
centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9),
|
||||
);
|
||||
if moves.len() > before || restamp {
|
||||
changed.push(*set);
|
||||
}
|
||||
}
|
||||
drop(editable);
|
||||
if !changed.is_empty() {
|
||||
s.edit("Symbol Set Density", |d, _| {
|
||||
for (id, v) in &moves {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(Affine::translate(*v), false);
|
||||
}
|
||||
}
|
||||
record_set_density(d, &changed, to);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": ids_json(&changed), "count": moves.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(x: f64, y: f64) -> Look {
|
||||
Look { center: Point::new(x, y), size: 20.0, angle: 0.0, opacity: 1.0, fill: None }
|
||||
}
|
||||
|
||||
/// The distance from each instance in `from` to the nearest other one in `refs`, measured
|
||||
/// against every other instance.
|
||||
fn brute(refs: &[&Look], from: impl Iterator<Item = usize>) -> Vec<f64> {
|
||||
from.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)).collect()
|
||||
}
|
||||
|
||||
/// The gaps are each instance's distance to its nearest neighbor, measured against every other
|
||||
/// instance: close pairs whose members are far apart in the order, instances on top of each
|
||||
/// other, instances far from all others, many instances close together, and many on one line.
|
||||
#[test]
|
||||
fn nearest_gaps_match_measuring_every_pair() {
|
||||
let mut looks: Vec<Look> = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect();
|
||||
// The second member of each pair comes 300 places later.
|
||||
looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0)));
|
||||
looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]);
|
||||
// 400 instances within one point of each other, and 200 on one upright line.
|
||||
looks.extend((0..400).map(|i| at(700.0 + f64::from(i % 20) * 0.05, 700.0 + f64::from(i / 20) * 0.05)));
|
||||
looks.extend((0..200).map(|i| at(-50.0, f64::from(i) * 1.5)));
|
||||
let refs: Vec<&Look> = looks.iter().collect();
|
||||
assert_eq!(nearest_gaps(&refs), brute(&refs, 0..refs.len()));
|
||||
assert_eq!(nearest_gaps(&refs[..1]), [f64::INFINITY]);
|
||||
assert_eq!(nearest_gaps(&refs[..0]), Vec::<f64>::new());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::dynamic::{fit_overrides, type_id, type_param};
|
||||
use super::symbolism::{Grid, Mean, Method, Sides, look, mean, method_param, natural_side, record_set_density, spacing, spray_modes, wrap_angle};
|
||||
use super::{
|
||||
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json,
|
||||
@@ -906,16 +907,40 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result<Valu
|
||||
// ---------- symbolism tools ----------
|
||||
|
||||
fn points(p: &Value, cmd: &str) -> Result<Vec<Point>> {
|
||||
Ok(samples(p, cmd)?.into_iter().map(|(q, _)| q).collect())
|
||||
}
|
||||
|
||||
/// The stroke's points, each with its pen pressure: the third number of `[x, y, pressure]`, kept
|
||||
/// within 0..1, and 1 for a point that gives none (or null). A pressure that isn't a number is an
|
||||
/// error.
|
||||
fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
|
||||
let v: Vec<Point> = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect();
|
||||
if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
let mut v = Vec::with_capacity(a.len());
|
||||
for q in a {
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
let pressure = match q.get(2) {
|
||||
None | Some(Value::Null) => 1.0,
|
||||
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
|
||||
};
|
||||
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
|
||||
}
|
||||
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
return Err(bad(cmd, "points must be finite [x,y] pairs"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The fill of the graphic style `p` names with `style`, else of the document's first style after
|
||||
/// the default one.
|
||||
fn style_paint(d: &Document, p: &Value) -> Option<Paint> {
|
||||
match str_param(p, "style") {
|
||||
Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
|
||||
fn jitter(i: usize, q: Point) -> (f64, f64, f64) {
|
||||
pub(super) fn jitter(i: usize, q: Point) -> (f64, f64, f64) {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64;
|
||||
for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] {
|
||||
h ^= v;
|
||||
@@ -926,7 +951,8 @@ fn jitter(i: usize, q: Point) -> (f64, f64, f64) {
|
||||
(f(0), f(1), f(2))
|
||||
}
|
||||
|
||||
fn is_symbol_set(n: &Node) -> bool {
|
||||
/// Whether `n` is a symbol set: the group the Symbol Sprayer sprays instances into.
|
||||
pub fn is_symbol_set(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set")
|
||||
}
|
||||
|
||||
@@ -939,6 +965,20 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0);
|
||||
let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0);
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let modes = spray_modes(p, C)?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let stain = match color_param(p, "color", C)? {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
None => s.paint.fill.color().unwrap_or(Color::BLACK),
|
||||
};
|
||||
if let Some(v) = p.get("style").filter(|v| !v.is_string()) {
|
||||
return Err(bad(C, format!("`style` must be a graphic style's name, not {v}")));
|
||||
}
|
||||
let style = style_paint(&st.doc, p);
|
||||
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
|
||||
if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
|
||||
return Err(bad(C, format!("unknown graphic style `{n}`")));
|
||||
}
|
||||
let size = natural_size(&st.doc, &name);
|
||||
let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set));
|
||||
// Only a new Symbol Set needs a layer that takes new art.
|
||||
@@ -965,26 +1005,82 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
return Ok(json!({ "count": n }));
|
||||
}
|
||||
// Keep instances at least this far apart along the stroke (denser = closer).
|
||||
let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1);
|
||||
let mut placed: Vec<Point> = vec![];
|
||||
let side = natural_side(&st.doc, &name);
|
||||
// The symbol's longest side as drawn at its own size: its art's, when it has no recorded size.
|
||||
let recorded = stored_natural_size(&st.doc, &name).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0);
|
||||
let extent = match recorded {
|
||||
Some((w, h)) => w.max(h),
|
||||
None => {
|
||||
let art = st.doc.symbol_art_bounds(&name).map(|r| r.width().max(r.height()));
|
||||
art.filter(|e| e.is_finite() && *e > 0.0).unwrap_or(size.0.max(size.1))
|
||||
}
|
||||
};
|
||||
// The scale a new instance is placed at, before the User Defined size jitter. Size: Average is
|
||||
// the mean size on the page under the brush, of any symbol, or the symbol's own size with none
|
||||
// there (not `scale`).
|
||||
let placed_scale = |near: Option<&Mean>| {
|
||||
if modes.size { near.map(|m| m.size / side).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0) } else { scale }
|
||||
};
|
||||
// The instances the selected set has, for the values a new one takes as their average.
|
||||
let existing = set.filter(|_| modes.any_average()).map(|g| {
|
||||
let d = &st.doc;
|
||||
let mut sides = Sides::new();
|
||||
let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c, &mut sides)).collect();
|
||||
Grid::new(looks, radius)
|
||||
});
|
||||
// Each instance to add: where, the mean of the set's instances under the brush there, and the
|
||||
// direction of the stroke there (None while the pointer has not moved).
|
||||
let mut placed: Vec<(Point, Option<Mean>, Option<Vec2>)> = vec![];
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
let (jx, jy, _) = jitter(i, *q);
|
||||
let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5);
|
||||
if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 {
|
||||
let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch));
|
||||
// Keep instances at least this far apart along the stroke (denser = closer), by the size
|
||||
// the instance is placed at.
|
||||
let min_gap = extent * placed_scale(near.as_ref()) * spacing(density);
|
||||
// Scrunch: Average spaces new instances as the ones under the brush are spaced.
|
||||
let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap);
|
||||
if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 {
|
||||
continue;
|
||||
}
|
||||
placed.push(c);
|
||||
let along = pts.get(i + 1).unwrap_or(q).to_vec2() - pts.get(i.saturating_sub(1)).unwrap_or(q).to_vec2();
|
||||
placed.push((c, near, (along.hypot() > 1e-9).then_some(along)));
|
||||
}
|
||||
let count = placed.len();
|
||||
let reg = s.doc()?.doc.symbol_registration(&name);
|
||||
let id = s.edit("Symbol Sprayer", |d, sel| {
|
||||
let mut nodes = vec![];
|
||||
for (i, c) in placed.iter().enumerate() {
|
||||
for (i, (c, near, along)) in placed.iter().enumerate() {
|
||||
let (_, _, js) = jitter(i + 7, *c);
|
||||
let k = scale * (1.0 + js * 0.1);
|
||||
let near = near.as_ref();
|
||||
// User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained
|
||||
// with the fill color and given the style, each in full. Size: Average has no size jitter.
|
||||
let k = if modes.size { placed_scale(near) } else { scale * (1.0 + js * 0.1) };
|
||||
let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) };
|
||||
let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2());
|
||||
let id = d.alloc_id();
|
||||
nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) }));
|
||||
let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: turn * place_xf(*c, size, reg) * Affine::scale(k) });
|
||||
if modes.screen
|
||||
&& let Some(m) = near
|
||||
{
|
||||
n.opacity = (m.opacity as f32).clamp(0.0, 1.0);
|
||||
}
|
||||
// The stain and the style are both the instance's fill: the style, set last, replaces
|
||||
// the stain, an averaged one too when the instances under the brush have a fill.
|
||||
let averaged = near.filter(|m| m.amount > 0.0).and_then(|m| Some((m.paint.clone()?, m.amount as f32)));
|
||||
let mut fill = if modes.stain { averaged.clone() } else { Some((Paint::solid(stain), 1.0)) };
|
||||
if modes.style {
|
||||
fill = averaged.or(fill);
|
||||
} else if let Some(paint) = style.as_ref().filter(|p| !matches!(p, Paint::None)) {
|
||||
// A style without a fill (the default style) gives none.
|
||||
fill = Some((paint.clone(), 1.0));
|
||||
}
|
||||
if let Some((paint, amount)) = fill {
|
||||
let mut f = FillLayer::new(paint);
|
||||
f.opacity = amount.clamp(0.0, 1.0);
|
||||
n.appearance.items.insert(0, AppearanceItem::Fill(f));
|
||||
}
|
||||
nodes.push(n);
|
||||
}
|
||||
let gid = match set {
|
||||
Some(g) => {
|
||||
@@ -1001,13 +1097,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
gid
|
||||
}
|
||||
};
|
||||
// A new set has the density it is sprayed at; more instances sprayed into a set leave the
|
||||
// density the set has.
|
||||
if set.is_none() {
|
||||
record_set_density(d, &[gid], density);
|
||||
}
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0, "count": count }))
|
||||
}
|
||||
|
||||
fn instance_center(n: &Node) -> Option<Point> {
|
||||
pub(super) fn instance_center(n: &Node) -> Option<Point> {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO),
|
||||
_ => None,
|
||||
@@ -1021,10 +1122,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("unknown tool `{tool}`")));
|
||||
}
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let pts = points(p, C)?;
|
||||
let pts = samples(p, C)?;
|
||||
let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0);
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let use_pressure = switch_or(p, "usePressure", false, C)?;
|
||||
let proportional = switch_or(p, "proportional", true, C)?;
|
||||
let affects_density = switch_or(p, "affectsDensity", false, C)?;
|
||||
// The Symbol Shifter has no Method.
|
||||
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
crate::cmd::edit::refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
@@ -1032,10 +1138,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
None => s.paint.fill.color().unwrap_or(Color::BLACK),
|
||||
};
|
||||
let style_paint = match str_param(p, "style") {
|
||||
Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
};
|
||||
let style_paint = style_paint(&st.doc, p);
|
||||
let candidates: Vec<NodeId> = {
|
||||
let d = &st.doc;
|
||||
let mut v = vec![];
|
||||
@@ -1065,62 +1168,165 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"screen" => "Symbol Screener",
|
||||
_ => "Symbol Styler",
|
||||
};
|
||||
let count = s.edit(label, |d, _| {
|
||||
// Random: each instance's share of the tool's change, from none of it to twice it, the same
|
||||
// for the whole stroke (and for every preview of it).
|
||||
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
|
||||
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
|
||||
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
|
||||
let mut touched = std::collections::BTreeSet::new();
|
||||
for (j, q) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO };
|
||||
let mut sides = Sides::new();
|
||||
for (j, (q, pressure)) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
|
||||
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
|
||||
let strength = if use_pressure { *pressure } else { intensity };
|
||||
// Average: the mean of the instances under the brush, as they are at this point.
|
||||
let target = (method == Method::Average)
|
||||
.then(|| {
|
||||
let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius);
|
||||
let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n, &mut sides))).collect();
|
||||
mean(&looks.iter().collect::<Vec<_>>(), *q, false)
|
||||
})
|
||||
.flatten();
|
||||
for id in &candidates {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let Some(c) = instance_center(n) else { continue };
|
||||
let Some(c) = d.node(*id).and_then(instance_center) else { continue };
|
||||
let dist = c.distance(*q);
|
||||
if dist > radius {
|
||||
continue;
|
||||
}
|
||||
let w = intensity * (1.0 - dist / radius).max(0.0);
|
||||
let w = strength * (1.0 - dist / radius).max(0.0);
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
touched.insert(*id);
|
||||
// Average needs the instance's own values, so it leaves an instance without a size
|
||||
// as it is; the other methods change it as before.
|
||||
// The instance's own values are read for Average only.
|
||||
let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n, &mut sides))).flatten();
|
||||
let avg = match (method, &target, own) {
|
||||
(Method::Average, Some(t), Some(cur)) => Some((t, cur)),
|
||||
// No mean under the brush (every instance there without a size), or none of
|
||||
// its own.
|
||||
(Method::Average, ..) => continue,
|
||||
_ => None,
|
||||
};
|
||||
// Average leaves an instance that already has the mean as it is.
|
||||
let at_mean = avg.as_ref().is_some_and(|(t, cur)| match tool.as_str() {
|
||||
"scrunch" => {
|
||||
let out = (c - t.middle).hypot();
|
||||
out <= 1e-9 || (t.reach - out).abs() < 1e-9
|
||||
}
|
||||
"size" => (t.size / cur.size - 1.0).abs() < 1e-9,
|
||||
"spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9,
|
||||
"stain" | "style" => {
|
||||
(t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none())
|
||||
}
|
||||
"screen" => (t.opacity - cur.opacity).abs() < 1e-6,
|
||||
_ => false,
|
||||
});
|
||||
if at_mean {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
// Counted only when it changes: Random can give an instance no share of the change.
|
||||
let before = n.clone();
|
||||
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
|
||||
let share = share(*id);
|
||||
match tool.as_str() {
|
||||
"shift" => n.transform(Affine::translate(delta * w.min(1.0)), false),
|
||||
"scrunch" => {
|
||||
let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 };
|
||||
let v = match &avg {
|
||||
// Toward the instances' mean distance from their middle.
|
||||
Some((t, _)) => {
|
||||
let out = c - t.middle;
|
||||
if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO }
|
||||
}
|
||||
None => (*q - c) * (0.15 * w * share) * if alt { -1.0 } else { 1.0 },
|
||||
};
|
||||
n.transform(Affine::translate(v), false);
|
||||
}
|
||||
"size" => {
|
||||
let k = 1.0 + 0.08 * w;
|
||||
n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false);
|
||||
let k = match &avg {
|
||||
Some((t, cur)) => (t.size / cur.size).powf(w.min(1.0)),
|
||||
None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }),
|
||||
};
|
||||
// Without Proportional Resizing a drag resizes along its own direction: a
|
||||
// level drag the width, an upright one the height. A click resizes both.
|
||||
// The first point of a drag takes the direction to the second.
|
||||
let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) };
|
||||
let (kx, ky) = if proportional || avg.is_some() || along.hypot() <= 1e-9 {
|
||||
(k, k)
|
||||
} else {
|
||||
let level = along.x.abs() / (along.x.abs() + along.y.abs());
|
||||
(k.powf(2.0 * level), k.powf(2.0 * (1.0 - level)))
|
||||
};
|
||||
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
|
||||
// Resizing Affects Density: instances move away from the brush's center as
|
||||
// they grow and toward it as they shrink.
|
||||
if affects_density {
|
||||
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
|
||||
}
|
||||
}
|
||||
"spin" => {
|
||||
// Turn towards the drag direction; a click spins a little.
|
||||
let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w };
|
||||
n.transform(about(Affine::rotate(if alt { -a } else { a })), false);
|
||||
let a = match (&avg, method) {
|
||||
(Some((t, cur)), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0),
|
||||
// A turn either way, whichever way the drag runs.
|
||||
(None, Method::Random) => 0.1 * w * (share - 1.0),
|
||||
// Turn towards the drag direction; a click spins a little.
|
||||
(None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w,
|
||||
(None, _) => 0.05 * w,
|
||||
};
|
||||
n.transform(about(Affine::rotate(if alt && avg.is_none() { -a } else { a })), false);
|
||||
}
|
||||
"stain" | "style" => {
|
||||
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
|
||||
if tool == "style" && alt {
|
||||
n.appearance.items.clear();
|
||||
continue;
|
||||
}
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 };
|
||||
let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) };
|
||||
let (paint, o) = match &avg {
|
||||
// Toward the mean amount, keeping the stain or style the instance has.
|
||||
Some((t, look)) => {
|
||||
let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
|
||||
}
|
||||
// Alt with the Symbol Styler removes the instance's appearance.
|
||||
None if tool == "style" && alt => {
|
||||
n.appearance.items.clear();
|
||||
(paint, 0.0)
|
||||
}
|
||||
None => {
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
let step = match (tool.as_str(), method) {
|
||||
// Random: the instance's share of the style, scaled by the
|
||||
// brush strength there.
|
||||
("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
|
||||
("style", _) => 1.0,
|
||||
_ => (0.15 * w * share) as f32,
|
||||
};
|
||||
(paint, if alt { cur - step } else { cur + step })
|
||||
}
|
||||
};
|
||||
n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_)));
|
||||
if o > 0.0 {
|
||||
let mut f = FillLayer::new(paint);
|
||||
f.opacity = o;
|
||||
f.opacity = o.min(1.0);
|
||||
n.appearance.items.insert(0, AppearanceItem::Fill(f));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let step = (0.1 * w) as f32;
|
||||
n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) };
|
||||
let step = (0.1 * w * share) as f32;
|
||||
n.opacity = match &avg {
|
||||
// The mean may be below the 5% the Screener otherwise stops at.
|
||||
Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.0, 1.0),
|
||||
None if alt => (n.opacity + step).min(1.0),
|
||||
None => (n.opacity - step).max(0.05),
|
||||
};
|
||||
}
|
||||
}
|
||||
if *n != before {
|
||||
touched.insert(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(touched.len())
|
||||
// An instance the stroke moved away and back again is not counted.
|
||||
touched.retain(|id| d.node(*id) != orig.node(*id));
|
||||
Ok((touched.len(), !touched.is_empty()))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
@@ -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;
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -181,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Image Trace View",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}",
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}",
|
||||
has_selection_or_ids,
|
||||
trace_set_view
|
||||
),
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given.
|
||||
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
|
||||
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
|
||||
}
|
||||
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for.
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
// view's divider.
|
||||
let view = view.unwrap_or_else(|| src.trace_view());
|
||||
g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
|
||||
let mut t = json!({ "preset": preset_label, "params": params_json, "view": view.id() });
|
||||
if let Some(split) = src.extras().trace.as_deref().and_then(|t| t.get("split")).filter(|v| !v.is_null()) {
|
||||
t["split"] = split.clone();
|
||||
}
|
||||
g.extras_mut().trace = Some(Box::new(t));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
@@ -1127,23 +1138,37 @@ fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.setView";
|
||||
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
|
||||
let split = split_param(C, p)?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
|
||||
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
|
||||
let result = |d: &vectorcraft_doc::Document| {
|
||||
let mut r = json!({ "ids": ids_json(&targets), "view": view.id() });
|
||||
if view == TraceView::Split
|
||||
&& let Some(n) = targets.first().and_then(|g| d.node(*g))
|
||||
{
|
||||
r["split"] = json!(split.unwrap_or_else(|| n.trace_split()));
|
||||
}
|
||||
r
|
||||
};
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) {
|
||||
return Ok(result(d));
|
||||
}
|
||||
s.edit("Image Trace View", |d, _| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" })));
|
||||
}
|
||||
if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) {
|
||||
t.insert("view".into(), json!(view.id()));
|
||||
} else {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
|
||||
if let Some(f) = split {
|
||||
t.insert("split".into(), json!(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
|
||||
Ok(result(&s.doc()?.doc))
|
||||
}
|
||||
|
||||
pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -47,10 +47,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Conflicts",
|
||||
[],
|
||||
None,
|
||||
"{} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none",
|
||||
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
|
||||
has_doc,
|
||||
conflicts
|
||||
),
|
||||
cmd!(
|
||||
query "clipboard.profileMismatch",
|
||||
"Paste Profile Mismatch",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument?, ids?: as edit.dropSelection, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\", convertible}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then; an assigned profile removed since: the working space) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). convertible: false when either profile is not available (removed with color.removeProfile): the colors then keep their numbers whatever the choice, and default is preserveNumbers. With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none",
|
||||
has_doc,
|
||||
profile_mismatch
|
||||
),
|
||||
];
|
||||
v.extend(flavours::specs());
|
||||
v
|
||||
@@ -100,6 +109,15 @@ pub struct Clipboard {
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
|
||||
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
|
||||
/// from outside an open document. Paste compares them with the destination's
|
||||
/// ([`super::colormgmt::paste_mismatches`]).
|
||||
pub source_profiles: Option<[String; 2]>,
|
||||
/// The colors were converted for this paste ([`super::colormgmt::paste_profiles`]): back in the
|
||||
/// source document its resources of the same names are compared with them, as another
|
||||
/// document's are, while its layers are still found by id.
|
||||
pub colors_converted: bool,
|
||||
}
|
||||
|
||||
/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level
|
||||
@@ -264,6 +282,7 @@ impl Clipboard {
|
||||
pub fn from_node(st: &DocState, node: Node) -> Self {
|
||||
let mut clip = Self::gather(&st.doc, vec![node]);
|
||||
clip.source_doc = Some(st.uid);
|
||||
clip.source_profiles = Some(super::colormgmt::effective_profiles(&st.doc));
|
||||
clip
|
||||
}
|
||||
|
||||
@@ -335,6 +354,7 @@ impl Clipboard {
|
||||
source_artboard: board.and_then(|i| d.artboards.get(i)).map(|a| a.rect),
|
||||
source_layers,
|
||||
source_doc: Some(st.uid),
|
||||
source_profiles: Some(super::colormgmt::effective_profiles(d)),
|
||||
..Self::gather(d, nodes)
|
||||
}
|
||||
}
|
||||
@@ -369,7 +389,7 @@ impl Clipboard {
|
||||
/// The swatch name conflicts pasting into `st` raises, as (pasted, document) swatches: none
|
||||
/// back in the document the objects came from.
|
||||
pub fn swatch_conflicts<'a>(&'a self, st: &'a DocState) -> Vec<(&'a Swatch, &'a Swatch)> {
|
||||
if self.source_doc == Some(st.uid) {
|
||||
if self.source_doc == Some(st.uid) && !self.colors_converted {
|
||||
return vec![];
|
||||
}
|
||||
self.conflicts(&st.doc, &self.used())
|
||||
@@ -419,6 +439,56 @@ impl Clipboard {
|
||||
d
|
||||
}
|
||||
|
||||
/// The clipboard with every color of its objects and of the resources it carries (swatches,
|
||||
/// symbols, patterns, graphic styles, brushes, character and paragraph styles, the background
|
||||
/// colors of copied artboards) mapped by `conv`, as Document Color Mode maps a document's
|
||||
/// ([`super::colormgmt::convert_art_and_style_colors`]).
|
||||
/// Images keep their pixels.
|
||||
pub(crate) fn with_colors(&self, conv: &dyn Fn(&vectorcraft_color::Color) -> vectorcraft_color::Color) -> Self {
|
||||
let mut d = self.to_document();
|
||||
// Only what the clipboard carries: not the swatches, graphic styles and brushes every new
|
||||
// document starts with.
|
||||
d.swatches = self.swatches.clone().into();
|
||||
d.swatch_groups = Default::default();
|
||||
d.graphic_styles = self.graphic_styles.clone().into();
|
||||
vectorcraft_brush::store(&mut d, &self.brushes);
|
||||
// Not the stand-in document's own artboard and Document Setup colors: only what the
|
||||
// clipboard carries is mapped.
|
||||
super::colormgmt::convert_art_and_style_colors(&mut d, conv);
|
||||
// `to_document` puts the objects in its one layer.
|
||||
let nodes = d.layers.first().and_then(|l| l.children()).map(|ch| ch.iter().map(|n| (**n).clone()).collect()).unwrap_or_default();
|
||||
Self {
|
||||
nodes,
|
||||
symbols: d.symbols.clone(),
|
||||
patterns: d.patterns.clone(),
|
||||
swatches: d.swatches.to_vec(),
|
||||
graphic_styles: d.graphic_styles.to_vec(),
|
||||
char_styles: d.char_styles.to_vec(),
|
||||
para_styles: d.para_styles.to_vec(),
|
||||
brushes: vectorcraft_brush::library(&d),
|
||||
images: self.images.clone(),
|
||||
symbol_options: self.symbol_options.clone(),
|
||||
source_artboard: self.source_artboard,
|
||||
source_layers: self.source_layers.clone(),
|
||||
source_doc: self.source_doc,
|
||||
// The background colors of copied artboards map too.
|
||||
artboards: self
|
||||
.artboards
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let mut a = a.clone();
|
||||
if let Some(c) = a.color.as_mut() {
|
||||
*c = conv(c);
|
||||
}
|
||||
a
|
||||
})
|
||||
.collect(),
|
||||
guides: self.guides.clone(),
|
||||
source_profiles: self.source_profiles.clone(),
|
||||
colors_converted: self.colors_converted,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects as standalone SVG (`None` when there are none).
|
||||
pub fn svg(&self) -> Option<String> {
|
||||
if !self.has_art() {
|
||||
@@ -486,17 +556,33 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": s.load_clipboard(clip, p)? }))
|
||||
}
|
||||
|
||||
fn conflicts(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
|
||||
let list: Vec<Value> = s
|
||||
.clipboard
|
||||
.swatch_conflicts(s.doc()?)
|
||||
// The swatches as the paste brings them: converted from another profile when it converts.
|
||||
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
|
||||
let st = s.doc()?;
|
||||
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
|
||||
let list: Vec<Value> = converted
|
||||
.as_ref()
|
||||
.unwrap_or(&s.clipboard)
|
||||
.swatch_conflicts(st)
|
||||
.into_iter()
|
||||
.map(|(c, t)| json!({"name": c.name, "document": hex(t), "clipboard": hex(c), "spot": c.spot}))
|
||||
.collect();
|
||||
Ok(json!({ "swatches": list }))
|
||||
}
|
||||
|
||||
fn profile_mismatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "clipboard.profileMismatch";
|
||||
// With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's.
|
||||
let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None };
|
||||
let clip = dropped.as_ref().unwrap_or(&s.clipboard);
|
||||
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
|
||||
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
|
||||
let list: Vec<Value> = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc, !all_artboards).iter().map(|m| m.to_json()).collect();
|
||||
Ok(json!({ "mismatches": list }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -20,12 +20,14 @@ use std::sync::Arc;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::Brush;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
|
||||
SymbolRegistration, TextStyleDef,
|
||||
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
|
||||
SymbolNineSlice, SymbolRegistration, TextStyleDef,
|
||||
};
|
||||
|
||||
use super::super::brushsym::{set_natural_size, stored_natural_size};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
|
||||
use super::super::patterncmds::add_pattern;
|
||||
use super::super::{EngineError, Result, bad, unique_name};
|
||||
@@ -517,6 +519,36 @@ fn copy_of(base: &str, name: &str) -> bool {
|
||||
name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// The `i`th numbered copy of a Kinsoku Shori set's name `base` ("name 2"), within
|
||||
/// [`KINSOKU_NAME_MAX`]: when it would be too long, the number takes the place of the name's last
|
||||
/// characters, and spaces left at the end of what remains are dropped.
|
||||
fn numbered_kinsoku_name(base: &str, i: usize) -> String {
|
||||
let number = format!(" {i}");
|
||||
let head: String = base.chars().take(KINSOKU_NAME_MAX.saturating_sub(number.chars().count())).collect();
|
||||
format!("{}{number}", head.trim_end())
|
||||
}
|
||||
|
||||
/// [`unique_name`] for a pasted Kinsoku Shori set among `sets` (a document's custom sets, any
|
||||
/// case), with names that fit [`KINSOKU_NAME_MAX`] ([`numbered_kinsoku_name`]).
|
||||
fn unique_kinsoku_name(base: &str, sets: &[KinsokuSet]) -> String {
|
||||
let taken = |n: &str| KinsokuSet::named(sets, n).is_some();
|
||||
if !taken(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2..).map(|i| numbered_kinsoku_name(base, i)).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Is `name` (any case) the Kinsoku Shori set name `base` or a numbered copy of it, as
|
||||
/// [`unique_kinsoku_name`] names one?
|
||||
fn kinsoku_copy_of(base: &str, name: &str) -> bool {
|
||||
KinsokuSet::same_name(base, name)
|
||||
|| name.rsplit_once(' ').is_some_and(|(_, n)| {
|
||||
!n.is_empty()
|
||||
&& n.bytes().all(|b| b.is_ascii_digit())
|
||||
&& n.parse::<usize>().is_ok_and(|i| i >= 2 && KinsokuSet::same_name(&numbered_kinsoku_name(base, i), name))
|
||||
})
|
||||
}
|
||||
|
||||
/// The document's own resource for pasted resource `name`, among the document's `names`: the
|
||||
/// one of that name when `same` holds for it (or, pasting back into the source document, at all),
|
||||
/// else a numbered copy of it (added by an earlier paste) that is the same. `None`: add it.
|
||||
@@ -600,6 +632,9 @@ struct Relink {
|
||||
styles: BTreeMap<u32, u32>,
|
||||
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
|
||||
colors: BTreeMap<String, Color>,
|
||||
/// A custom Kinsoku set the pasted paragraphs and paragraph styles hold → the document's set
|
||||
/// they take, or none (Hard) when the document has no room for it ([`Clipboard::import_kinsoku_sets`]).
|
||||
kinsoku: HashMap<KinsokuSet, Option<Arc<KinsokuSet>>>,
|
||||
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
|
||||
keep_styles: bool,
|
||||
}
|
||||
@@ -646,11 +681,19 @@ impl Relink {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A 3D effect's mapped graphics follow their symbols' names in the document. Each name is
|
||||
// looked up once, so renames that chain (A to B, B to C) do not apply twice.
|
||||
// A 3D effect's mapped graphics and Map Art maps follow their symbols' names in the
|
||||
// document. Each name is looked up once, so renames that chain (A to B, B to C) do not
|
||||
// apply twice.
|
||||
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) {
|
||||
let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut);
|
||||
for e in a.effects.iter_mut().chain(items) {
|
||||
let key = if vectorcraft_render::effects::takes_graphics(&e.id) {
|
||||
vectorcraft_render::effects::GRAPHICS
|
||||
} else if vectorcraft_render::effects::takes_map_art(&e.id) {
|
||||
vectorcraft_render::effects::MAP_ART
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let list = e.params.get_mut(key).and_then(Value::as_array_mut);
|
||||
for g in list.into_iter().flatten() {
|
||||
if let Some(Value::String(s)) = g.get_mut("symbol") {
|
||||
self.name(Res::Symbol, s);
|
||||
@@ -667,6 +710,17 @@ impl Relink {
|
||||
}
|
||||
}
|
||||
fn attrs(&self, a: &mut Map<String, Value>) {
|
||||
if let Some(to) =
|
||||
a.get("kinsoku_set").and_then(|v| serde_json::from_value::<KinsokuSet>(v.clone()).ok()).and_then(|set| self.kinsoku.get(&set))
|
||||
{
|
||||
match to {
|
||||
Some(set) => a.insert("kinsoku_set".into(), json!(set)),
|
||||
None => {
|
||||
a.insert("kinsoku".into(), json!(Kinsoku::Hard));
|
||||
a.insert("kinsoku_set".into(), Value::Null)
|
||||
}
|
||||
};
|
||||
}
|
||||
for k in STYLE_PAINTS {
|
||||
let Some(before) = style_paint(a, k) else { continue };
|
||||
let mut p = before.clone();
|
||||
@@ -707,6 +761,10 @@ impl Relink {
|
||||
if let Some(s) = &mut pa.style_name {
|
||||
self.name(Res::ParaStyle, s);
|
||||
}
|
||||
// A graph draws its labels again from the paragraph attributes it keeps for them.
|
||||
if let Some(to) = pa.kinsoku_set.as_deref().and_then(|set| self.kinsoku.get(set)) {
|
||||
pa.kinsoku_set = to.clone();
|
||||
}
|
||||
}
|
||||
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
|
||||
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
|
||||
@@ -721,10 +779,21 @@ impl Relink {
|
||||
self.name(Res::CharStyle, s);
|
||||
}
|
||||
}
|
||||
// Lines break anew when a paragraph's set takes other characters or Hard.
|
||||
let mut relaid = false;
|
||||
for pa in t.para_styles_mut() {
|
||||
if let Some(s) = &mut pa.style_name {
|
||||
self.name(Res::ParaStyle, s);
|
||||
}
|
||||
if let Some(set) = pa.kinsoku_set.as_deref()
|
||||
&& let Some(to) = self.kinsoku.get(set)
|
||||
{
|
||||
relaid |= to.as_deref().is_none_or(|to| kinsoku_chars(to) != kinsoku_chars(set));
|
||||
pa.kinsoku_set = to.clone();
|
||||
}
|
||||
}
|
||||
if relaid {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
|
||||
@@ -738,6 +807,11 @@ impl Relink {
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters and sequences of Kinsoku set `s`, without its name.
|
||||
fn kinsoku_chars(s: &KinsokuSet) -> (&[char], &[char], &[char], &[String]) {
|
||||
(&s.cannot_start, &s.cannot_end, &s.hanging, &s.inseparable)
|
||||
}
|
||||
|
||||
/// Is `ours` (a document definition's art) the art of `theirs` (a pasted one's) once that is
|
||||
/// relinked by `r`? Graphic style links don't count: they are relinked last.
|
||||
fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
|
||||
@@ -1121,8 +1195,11 @@ impl Clipboard {
|
||||
/// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added
|
||||
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
|
||||
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
|
||||
/// `same_doc`: `d` is the document the objects were copied from. With colors converted for the
|
||||
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
|
||||
/// document's are, while its image blobs are still the document's own under their keys.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used(d, &self.used(), choices, same_doc)
|
||||
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
@@ -1155,10 +1232,24 @@ impl Clipboard {
|
||||
/// other is matched on its own ([`loop_groups`]). Pasted back into its own document
|
||||
/// (`same_doc`), each definition of a loop is the document's of its name.
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
|
||||
self.import_used_with_images(d, used, choices, same_doc, same_doc)
|
||||
}
|
||||
|
||||
/// [`Self::import_used`], with the image blobs matched as those of the document they came
|
||||
/// from when `same_doc_images`.
|
||||
fn import_used_with_images(
|
||||
&self,
|
||||
d: &mut Document,
|
||||
used: &Used,
|
||||
choices: &SwatchChoices,
|
||||
same_doc: bool,
|
||||
same_doc_images: bool,
|
||||
) -> Result<Imported> {
|
||||
let mut out = Imported::default();
|
||||
out.relink.filters = self.filter_links(d, same_doc)?;
|
||||
self.import_images(d, used, same_doc, &mut out);
|
||||
self.import_images(d, used, same_doc_images, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
self.import_kinsoku_sets(d, used, same_doc, &mut out);
|
||||
let mut defs: Vec<Def<'_>> = vec![];
|
||||
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
|
||||
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
|
||||
@@ -1305,10 +1396,86 @@ impl Clipboard {
|
||||
&& out.relink.filters.is_empty()
|
||||
&& out.relink.styles.is_empty()
|
||||
&& out.relink.colors.is_empty()
|
||||
&& out.relink.kinsoku.is_empty()
|
||||
&& used.styles.is_empty());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Add the custom Kinsoku sets that the pasted paragraphs and the used paragraph styles hold
|
||||
/// to `d`'s sets, and record in [`Relink::kinsoku`] which set of `d` each one takes. A set
|
||||
/// takes `d`'s set of its name (in any case) when that has the same characters, or, pasted
|
||||
/// back into its own document, in any case; else a numbered copy of it ("Tight 2") with the
|
||||
/// same characters. Any other set is added under a free name that fits [`KINSOKU_NAME_MAX`]
|
||||
/// ([`unique_kinsoku_name`]), so editing `d`'s set of that name leaves the pasted paragraphs
|
||||
/// alone. When `d` already holds [`KINSOKU_SETS_MAX`] sets, or the pasted set's own name is
|
||||
/// longer than a name can be, the paragraphs and styles take Hard.
|
||||
fn import_kinsoku_sets(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
|
||||
let mut found: Vec<KinsokuSet> = vec![];
|
||||
let mut seen: HashSet<KinsokuSet> = HashSet::new();
|
||||
let mut note = |set: &KinsokuSet| {
|
||||
if !seen.contains(set) {
|
||||
seen.insert(set.clone());
|
||||
found.push(set.clone());
|
||||
}
|
||||
};
|
||||
let mut nodes = |n: &Node| {
|
||||
// Opacity-mask art included.
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if let NodeKind::Text(t) = &m.kind {
|
||||
t.para_styles().filter_map(|p| p.kinsoku_set.as_deref()).for_each(&mut note);
|
||||
}
|
||||
// The paragraph attributes a graph keeps for its labels.
|
||||
if let Some(spec) = m.extras().graph.as_deref() {
|
||||
let l = &spec.label_styles;
|
||||
[&l.values_para, &l.categories_para, &l.legend_para]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p.kinsoku_set.as_deref())
|
||||
.for_each(&mut note);
|
||||
}
|
||||
});
|
||||
};
|
||||
self.nodes.iter().for_each(&mut nodes);
|
||||
self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).for_each(|s| nodes(s.art.as_ref()));
|
||||
self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).flat_map(|p| p.art.iter()).for_each(|a| nodes(a.as_ref()));
|
||||
self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).flat_map(Brush::art).for_each(&mut nodes);
|
||||
let styles = self.para_styles.iter().filter(|s| used.has(Res::ParaStyle, &s.name));
|
||||
for set in styles.filter_map(|s| s.attrs.get("kinsoku_set")).filter_map(|v| serde_json::from_value::<KinsokuSet>(v.clone()).ok()) {
|
||||
note(&set);
|
||||
}
|
||||
for set in found {
|
||||
let lower = set.name.to_lowercase();
|
||||
let mut copies: Vec<&KinsokuSet> =
|
||||
d.kinsoku_sets.iter().filter(|x| copy_of(&lower, &x.name.to_lowercase()) || kinsoku_copy_of(&set.name, &x.name)).collect();
|
||||
// The set of its name first.
|
||||
copies.sort_by_key(|x| !KinsokuSet::same_name(&x.name, &set.name));
|
||||
let own = copies.first().copied().filter(|x| same_doc && KinsokuSet::same_name(&x.name, &set.name));
|
||||
let to = match own.or_else(|| copies.iter().copied().find(|x| kinsoku_chars(x) == kinsoku_chars(&set))) {
|
||||
Some(x) => {
|
||||
if !KinsokuSet::same_name(&x.name, &set.name) {
|
||||
out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": x.name}));
|
||||
}
|
||||
Some(Arc::new(x.clone()))
|
||||
}
|
||||
None => {
|
||||
let name = unique_kinsoku_name(&set.name, &d.kinsoku_sets);
|
||||
(d.kinsoku_sets.len() < KINSOKU_SETS_MAX && name.chars().count() <= KINSOKU_NAME_MAX).then(|| {
|
||||
let added = KinsokuSet { name: name.clone(), ..set.clone() };
|
||||
d.kinsoku_sets.push(added.clone());
|
||||
out.added += 1;
|
||||
if name != set.name {
|
||||
out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": name}));
|
||||
}
|
||||
Arc::new(added)
|
||||
})
|
||||
}
|
||||
};
|
||||
if to.as_deref() != Some(&set) {
|
||||
out.relink.kinsoku.insert(set, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
|
||||
/// filter of its name; one that draws another definition than that filter takes the document's
|
||||
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -183,6 +183,9 @@ fn settings_json(st: &ColorSettings) -> Value {
|
||||
"bpc": st.bpc,
|
||||
"rgbPolicy": st.rgb_policy.id(),
|
||||
"cmykPolicy": st.cmyk_policy.id(),
|
||||
"askMismatchOpen": st.ask_mismatch_open,
|
||||
"askMismatchPaste": st.ask_mismatch_paste,
|
||||
"askMissingOpen": st.ask_missing_open,
|
||||
"profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -225,6 +228,9 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? {
|
||||
st.cmyk_policy = v;
|
||||
}
|
||||
st.ask_mismatch_open = switch_or(p, "askMismatchOpen", st.ask_mismatch_open, C)?;
|
||||
st.ask_mismatch_paste = switch_or(p, "askMismatchPaste", st.ask_mismatch_paste, C)?;
|
||||
st.ask_missing_open = switch_or(p, "askMissingOpen", st.ask_missing_open, C)?;
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
// Saved for the next start when the app attached a settings file (#6335).
|
||||
@@ -659,39 +665,259 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
// Without a choice nothing can fail.
|
||||
apply_open_policies_choosing(d, None).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
|
||||
/// boxes): the profile of its color mode differs from the working space, or it has none.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ProfileIssue {
|
||||
/// Profile Mismatches: tagged with a profile other than the working space.
|
||||
Mismatch,
|
||||
/// Missing Profiles: not tagged with a profile.
|
||||
Missing,
|
||||
}
|
||||
|
||||
impl ProfileIssue {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ProfileIssue::Mismatch => "mismatch",
|
||||
ProfileIssue::Missing => "missing",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer to a [`ProfileQuestion`] (`document.open`'s `profileChoice`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ProfileChoice {
|
||||
/// Mismatch: keep the profile (as Preserve Embedded Profiles).
|
||||
UseEmbedded,
|
||||
/// Mismatch: convert the colors of that model into the working space and take the profile off
|
||||
/// (as Convert to Working Space).
|
||||
Convert,
|
||||
/// Mismatch: take the profile off and keep the color numbers (as Off).
|
||||
Discard,
|
||||
/// Missing: leave the document untagged (it follows the working space).
|
||||
Leave,
|
||||
/// Missing: tag the document with the working space of its color mode.
|
||||
AssignWorking,
|
||||
/// Missing: tag the document with this profile.
|
||||
Assign(String),
|
||||
}
|
||||
|
||||
impl ProfileChoice {
|
||||
/// The ids `profileChoice` takes.
|
||||
pub const IDS: [&'static str; 6] = ["useEmbedded", "convert", "discard", "leave", "assignWorking", "assign"];
|
||||
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
ProfileChoice::UseEmbedded => "useEmbedded",
|
||||
ProfileChoice::Convert => "convert",
|
||||
ProfileChoice::Discard => "discard",
|
||||
ProfileChoice::Leave => "leave",
|
||||
ProfileChoice::AssignWorking => "assignWorking",
|
||||
ProfileChoice::Assign(_) => "assign",
|
||||
}
|
||||
}
|
||||
|
||||
/// The question kind this choice answers.
|
||||
pub fn issue(&self) -> ProfileIssue {
|
||||
match self {
|
||||
ProfileChoice::UseEmbedded | ProfileChoice::Convert | ProfileChoice::Discard => ProfileIssue::Mismatch,
|
||||
_ => ProfileIssue::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice `id` (`profile`, which only `assign` takes, for `assign`), or an error naming
|
||||
/// `cmd`.
|
||||
pub fn parse(id: &str, profile: Option<&str>, cmd: &str) -> Result<Self> {
|
||||
let key = "profileChoice";
|
||||
let choice = match id {
|
||||
"useEmbedded" => ProfileChoice::UseEmbedded,
|
||||
"convert" => ProfileChoice::Convert,
|
||||
"discard" => ProfileChoice::Discard,
|
||||
"leave" => ProfileChoice::Leave,
|
||||
"assignWorking" => ProfileChoice::AssignWorking,
|
||||
"assign" => match profile.filter(|p| !p.is_empty()) {
|
||||
Some(p) => ProfileChoice::Assign(cms::canonical_name(p).to_string()),
|
||||
None => {
|
||||
let path = "assignProfile";
|
||||
return Err(bad(cmd, format!("missing `{path}`")));
|
||||
}
|
||||
},
|
||||
_ => return Err(bad(cmd, format!("`{key}` must be one of {}", Self::IDS.join(", ")))),
|
||||
};
|
||||
// `assignProfile` goes with `assign` only.
|
||||
if profile.is_some() && !matches!(choice, ProfileChoice::Assign(_)) {
|
||||
let path = "assignProfile";
|
||||
return Err(bad(cmd, format!("`{path}` goes with `{key}`: \"assign\" only")));
|
||||
}
|
||||
Ok(choice)
|
||||
}
|
||||
|
||||
/// `document.open`'s `profileChoice` and `assignProfile` in `p` (`None` when left out).
|
||||
pub(crate) fn param(p: &Value, cmd: &str) -> Result<Option<Self>> {
|
||||
let profile = text_param(p, "assignProfile", cmd)?;
|
||||
match text_param(p, "profileChoice", cmd)? {
|
||||
Some(id) => Self::parse(id, profile, cmd).map(Some),
|
||||
None if profile.is_some() => {
|
||||
let path = "profileChoice";
|
||||
Err(bad(cmd, format!("missing `{path}`")))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What opening document `d` could ask about the profile of its color mode, with the working
|
||||
/// settings `st`: none when it is tagged with the working space.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ProfileQuestion {
|
||||
pub issue: ProfileIssue,
|
||||
/// The model of the document's color mode.
|
||||
pub model: ColorMode,
|
||||
/// The profile the document is tagged with (none when it is missing).
|
||||
pub profile: Option<String>,
|
||||
/// The working space of that model.
|
||||
pub working: String,
|
||||
/// What the policy of that model does, the choice the prompt starts on.
|
||||
pub default: ProfileChoice,
|
||||
}
|
||||
|
||||
impl ProfileQuestion {
|
||||
/// The question for document `d` under the working settings `st` (whether or not they ask it).
|
||||
pub fn of(d: &vectorcraft_doc::Document, st: &ColorSettings) -> Option<Self> {
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let (tag, working, policy) = match d.color_mode {
|
||||
ColorMode::Rgb => (rgb, cms::canonical_name(&st.rgb).to_string(), st.rgb_policy),
|
||||
ColorMode::Cmyk => (cmyk, cms::canonical_name(&st.cmyk).to_string(), st.cmyk_policy),
|
||||
};
|
||||
let (issue, default) = match &tag {
|
||||
Some(t) if *t == working => return None,
|
||||
Some(_) => (
|
||||
ProfileIssue::Mismatch,
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => ProfileChoice::UseEmbedded,
|
||||
Policy::Convert => ProfileChoice::Convert,
|
||||
Policy::Off | Policy::PreserveNumbers => ProfileChoice::Discard,
|
||||
},
|
||||
),
|
||||
// VectorCraft's own rule: Convert to Working Space starts on assigning the working
|
||||
// space, the other policies on leaving the document as it is.
|
||||
None => (ProfileIssue::Missing, if policy == Policy::Convert { ProfileChoice::AssignWorking } else { ProfileChoice::Leave }),
|
||||
};
|
||||
Some(Self { issue, model: d.color_mode, profile: tag, working, default })
|
||||
}
|
||||
|
||||
/// Do the settings `st` ask it (the Ask When Opening box of its kind is on)?
|
||||
pub fn asked(&self, st: &ColorSettings) -> bool {
|
||||
match self.issue {
|
||||
ProfileIssue::Mismatch => st.ask_mismatch_open,
|
||||
ProfileIssue::Missing => st.ask_missing_open,
|
||||
}
|
||||
}
|
||||
|
||||
/// The model's name as the UI shows it ("RGB", "CMYK").
|
||||
pub fn model_label(&self) -> &'static str {
|
||||
match self.model {
|
||||
ColorMode::Rgb => "RGB",
|
||||
ColorMode::Cmyk => "CMYK",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"issue": self.issue.id(),
|
||||
"model": self.model_label().to_ascii_lowercase(),
|
||||
"profile": self.profile,
|
||||
"working": self.working,
|
||||
"default": self.default.id(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// [`apply_open_policies`] with the answer `choice` to the document's [`ProfileQuestion`]: a
|
||||
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
|
||||
/// choice tags the document after the policies ran. A choice for the other kind of question, or
|
||||
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
|
||||
/// to assign is not a profile of that model.
|
||||
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
|
||||
let working = cms::working_settings();
|
||||
let question = ProfileQuestion::of(d, &working);
|
||||
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
|
||||
// A mismatch answer stands in for the policy of the document's color mode.
|
||||
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
|
||||
match choice {
|
||||
Some(c) if d.color_mode == model => match c {
|
||||
ProfileChoice::UseEmbedded => (Policy::PreserveEmbedded, true),
|
||||
ProfileChoice::Convert => (Policy::Convert, true),
|
||||
ProfileChoice::Discard => (Policy::Off, true),
|
||||
_ => (policy, false),
|
||||
},
|
||||
_ => (policy, false),
|
||||
}
|
||||
};
|
||||
let (rgb_policy, rgb_chosen) = chosen(ColorMode::Rgb, working.rgb_policy);
|
||||
let (cmyk_policy, cmyk_chosen) = chosen(ColorMode::Cmyk, working.cmyk_policy);
|
||||
// The profile a missing answer assigns, checked before anything changes.
|
||||
let assign = match (choice, &question) {
|
||||
(Some(ProfileChoice::AssignWorking), Some(q)) => Some(q.working.clone()),
|
||||
(Some(ProfileChoice::Assign(name)), Some(q)) => {
|
||||
let kind = if q.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk };
|
||||
let (key, n) = (q.model_label().to_ascii_lowercase(), name);
|
||||
let info = cms::profile(name).filter(|p| p.kind == kind).ok_or_else(|| bad("document.open", format!("unknown {key} profile `{n}`")))?;
|
||||
Some(info.name)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let mut notes = Vec::new();
|
||||
// What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after
|
||||
// converting the colors from the profile it holds.
|
||||
let mut decide = |label: &str, tag: Option<String>, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option<Option<String>> {
|
||||
let tag = tag.filter(|t| t != working)?;
|
||||
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => None,
|
||||
Policy::Off | Policy::PreserveNumbers => {
|
||||
notes.push(format!(
|
||||
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
|
||||
policy.label()
|
||||
));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Convert if available => {
|
||||
notes.push(format!(
|
||||
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
|
||||
));
|
||||
Some(Some(tag))
|
||||
}
|
||||
Policy::Convert => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
|
||||
None
|
||||
// converting the colors from the profile it holds. `by_choice`: the prompt's answer decided.
|
||||
let mut decide =
|
||||
|label: &str, tag: Option<String>, working: &str, policy: Policy, by_choice: bool, kind: cms::ProfileKind| -> Option<Option<String>> {
|
||||
let tag = tag.filter(|t| t != working)?;
|
||||
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => None,
|
||||
Policy::Off | Policy::PreserveNumbers if by_choice => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with was discarded, as chosen when it was opened"));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Off | Policy::PreserveNumbers => {
|
||||
notes.push(format!(
|
||||
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
|
||||
policy.label()
|
||||
));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Convert if available => {
|
||||
notes.push(format!(
|
||||
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
|
||||
));
|
||||
Some(Some(tag))
|
||||
}
|
||||
Policy::Convert => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let rgb_do = decide("RGB", rgb, &working.rgb, rgb_policy, rgb_chosen, cms::ProfileKind::Rgb);
|
||||
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, cmyk_policy, cmyk_chosen, cms::ProfileKind::Cmyk);
|
||||
let mut changed = false;
|
||||
if let (Some(name), Some(q)) = (assign, &question) {
|
||||
let label = q.model_label();
|
||||
notes.push(format!("the document was assigned the {label} profile “{name}”, as chosen when it was opened"));
|
||||
match q.model {
|
||||
ColorMode::Rgb => d.color_profiles.rgb = Some(name),
|
||||
ColorMode::Cmyk => d.color_profiles.cmyk = Some(name),
|
||||
}
|
||||
};
|
||||
let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb);
|
||||
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk);
|
||||
changed = true;
|
||||
}
|
||||
if rgb_do.is_none() && cmyk_do.is_none() {
|
||||
return (notes, false);
|
||||
return Ok((notes, changed));
|
||||
}
|
||||
let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten());
|
||||
if from_rgb.is_some() || from_cmyk.is_some() {
|
||||
@@ -713,7 +939,214 @@ pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<Str
|
||||
if cmyk_do.is_some() {
|
||||
d.color_profiles.cmyk = None;
|
||||
}
|
||||
(notes, true)
|
||||
Ok((notes, true))
|
||||
}
|
||||
|
||||
/// The colors of `d`'s art and resources ([`convert_colors`]) and of its character and paragraph
|
||||
/// styles, converted with `conv`; not its artboards' backgrounds or Document Setup's colors.
|
||||
pub(crate) fn convert_art_and_style_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
|
||||
convert_colors(d, conv);
|
||||
convert_style_colors(d, conv);
|
||||
}
|
||||
|
||||
/// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else
|
||||
/// the working spaces. An assigned profile that is not available (removed since) is the working
|
||||
/// space, as the document draws through it ([`cms::for_document`]).
|
||||
pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] {
|
||||
let working = cms::working_settings();
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let available = |name: Option<String>, kind: cms::ProfileKind| name.filter(|n| cms::profile(n).is_some_and(|p| p.kind == kind));
|
||||
[
|
||||
available(rgb, cms::ProfileKind::Rgb).unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()),
|
||||
available(cmyk, cms::ProfileKind::Cmyk).unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
/// What Paste does with the colors of a model when the document they were copied from showed them
|
||||
/// through another profile than the document they go into (`profileMismatch`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PasteProfile {
|
||||
/// The colors keep their numbers.
|
||||
PreserveNumbers,
|
||||
/// The colors convert from the source profile into the destination's, which keeps their
|
||||
/// appearance.
|
||||
Convert,
|
||||
}
|
||||
|
||||
impl PasteProfile {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
PasteProfile::PreserveNumbers => "preserveNumbers",
|
||||
PasteProfile::Convert => "convert",
|
||||
}
|
||||
}
|
||||
|
||||
/// What a model's policy does to pasted colors (VectorCraft's own mapping): Convert to Working
|
||||
/// Space converts them, the other policies keep their numbers.
|
||||
pub fn of(policy: Policy) -> Self {
|
||||
if policy == Policy::Convert { PasteProfile::Convert } else { PasteProfile::PreserveNumbers }
|
||||
}
|
||||
|
||||
/// The `profileMismatch` param of paste command `cmd` (`None` when left out): one choice for
|
||||
/// both models, or `{rgb?, cmyk?}` with a choice for each (a model left out follows its policy).
|
||||
pub(crate) fn param(p: &Value, cmd: &str) -> Result<Option<PasteChoice>> {
|
||||
let key = "profileMismatch";
|
||||
let refuse = || bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb?, cmyk?} of those"));
|
||||
let one = |v: &Value| match v.as_str() {
|
||||
Some("preserveNumbers") => Ok(PasteProfile::PreserveNumbers),
|
||||
Some("convert") => Ok(PasteProfile::Convert),
|
||||
_ => Err(refuse()),
|
||||
};
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Object(o)) => {
|
||||
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
|
||||
return Err(refuse());
|
||||
}
|
||||
let model = |m: &str| o.get(m).map(&one).transpose();
|
||||
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
|
||||
}
|
||||
Some(v) => {
|
||||
let c = one(v)?;
|
||||
Ok(Some(PasteChoice { rgb: Some(c), cmyk: Some(c) }))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What Paste does with the mismatched colors of each model (`profileMismatch`); a model without a
|
||||
/// choice follows its policy ([`PasteProfile::of`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PasteChoice {
|
||||
pub rgb: Option<PasteProfile>,
|
||||
pub cmyk: Option<PasteProfile>,
|
||||
}
|
||||
|
||||
impl PasteChoice {
|
||||
/// The choice for the colors of `model`, if any.
|
||||
pub fn of(&self, model: ColorMode) -> Option<PasteProfile> {
|
||||
match model {
|
||||
ColorMode::Rgb => self.rgb,
|
||||
ColorMode::Cmyk => self.cmyk,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A model whose colors a paste brings from another profile than the destination's.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PasteMismatch {
|
||||
pub model: ColorMode,
|
||||
/// The profile the colors showed through where they were copied.
|
||||
pub from: String,
|
||||
/// The profile they show through in the document they go into.
|
||||
pub to: String,
|
||||
/// What the model's policy does with them; Preserve Numbers when they can't convert.
|
||||
pub default: PasteProfile,
|
||||
/// Both profiles are available, so the colors can convert; otherwise they keep their numbers
|
||||
/// whatever the choice.
|
||||
pub convertible: bool,
|
||||
}
|
||||
|
||||
impl PasteMismatch {
|
||||
pub fn to_json(&self) -> Value {
|
||||
let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" };
|
||||
json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id(), "convertible": self.convertible })
|
||||
}
|
||||
}
|
||||
|
||||
/// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both,
|
||||
/// each only when the copied objects or the resources they carry hold a color of that model. The
|
||||
/// background colors of copied artboards count only with `boards` (Paste on All Artboards doesn't
|
||||
/// paste the artboards).
|
||||
pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, boards: bool) -> Vec<PasteMismatch> {
|
||||
let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] };
|
||||
let [to_rgb, to_cmyk] = effective_profiles(d);
|
||||
let working = cms::working_settings();
|
||||
let mut out: Vec<PasteMismatch> =
|
||||
[(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)]
|
||||
.into_iter()
|
||||
.filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to))
|
||||
.map(|(model, from, to, policy)| {
|
||||
let kind = if model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk };
|
||||
// Both profiles must be here to convert between them.
|
||||
let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind);
|
||||
let convertible = here(from) && here(&to);
|
||||
let default = if convertible { PasteProfile::of(policy) } else { PasteProfile::PreserveNumbers };
|
||||
PasteMismatch { model, from: from.clone(), to, default, convertible }
|
||||
})
|
||||
.collect();
|
||||
if out.is_empty() {
|
||||
return out;
|
||||
}
|
||||
// Without the artboards when their backgrounds don't paste.
|
||||
let without_boards;
|
||||
let clip = if !boards && !clip.artboards.is_empty() {
|
||||
without_boards = super::clipboard::Clipboard { artboards: vec![], ..clip.clone() };
|
||||
&without_boards
|
||||
} else {
|
||||
clip
|
||||
};
|
||||
// Which models the pasted colors use.
|
||||
let seen = std::cell::Cell::new((false, false));
|
||||
let _ = clip.with_colors(&|c: &Color| {
|
||||
let (rgb, cmyk) = seen.get();
|
||||
seen.set((rgb || matches!(c, Color::Rgb { .. }), cmyk || matches!(c, Color::Cmyk { .. })));
|
||||
*c
|
||||
});
|
||||
let (rgb, cmyk) = seen.get();
|
||||
out.retain(|m| if m.model == ColorMode::Rgb { rgb } else { cmyk });
|
||||
out
|
||||
}
|
||||
|
||||
/// The clipboard `clip` as pasting it into `d` brings it: for each mismatched model
|
||||
/// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into
|
||||
/// the destination's with the working intent, as `choice` says for that model (default: the
|
||||
/// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available
|
||||
/// keeps the numbers. `boards`: as [`paste_mismatches`].
|
||||
/// → the converted clipboard (`None` when nothing converts; its resources paste as another
|
||||
/// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`).
|
||||
pub(crate) fn paste_profiles(
|
||||
clip: &super::clipboard::Clipboard,
|
||||
d: &vectorcraft_doc::Document,
|
||||
choice: Option<PasteChoice>,
|
||||
boards: bool,
|
||||
) -> (Option<super::clipboard::Clipboard>, Vec<Value>) {
|
||||
let mismatches = paste_mismatches(clip, d, boards);
|
||||
let mut report = Vec::new();
|
||||
let (mut rgb_on, mut cmyk_on) = (false, false);
|
||||
for m in &mismatches {
|
||||
let picked = if m.convertible { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers };
|
||||
if picked == PasteProfile::Convert {
|
||||
match m.model {
|
||||
ColorMode::Rgb => rgb_on = true,
|
||||
ColorMode::Cmyk => cmyk_on = true,
|
||||
}
|
||||
}
|
||||
let mut line = m.to_json();
|
||||
if let Some(o) = line.as_object_mut() {
|
||||
o.remove("default");
|
||||
o.remove("convertible");
|
||||
o.insert("choice".into(), json!(picked.id()));
|
||||
}
|
||||
report.push(line);
|
||||
}
|
||||
if !rgb_on && !cmyk_on {
|
||||
return (None, report);
|
||||
}
|
||||
let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return (None, report) };
|
||||
let source = cms::for_document(Some(from_rgb), Some(from_cmyk));
|
||||
let dest = doc_cms(d);
|
||||
let intent = cms::working_settings().intent;
|
||||
let conv = |c: &Color| match c {
|
||||
Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent),
|
||||
Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent),
|
||||
_ => *c,
|
||||
};
|
||||
let mut converted = clip.with_colors(&conv);
|
||||
// Converted colors are not the source document's own: its resources of the same names are
|
||||
// compared with them, as another document's are.
|
||||
converted.colors_converted = true;
|
||||
(Some(converted), report)
|
||||
}
|
||||
|
||||
/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each
|
||||
@@ -726,6 +1159,11 @@ fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Colo
|
||||
for c in &mut d.setup.grid_colors {
|
||||
*c = conv(c);
|
||||
}
|
||||
convert_style_colors(d, conv);
|
||||
}
|
||||
|
||||
/// The fill and stroke colors of `d`'s character and paragraph styles, converted with `conv`.
|
||||
fn convert_style_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
|
||||
// A tint of a global swatch is the converted swatch's color at its tint, which
|
||||
// [`convert_colors`] already gave it.
|
||||
let bases = global_bases(d);
|
||||
|
||||
@@ -8,6 +8,8 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode};
|
||||
use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
@@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi};
|
||||
|
||||
const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"];
|
||||
|
||||
/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another
|
||||
/// open path that encloses no area once closed, and so contributes no area to the shape.
|
||||
pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -23,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Compound Shape",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}",
|
||||
"{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}",
|
||||
has_multi,
|
||||
make
|
||||
),
|
||||
@@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// all have `mode`, the topmost, or the backmost when they all subtract.
|
||||
let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() };
|
||||
let hook = |c: &Node| effects::outline_object(Some(d), c);
|
||||
let no_area = order.iter().any(|n| adds_no_area(d, n, &hook));
|
||||
let style = order.into_iter().find_map(|n| top_style(d, n, &hook));
|
||||
let id = s.edit("Make Compound Shape", |d, sel| {
|
||||
let gid = d.alloc_id();
|
||||
@@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
let mut out = json!({ "id": id.0 });
|
||||
if no_area {
|
||||
out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes
|
||||
/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath
|
||||
/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it
|
||||
/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd
|
||||
/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule
|
||||
/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the
|
||||
/// warning, as Divide measures it. An area that can't be measured gives no warning.
|
||||
fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool {
|
||||
effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| {
|
||||
let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind {
|
||||
NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule),
|
||||
NodeKind::Path { path, rule, .. } => (vec![path], *rule),
|
||||
_ => return false,
|
||||
};
|
||||
let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect();
|
||||
if subpaths.iter().all(|sp| sp.closed) {
|
||||
return false;
|
||||
}
|
||||
let closed = |sp: &SubPath| {
|
||||
let mut sp = sp.clone();
|
||||
sp.closed = true;
|
||||
sp
|
||||
};
|
||||
// An area that can't be measured counts as an area, so a failed measurement gives no warning.
|
||||
let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0);
|
||||
subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
|
||||
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where
|
||||
// the signed area is not zero (a contour traced twice).
|
||||
!(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp)))
|
||||
}) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect())))
|
||||
})
|
||||
}
|
||||
|
||||
/// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the
|
||||
|
||||
+10
-144
@@ -55,7 +55,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
super::flare::flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.editFlare",
|
||||
"Edit Flare",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}",
|
||||
has_doc,
|
||||
super::flare::edit_flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
@@ -515,149 +524,6 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
|
||||
}
|
||||
|
||||
/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo
|
||||
/// ring, rays of varying length and rings along the path to the end point.
|
||||
fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?);
|
||||
let numbers = [
|
||||
"diameter",
|
||||
"opacity",
|
||||
"brightness",
|
||||
"growth",
|
||||
"fuzziness",
|
||||
"rays",
|
||||
"longest",
|
||||
"rayFuzziness",
|
||||
"rotation",
|
||||
"rings",
|
||||
"largest",
|
||||
"x2",
|
||||
"y2",
|
||||
"direction",
|
||||
"pathLength",
|
||||
"seed",
|
||||
"ringSeed",
|
||||
];
|
||||
check_numbers(p, &numbers, "shape.flare")?;
|
||||
let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity", 50.0).min(1.0) as f32;
|
||||
let brightness = pct("brightness", 30.0).min(1.0) as f32;
|
||||
let growth = pct("growth", 20.0);
|
||||
let fuzz = pct("fuzziness", 50.0).min(1.0);
|
||||
let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize;
|
||||
let longest = pct("longest", 300.0);
|
||||
let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0);
|
||||
let ray_turn = f64_or(p, "rotation", 0.0).to_radians();
|
||||
let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize;
|
||||
let largest = pct("largest", 50.0);
|
||||
let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) {
|
||||
(Some(x), Some(y)) => Point::new(x, y),
|
||||
_ => {
|
||||
let a = f64_or(p, "direction", 45.0).to_radians();
|
||||
c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0)
|
||||
}
|
||||
};
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
let seed_of = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let ring_seed = match seed_of("ringSeed")? {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin());
|
||||
let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Flare", |d, sel| {
|
||||
let children = parts
|
||||
.into_iter()
|
||||
.map(|(name, pd, paint, op)| {
|
||||
let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
super::object::align_new_object(d, &mut n);
|
||||
std::sync::Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = Some("Flare".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
fn line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?);
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -144,6 +144,45 @@ fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) {
|
||||
(entry, (label, detail))
|
||||
}
|
||||
|
||||
/// The type of a font as Fonts lists it: `truetype` or `opentype` by the outlines of the face the
|
||||
/// type is drawn in (in the version the type names), `unknown` for a font that is not installed in
|
||||
/// the family and style it names, or whose face holds neither kind of outline.
|
||||
fn font_type(used: &super::fonts::UsedFont) -> &'static str {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let (family, style, version) = used;
|
||||
match db.resolve(family, style) {
|
||||
Some((f, vectorcraft_text::FontMatch::Exact)) => match db.face_version(family, style, version.as_deref()).unwrap_or(f).outline_format() {
|
||||
Some(vectorcraft_text::OutlineFormat::TrueType) => "truetype",
|
||||
Some(vectorcraft_text::OutlineFormat::Cff) => "opentype",
|
||||
None => "unknown",
|
||||
},
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// A font as Fonts lists it: its `fontUses` entry and its row, which gives the font's type and its
|
||||
/// number of uses (`uses`: the text objects set in it).
|
||||
fn font_use(used: &super::fonts::UsedFont, uses: usize) -> (Value, (String, String)) {
|
||||
let label = super::fonts::font_label(used);
|
||||
let kind = font_type(used);
|
||||
let name = match kind {
|
||||
"truetype" => "TrueType",
|
||||
"opentype" => "OpenType",
|
||||
_ => "unknown type",
|
||||
};
|
||||
let count = if uses == 1 { "1 use".to_string() } else { format!("{uses} uses") };
|
||||
(json!({ "font": label, "type": kind, "uses": uses }), (label, format!("{name}; {count}")))
|
||||
}
|
||||
|
||||
/// Counts text object `t` once for each font its runs are drawn in, a composite font's parts in
|
||||
/// place of its name ([`super::fonts::run_fonts`]).
|
||||
fn count_fonts(fonts: &mut BTreeMap<super::fonts::UsedFont, usize>, t: &vectorcraft_doc::TextObject) {
|
||||
let own: BTreeSet<super::fonts::UsedFont> = t.runs.iter().flat_map(super::fonts::run_fonts).collect();
|
||||
for font in own {
|
||||
*fonts.entry(font).or_default() += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// An image object as Document Info lists it: (name, width, height, linked file).
|
||||
type ImageRow = (String, u32, u32, Option<String>);
|
||||
|
||||
@@ -221,16 +260,16 @@ fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
|
||||
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
|
||||
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
|
||||
/// pattern and with a gradient.
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, the rows of
|
||||
/// its fonts and their Font Details rows, its image objects, the rows of the brushes its art uses,
|
||||
/// the rows of its Repeat objects and the rows of its objects filled or stroked with a spot color,
|
||||
/// with a pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
selected_artboards: &[(String, String)],
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
fonts: &[(String, String)],
|
||||
font_details: &[(String, String)],
|
||||
images: &[ImageRow],
|
||||
brushes: &[(String, String)],
|
||||
@@ -296,7 +335,7 @@ fn sections(
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
"fonts" => fonts.to_vec(),
|
||||
"fontDetails" => font_details.to_vec(),
|
||||
"linkedImages" => {
|
||||
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
|
||||
@@ -627,7 +666,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
|
||||
// strip of LEDs along the letters, #1958).
|
||||
let mut path_length = 0.0;
|
||||
let mut fonts = BTreeSet::new();
|
||||
// Each font with the number of text objects set in it.
|
||||
let mut fonts: BTreeMap<super::fonts::UsedFont, usize> = BTreeMap::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut image_rows: Vec<ImageRow> = vec![];
|
||||
// Whether the request being served may read each linked file (a relative path read from the
|
||||
@@ -702,9 +742,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
NodeKind::Compound { .. } => Some("compoundPaths"),
|
||||
NodeKind::Text(t) => {
|
||||
for run in &t.runs {
|
||||
fonts.insert((run.style.font_family.clone(), run.style.font_style.clone(), run.style.font_version.clone()));
|
||||
}
|
||||
count_fonts(&mut fonts, t);
|
||||
Some("textObjects")
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
@@ -787,12 +825,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
// The document's fonts include those of the type in opacity masks and in the art of its
|
||||
// symbols and patterns, as Find Font lists them.
|
||||
// symbols and patterns, as Find Font lists them. Each of those text objects counts once, however
|
||||
// many objects show it.
|
||||
if !selection_only {
|
||||
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
|
||||
for (_, t, _) in super::fonts::art_texts_of(d) {
|
||||
count_fonts(&mut fonts, t);
|
||||
}
|
||||
}
|
||||
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
|
||||
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip();
|
||||
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
|
||||
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
|
||||
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip();
|
||||
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
|
||||
// linked image's row value (its path, or its file name alone when the request may not read it),
|
||||
// and null for an embedded one.
|
||||
@@ -820,6 +862,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"objects": counts,
|
||||
"pathLength": path_length,
|
||||
"fonts": font_names,
|
||||
"fontUses": font_uses,
|
||||
"fontDetails": font_entries,
|
||||
"images": images,
|
||||
"imageObjects": image_objects,
|
||||
@@ -850,7 +893,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d,
|
||||
&out,
|
||||
&selected_rows,
|
||||
&fonts,
|
||||
&font_use_rows,
|
||||
&font_rows,
|
||||
&image_rows,
|
||||
&brush_rows,
|
||||
@@ -1083,6 +1126,92 @@ mod tests {
|
||||
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
|
||||
}
|
||||
|
||||
/// Fonts gives each font's type and its number of uses: the text objects set in it, each once
|
||||
/// however many of its runs use the font. The type in a symbol's art counts once however many
|
||||
/// instances show it, and the type in an opacity mask once. With Selection Only it counts the
|
||||
/// selected type alone. A font that is not installed has an unknown type. The rows, the report
|
||||
/// and `fontUses` give the same facts, in the order of `fonts`.
|
||||
#[test]
|
||||
fn info_fonts_give_each_font_s_type_and_uses() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let text =
|
||||
|s: &mut Session, font: &str, y: f64| id(s.execute("text.create", &json!({"x": 10, "y": y, "text": "Hello", "font": font})).unwrap());
|
||||
// Two runs in Source Sans 3 Regular in one text object, a second object in it, and one in Inter.
|
||||
let twice = text(&mut s, "Source Sans 3", 20.0);
|
||||
s.execute("text.setRangeStyle", &json!({"id": twice.0, "start": 0, "end": 2, "size": 30})).unwrap();
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(twice).unwrap().kind, NodeKind::Text(t) if t.runs.len() == 2));
|
||||
let other = text(&mut s, "Source Sans 3", 50.0);
|
||||
text(&mut s, "Inter", 80.0);
|
||||
text(&mut s, "Qx Absent Family", 110.0);
|
||||
// A symbol whose art holds type in Inter, shown by two instances, and a mask holding type in Inter.
|
||||
let in_symbol = text(&mut s, "Inter", 140.0);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
|
||||
s.execute("symbol.place", &json!({"name": "Mark", "x": 100, "y": 100})).unwrap();
|
||||
let masked = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
|
||||
let in_mask = text(&mut s, "Inter", 170.0);
|
||||
s.edit("Mask", |d, _| {
|
||||
let art = d.remove(in_mask)?;
|
||||
d.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fonts"], json!(["Inter Regular", "Qx Absent Family Regular", "Source Sans 3 Regular"]));
|
||||
assert_eq!(
|
||||
i["fontUses"],
|
||||
json!([
|
||||
{"font": "Inter Regular", "type": "truetype", "uses": 3},
|
||||
{"font": "Qx Absent Family Regular", "type": "unknown", "uses": 1},
|
||||
{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 2},
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([
|
||||
["Inter Regular", "TrueType; 3 uses"],
|
||||
["Qx Absent Family Regular", "unknown type; 1 use"],
|
||||
["Source Sans 3 Regular", "TrueType; 2 uses"],
|
||||
])
|
||||
);
|
||||
let report = s.execute("document.info", &json!({"category": "fonts", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(report.contains("\nFONTS\nInter Regular: TrueType; 3 uses\nQx Absent Family Regular: unknown type; 1 use\n"), "{report}");
|
||||
// Selection Only: the selected type's fonts and uses.
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fontUses"], json!([{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 1}]));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Source Sans 3 Regular", "TrueType; 1 use"]]));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap();
|
||||
assert_eq!((i["fontUses"].clone(), i["sections"][0]["rows"].clone()), (json!([]), json!([])));
|
||||
}
|
||||
|
||||
/// Type set in a composite font counts as a use of the fonts of the parts its characters fall
|
||||
/// in, as Find Font lists them, not of the composite font's name.
|
||||
#[test]
|
||||
fn info_fonts_count_the_parts_of_a_composite_font() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let font = json!({"name": "DI Uses Composite", "parts": {
|
||||
"kanji": {"font": "Source Sans 3"},
|
||||
"roman": {"font": "JetBrains Mono"},
|
||||
"numerals": {"font": "Inter"},
|
||||
}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab1", "font": "DI Uses Composite"})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "12", "font": "DI Uses Composite"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fonts"], json!(["Inter Regular", "JetBrains Mono Regular"]));
|
||||
assert_eq!(
|
||||
i["fontUses"],
|
||||
json!([
|
||||
{"font": "Inter Regular", "type": "truetype", "uses": 2},
|
||||
{"font": "JetBrains Mono Regular", "type": "truetype", "uses": 1},
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
|
||||
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
|
||||
#[test]
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -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]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise, finger wheel 0..1; 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\" | \"stylusWheel\" (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; stylusWheel from less at one end of an airbrush pen's finger wheel travel to more at the other. 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
|
||||
),
|
||||
|
||||
@@ -22,15 +22,17 @@ pub(super) struct Sample {
|
||||
tilt: Option<[f64; 2]>,
|
||||
/// Barrel rotation, degrees clockwise.
|
||||
rotation: Option<f64>,
|
||||
/// The airbrush finger wheel, 0..1.
|
||||
wheel: Option<f64>,
|
||||
}
|
||||
|
||||
/// The keys of a point's pen values, in the order a point given as an array holds them after its
|
||||
/// x and y.
|
||||
const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"];
|
||||
const PEN_KEYS: [&str; 5] = ["pressure", "tiltX", "tiltY", "rotation", "wheel"];
|
||||
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0).
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)];
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees, rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0) and the wheel 0..1.
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0), (0.0, 1.0)];
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size, in points.
|
||||
pub(super) const SIZES: (f64, f64) = (0.1, 1000.0);
|
||||
@@ -61,11 +63,11 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
}
|
||||
|
||||
/// [`points_param`] with what a pen read at each point, as far as it is given:
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure
|
||||
/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in
|
||||
/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or
|
||||
/// rotation is neither a number nor null or is outside its range, or an array of more than six
|
||||
/// numbers, is an error.
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation,wheel]…]` or `[{x,y,pressure,tiltX,tiltY,rotation,wheel}…]`.
|
||||
/// Pressure is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0);
|
||||
/// rotation in degrees clockwise, 0..360; the wheel 0..1. A point whose x or y is not a number,
|
||||
/// whose pressure, tilt, rotation or wheel is neither a number nor null or is outside its range,
|
||||
/// or an array of more than seven numbers, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sample>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<Sample> = a
|
||||
@@ -79,7 +81,7 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
|
||||
let key = format!("{key}[{at}]");
|
||||
return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries")));
|
||||
}
|
||||
let mut pen = [None; 4];
|
||||
let mut pen = [None; PEN_KEYS.len()];
|
||||
for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() {
|
||||
let given = match v {
|
||||
Value::Array(xy) => xy.get(i + 2),
|
||||
@@ -91,9 +93,9 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
};
|
||||
}
|
||||
let [pressure, tx, ty, rotation] = pen;
|
||||
let [pressure, tx, ty, rotation, wheel] = pen;
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0)));
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation })
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation, wheel })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if pts.is_empty() {
|
||||
@@ -126,6 +128,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option<PressureProfile> {
|
||||
PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0))))
|
||||
}
|
||||
|
||||
/// Where an airbrush pen's finger wheel was set along a freehand stroke, when any of its samples
|
||||
/// has it; samples without it count as the middle of its travel, which draws a brush's own value.
|
||||
fn stroke_wheel(samples: &[Sample]) -> Option<PressureProfile> {
|
||||
if samples.iter().all(|s| s.wheel.is_none()) {
|
||||
return None;
|
||||
}
|
||||
PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.wheel.unwrap_or(PressureProfile::MID))))
|
||||
}
|
||||
|
||||
/// A pen that leans less than this many degrees from upright leans no way in particular: its
|
||||
/// bearing is the one before it.
|
||||
const UPRIGHT: f64 = 1.0;
|
||||
@@ -165,24 +176,31 @@ fn stroke_pose(samples: &[Sample]) -> (Option<PressureProfile>, Option<AngleProf
|
||||
(tilt.flatten(), bearing.flatten(), rotation.flatten())
|
||||
}
|
||||
|
||||
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing` and
|
||||
/// `rotation`).
|
||||
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing`,
|
||||
/// `rotation` and `wheel`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct PenRecord {
|
||||
pressure: Option<PressureProfile>,
|
||||
tilt: Option<PressureProfile>,
|
||||
bearing: Option<AngleProfile>,
|
||||
rotation: Option<AngleProfile>,
|
||||
wheel: Option<PressureProfile>,
|
||||
}
|
||||
|
||||
impl PenRecord {
|
||||
/// What a freehand stroke's samples recorded.
|
||||
pub(super) fn of_samples(samples: &[Sample]) -> Self {
|
||||
let (tilt, bearing, rotation) = stroke_pose(samples);
|
||||
Self { pressure: stroke_pressure(samples), tilt, bearing, rotation }
|
||||
Self { pressure: stroke_pressure(samples), tilt, bearing, rotation, wheel: stroke_wheel(samples) }
|
||||
}
|
||||
pub(super) fn of(st: &StrokeLayer) -> Self {
|
||||
Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() }
|
||||
Self {
|
||||
pressure: st.pressure.clone(),
|
||||
tilt: st.tilt.clone(),
|
||||
bearing: st.bearing.clone(),
|
||||
rotation: st.rotation.clone(),
|
||||
wheel: st.wheel.clone(),
|
||||
}
|
||||
}
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
@@ -195,6 +213,7 @@ impl PenRecord {
|
||||
tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len),
|
||||
bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len),
|
||||
rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len),
|
||||
wheel: PressureProfile::extended(self.wheel.as_ref(), old_len, added.wheel.as_ref(), added_len),
|
||||
}
|
||||
}
|
||||
/// The record along the path reversed.
|
||||
@@ -204,6 +223,7 @@ impl PenRecord {
|
||||
tilt: self.tilt.as_ref().map(PressureProfile::reversed),
|
||||
bearing: self.bearing.as_ref().map(AngleProfile::reversed),
|
||||
rotation: self.rotation.as_ref().map(AngleProfile::reversed),
|
||||
wheel: self.wheel.as_ref().map(PressureProfile::reversed),
|
||||
}
|
||||
}
|
||||
/// Keep the record on stroke `st`.
|
||||
@@ -212,6 +232,7 @@ impl PenRecord {
|
||||
st.tilt = self.tilt;
|
||||
st.bearing = self.bearing;
|
||||
st.rotation = self.rotation;
|
||||
st.wheel = self.wheel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,18 +366,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;
|
||||
|
||||
@@ -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, ®ion, 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, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
@@ -407,7 +438,7 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\"";
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
@@ -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, ®ion, 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());
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Drop Artwork",
|
||||
[],
|
||||
None,
|
||||
"{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step",
|
||||
"{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: as edit.paste} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}",
|
||||
has_doc,
|
||||
drop_selection
|
||||
),
|
||||
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Front",
|
||||
["Edit"],
|
||||
Some("Cmd+F"),
|
||||
"{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, profileMismatch? (as edit.paste), artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Front)
|
||||
),
|
||||
@@ -198,7 +198,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Back",
|
||||
["Edit"],
|
||||
Some("Cmd+B"),
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Back)
|
||||
),
|
||||
@@ -207,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste in Place",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+V"),
|
||||
"{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::InPlace)
|
||||
),
|
||||
@@ -216,7 +216,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste on All Artboards",
|
||||
["Edit"],
|
||||
Some("Cmd+Alt+Shift+V"),
|
||||
"{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
"{swatchConflict?, profileMismatch? (as edit.paste)} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::AllArtboards)
|
||||
),
|
||||
@@ -1278,26 +1278,12 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Document ids scope node ids: two tabs may contain objects with the same node id.
|
||||
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "edit.dropSelection";
|
||||
let uid = u64_req(p, "sourceDocument", CMD)?;
|
||||
u64_req(p, "sourceDocument", CMD)?;
|
||||
let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates")));
|
||||
let grab = point("grab")?;
|
||||
let at = point("at")?;
|
||||
let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?;
|
||||
let key = "ids";
|
||||
let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
if values.is_empty() || values.len() > 10000 {
|
||||
return Err(bad(CMD, "ids must contain 1–10000 object ids"));
|
||||
}
|
||||
let ids = values
|
||||
.iter()
|
||||
.map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer"))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// Validate the entire batch in one walk; node ids are local to the source document.
|
||||
let paths = source.doc.index_paths(ids.iter().copied());
|
||||
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false);
|
||||
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
|
||||
let clip = drop_clip(s, p, CMD)?;
|
||||
let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?;
|
||||
let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]);
|
||||
if !center.x.is_finite() || !center.y.is_finite() {
|
||||
@@ -1305,7 +1291,38 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A drop preserves the source colours even when the flyer has same-named swatches.
|
||||
let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?;
|
||||
paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices)
|
||||
// Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as
|
||||
// the policies say.
|
||||
let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile, true);
|
||||
let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices);
|
||||
if let Ok(v) = &mut r
|
||||
&& !report.is_empty()
|
||||
{
|
||||
v["profileMismatch"] = json!(report);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The objects `ids` of the open document `sourceDocument` that `edit.dropSelection` drops, copied
|
||||
/// as a clipboard is (errors name command `cmd`).
|
||||
pub(crate) fn drop_clip(s: &Session, p: &Value, cmd: &str) -> Result<Clipboard> {
|
||||
let uid = u64_req(p, "sourceDocument", cmd)?;
|
||||
let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(cmd, "that document is no longer open"))?;
|
||||
let key = "ids";
|
||||
let values = p[key].as_array().ok_or_else(|| bad(cmd, format!("{key} must be an array of non-negative integer object ids")))?;
|
||||
if values.is_empty() || values.len() > 10000 {
|
||||
return Err(bad(cmd, "ids must contain 1–10000 object ids"));
|
||||
}
|
||||
let ids = values
|
||||
.iter()
|
||||
.map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("invalid object id {value}: expected a non-negative integer"))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// Validate the entire batch in one walk; node ids are local to the source document.
|
||||
let paths = source.doc.index_paths(ids.iter().copied());
|
||||
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
Ok(Clipboard::copy(source, &roots_of(&source.doc, ids), false))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -1340,10 +1357,23 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result<Value> {
|
||||
if mode == PasteMode::Offset {
|
||||
check_numbers(p, &["dx", "dy"], "edit.paste")?;
|
||||
}
|
||||
let profile = super::colormgmt::PasteProfile::param(p, mode.label())?;
|
||||
// Taken out of the session for the edit (and put back whatever happens).
|
||||
let clip = std::mem::take(&mut s.clipboard);
|
||||
let r = paste_clip(s, p, mode, &clip, &choices);
|
||||
// Colors copied from a document with other profiles keep their numbers or convert
|
||||
// (Edit › Color Settings' policies, or `profileMismatch`). Paste on All Artboards leaves the
|
||||
// copied artboards, and so their backgrounds, behind.
|
||||
let (converted, report) = match s.doc() {
|
||||
Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile, mode != PasteMode::AllArtboards),
|
||||
Err(_) => (None, vec![]),
|
||||
};
|
||||
let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices);
|
||||
s.clipboard = clip;
|
||||
if let Ok(v) = &mut r
|
||||
&& !report.is_empty()
|
||||
{
|
||||
v["profileMismatch"] = json!(report);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
@@ -1520,6 +1550,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
vec![Affine::IDENTITY]
|
||||
};
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
// Converted colors are compared with the document's resources, as another document's are
|
||||
// (`Clipboard::import_into`); its images are still the document's own.
|
||||
let imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
@@ -1611,6 +1643,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)?);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,15 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
map_graphic
|
||||
),
|
||||
cmd!(
|
||||
"threeD.mapArt",
|
||||
"Map Art",
|
||||
[],
|
||||
None,
|
||||
"{surface?: integer (1..the object's surface count: Extrude & Bevel (Classic) numbers each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; Revolve (Classic)'s swept side is surface 1, in a group the side of the member with the longest profile, and the other members take no map), symbol?: name of a document symbol|null (with surface: the symbol mapped onto it; null removes the surface's map, also a map kept past the surface count, and is refused with x, y, scaleX, scaleY, rotation or fit true; omitted: the surface's map keeps its symbol, and a surface with no map is refused), x?: pt, y?: pt (-1000000..1000000; the offset of the art's center from the center of the surface laid out flat; a new map starts at 0, 0), scaleX?: %, scaleY?: % (1..10000; of the symbol's own width and height; a new map starts at 100), rotation?: degrees (-360..360; counterclockwise; a new map starts at 0), fit?: bool (false; true is Scale to Fit: the art is centered and scaled to fill the surface, each side on its own when the art is square to the surface, else in proportion; art with no area keeps its scales), clearAll?: bool (false; true removes every map first, so with surface only that surface's map is left), shade?: bool (Shade Artwork: the mapped art takes the tone and highlight of its face), invisible?: bool (Invisible Geometry: with at least one map, only the mapped art is drawn), index?: int (the 3D effect's position; default: each object's first Extrude & Bevel (Classic) or Revolve (Classic), its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} set, edit or remove the art mapped onto the numbered surfaces of each selected object's 3D effect, which must be Extrude & Bevel (Classic) or Revolve (Classic) (Rotate (Classic) takes no map); one of surface, clearAll, shade or invisible is required; the maps are the effect's mapArt, mapShade and mapInvisible parameters; one undo step, and none when nothing changes → {ids: [the objects changed], maps: [the first object's maps]}",
|
||||
has_doc,
|
||||
map_art
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -158,6 +167,178 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids), "graphic": first }))
|
||||
}
|
||||
|
||||
/// The effect of `n` that Map Art edits when none is named: its first Extrude & Bevel (Classic) or
|
||||
/// Revolve (Classic), its own before its fills' and strokes'.
|
||||
fn first_mapped(n: &Node) -> Option<(Option<usize>, usize)> {
|
||||
let at = |fx: &[Effect]| fx.iter().position(|e| effects::takes_map_art(&e.id));
|
||||
at(&n.appearance.effects)
|
||||
.map(|i| (None, i))
|
||||
.or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i))))
|
||||
}
|
||||
|
||||
/// `threeD.mapArt`: sets, edits or removes the maps of each target's classic 3D effect, after
|
||||
/// checking that every target takes the change. Nothing is recorded when no target changes.
|
||||
fn map_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "threeD.mapArt";
|
||||
const PLACING: [&str; 6] = ["symbol", "x", "y", "scaleX", "scaleY", "rotation"];
|
||||
const KEYS: [&str; 15] =
|
||||
["surface", "symbol", "x", "y", "scaleX", "scaleY", "rotation", "fit", "clearAll", "shade", "invisible", "index", "item", "ids", "id"];
|
||||
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) {
|
||||
return Err(bad(C, format!("unknown parameter `{key}`")));
|
||||
}
|
||||
if p.get("item").is_some() && p.get("index").is_none() {
|
||||
return Err(bad(C, "`item` needs `index`"));
|
||||
}
|
||||
let surface = match p.get("surface") {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_u64()
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.filter(|n| (1..=effects::MAX_MAP_SURFACE).contains(n))
|
||||
.ok_or_else(|| bad(C, "`surface` must be a whole number from 1 to the object's surface count"))?,
|
||||
),
|
||||
};
|
||||
let fit = super::super::switch_or(p, "fit", false, C)?;
|
||||
let clear_all = super::super::switch_or(p, "clearAll", false, C)?;
|
||||
let flag = |key: &str| -> Result<Option<bool>> {
|
||||
match p.get(key) {
|
||||
None => Ok(None),
|
||||
Some(_) => super::super::switch_or(p, key, false, C).map(Some),
|
||||
}
|
||||
};
|
||||
let (shade, invisible) = (flag("shade")?, flag("invisible")?);
|
||||
match surface {
|
||||
None if fit || PLACING.iter().any(|k| p.get(*k).is_some()) => {
|
||||
return Err(bad(C, "`symbol`, `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit` need `surface`"));
|
||||
}
|
||||
None if !clear_all && shade.is_none() && invisible.is_none() => {
|
||||
return Err(bad(C, "give `surface`, `clearAll`, `shade` or `invisible`"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let removes = p.get("symbol").is_some_and(Value::is_null);
|
||||
if removes && (fit || PLACING[1..].iter().any(|k| p.get(*k).is_some())) {
|
||||
return Err(bad(C, "`symbol: null` removes the map: leave out `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit`"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let targets: Vec<(NodeId, Option<usize>, usize)> = if p.get("index").is_some() {
|
||||
let index = index_param(p, "index", C)?;
|
||||
let item = item_target(s, p, C)?;
|
||||
effect_targets(s, p, item, index, C)?
|
||||
} else {
|
||||
let mut out = vec![];
|
||||
for id in edit_targets(s, p, C)? {
|
||||
let found = d.node(id).and_then(first_mapped);
|
||||
let (item, index) = found.ok_or_else(|| bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN)))?;
|
||||
out.push((id, item, index));
|
||||
}
|
||||
out
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect"));
|
||||
}
|
||||
let mut edits = Vec::with_capacity(targets.len());
|
||||
for &(id, item, index) in &targets {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
};
|
||||
if !effects::takes_map_art(&effect.id) {
|
||||
return Err(bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN)));
|
||||
}
|
||||
let merged = effects::merged_params(&effect.id, &effect.params);
|
||||
let mut params = merged.clone();
|
||||
if clear_all {
|
||||
params[effects::MAP_ART] = json!([]);
|
||||
}
|
||||
if let Some(surface) = surface {
|
||||
// Art that can't be built has no surfaces: the effect's own check says why.
|
||||
let surfaces = match effects::map_surfaces_at(Some(d), n, item, index) {
|
||||
Some(surfaces) => surfaces,
|
||||
None => {
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, &merged, (item, index)).map_err(|e| bad(C, e))?;
|
||||
vec![]
|
||||
}
|
||||
};
|
||||
// Read before clearAll empties the list, so with clearAll the surface keeps its map.
|
||||
let current = effects::surface_maps(&merged).into_iter().find(|m| m.surface == surface);
|
||||
// A map kept past the surface count (the solid lost surfaces) can still be removed.
|
||||
let flat = surfaces.get(surface - 1);
|
||||
if flat.is_none() && !(removes && current.is_some()) {
|
||||
return Err(bad(C, format!("object {}: `surface` must be from 1 to {}, the object's surface count", id.0, surfaces.len())));
|
||||
}
|
||||
if removes {
|
||||
params = effects::with_surface_map(¶ms, surface, None);
|
||||
} else if let Some(flat) = flat {
|
||||
// The values given go over the surface's map, or over a new map's defaults.
|
||||
let mut given = match (¤t, p.get("symbol")) {
|
||||
(Some(m), _) => m.to_value(),
|
||||
(None, Some(_)) => json!({ "surface": surface }),
|
||||
(None, None) => return Err(bad(C, format!("object {}: surface {surface} has no map: give `symbol`", id.0))),
|
||||
};
|
||||
for key in PLACING {
|
||||
if let Some(v) = p.get(key) {
|
||||
given[key] = v.clone();
|
||||
}
|
||||
}
|
||||
let mut map = effects::SurfaceMap::from_value(&given).map_err(|e| bad(C, e))?;
|
||||
// A map whose symbol was deleted keeps it while the request leaves `symbol` out; a
|
||||
// symbol the request names must exist.
|
||||
if !d.symbols.iter().any(|sym| sym.name == map.symbol) && (p.get("symbol").is_some() || current.is_none()) {
|
||||
return Err(bad(C, format!("no symbol named `{}`", map.symbol)));
|
||||
}
|
||||
if fit {
|
||||
// Art or a surface with no area has no size to fit: the map is centered and
|
||||
// keeps its scales.
|
||||
let scales = effects::graphic_bounds(d, &map.symbol).and_then(|art| map.fitting_scales(art, (flat.width, flat.height)));
|
||||
let (scale_x, scale_y) = scales.unwrap_or((map.scale_x, map.scale_y));
|
||||
map = effects::SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..map };
|
||||
}
|
||||
params = effects::with_surface_map(¶ms, surface, Some(&map));
|
||||
}
|
||||
}
|
||||
for (key, value) in [(effects::MAP_SHADE, shade), (effects::MAP_INVISIBLE, invisible)] {
|
||||
if let Some(on) = value {
|
||||
params[key] = json!(on);
|
||||
}
|
||||
}
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?;
|
||||
let state = |p: &Value| {
|
||||
let on = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false);
|
||||
(effects::surface_maps(p), on(effects::MAP_SHADE), on(effects::MAP_INVISIBLE))
|
||||
};
|
||||
let maps: Vec<Value> = effects::surface_maps(¶ms).iter().map(effects::SurfaceMap::to_value).collect();
|
||||
let changed = state(¶ms) != state(&merged);
|
||||
edits.push((id, item, index, params, changed, maps));
|
||||
}
|
||||
let first = edits.first().map(|(.., maps)| maps.clone()).unwrap_or_default();
|
||||
if !edits.iter().any(|(.., changed, _)| *changed) {
|
||||
return Ok(json!({ "ids": [], "maps": first }));
|
||||
}
|
||||
let ids = s.edit("Map Art", |d, _| {
|
||||
let mut done = vec![];
|
||||
for (id, item, index, params, changed, _) in &edits {
|
||||
let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)).filter(|_| *changed) else {
|
||||
continue;
|
||||
};
|
||||
let mut current = effects::upgrade_params(&e.id, &e.params);
|
||||
for key in [effects::MAP_ART, effects::MAP_SHADE, effects::MAP_INVISIBLE] {
|
||||
if let (Some(v), Some(m)) = (params.get(key), current.as_object_mut()) {
|
||||
m.insert(key.into(), v.clone());
|
||||
}
|
||||
}
|
||||
e.params = current;
|
||||
done.push(*id);
|
||||
}
|
||||
Ok(done)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids), "maps": first }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "graphics_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "map_art_tests.rs"]
|
||||
mod map_art_tests;
|
||||
@@ -0,0 +1,258 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A 100 × 100 square with `effect` seen straight on, and a 10 × 20 red rectangle beside it kept
|
||||
/// as symbol "Mark" (11 × 21 with its stroke).
|
||||
fn setup(effect: &str) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn params(s: &Session, id: NodeId) -> Value {
|
||||
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn map(surface: u64, x: f64, scale: (f64, f64), rotation: f64) -> Value {
|
||||
json!({"surface": surface, "symbol": "Mark", "x": x, "y": 0.0, "scaleX": scale.0, "scaleY": scale.1, "rotation": rotation})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_art_sets_edits_and_removes_a_surfaces_map_one_undo_step_each() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let r = s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap();
|
||||
assert_eq!(r["ids"], json!([id.0]));
|
||||
assert_eq!(r["maps"], json!([map(1, 5.0, (100.0, 100.0), 30.0)]));
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (100.0, 100.0), 30.0)]));
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
// Without a symbol the surface's map keeps its own, and only the values given change.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "scaleX": 50.0})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (50.0, 100.0), 30.0)]));
|
||||
// Another surface takes a map of its own, kept in the order of the surfaces.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 4, "symbol": "Mark"})).unwrap();
|
||||
s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap();
|
||||
let surfaces: Vec<u64> = params(&s, id)["mapArt"].as_array().unwrap().iter().map(|m| m["surface"].as_u64().unwrap()).collect();
|
||||
assert_eq!(surfaces, [1, 2, 4]);
|
||||
// Shade Artwork and Invisible Geometry are the effect's own flags.
|
||||
s.execute("threeD.mapArt", &json!({"shade": true, "invisible": true})).unwrap();
|
||||
assert_eq!((params(&s, id)["mapShade"].clone(), params(&s, id)["mapInvisible"].clone()), (json!(true), json!(true)));
|
||||
// A null symbol clears one surface, and clearAll every surface.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": null})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"].as_array().unwrap().len(), 2);
|
||||
let r = s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap();
|
||||
assert_eq!((r["maps"].clone(), params(&s, id)["mapArt"].clone()), (json!([]), json!([])));
|
||||
// With a surface, clearAll leaves that surface's new map alone.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "clearAll": true})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(3, 0.0, (100.0, 100.0), 0.0)]));
|
||||
// Without a symbol, clearAll keeps the surface's own map and edits it.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
s.execute("threeD.mapArt", &json!({"surface": 3, "x": 4.0, "clearAll": true})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(3, 4.0, (100.0, 100.0), 0.0)]));
|
||||
assert_eq!(undo_len(&s), history + 11);
|
||||
for _ in 0..11 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_past_the_surface_count_can_still_be_removed() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark"})).unwrap();
|
||||
// With no depth the solid is a plane with fewer surfaces, and the map of surface 6 stays.
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0}})).unwrap();
|
||||
let e = s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark", "x": 3.0})).unwrap_err().to_string();
|
||||
assert!(e.contains("the object's surface count"), "{e}");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": null})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)]));
|
||||
// A surface past the count with no map is still refused.
|
||||
let e = s.execute("threeD.mapArt", &json!({"surface": 9, "symbol": null})).unwrap_err().to_string();
|
||||
assert!(e.contains("the object's surface count"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_of_a_deleted_symbol_keeps_it_only_while_the_request_leaves_symbol_out() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
s.execute("symbol.delete", &json!({"name": "Mark"})).unwrap();
|
||||
let ids = json!([id.0]);
|
||||
// Naming the deleted symbol is refused, and nothing changes.
|
||||
let e = s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": "Mark", "x": 10.0})).unwrap_err().to_string();
|
||||
assert!(e.contains("no symbol named `Mark`"), "{e}");
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)]));
|
||||
// Leaving it out edits the map and keeps its symbol, and `symbol: null` removes the map.
|
||||
s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "x": 10.0})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([map(1, 10.0, (100.0, 100.0), 0.0)]));
|
||||
s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": null})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_to_fit_centers_the_art_and_fills_the_surface() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
// The cap is 100 × 100 and the symbol's art 11 × 21.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 20.0, "y": 3.0, "fit": true})).unwrap();
|
||||
let m = ¶ms(&s, id)["mapArt"][0];
|
||||
assert_eq!((m["x"].as_f64(), m["y"].as_f64()), (Some(0.0), Some(0.0)));
|
||||
assert!((m["scaleX"].as_f64().unwrap() - 100.0 / 11.0 * 100.0).abs() < 1e-6, "{m}");
|
||||
assert!((m["scaleY"].as_f64().unwrap() - 100.0 / 21.0 * 100.0).abs() < 1e-6, "{m}");
|
||||
// A side wall is 100 along the outline and as deep as the solid, 50.
|
||||
s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "fit": true})).unwrap();
|
||||
let m = ¶ms(&s, id)["mapArt"][1];
|
||||
assert!((m["scaleY"].as_f64().unwrap() - 50.0 / 21.0 * 100.0).abs() < 1e-6, "{m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_that_changes_nothing_records_no_undo_step() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
let same = params(&s, id);
|
||||
for p in [
|
||||
json!({"surface": 1, "symbol": "Mark"}),
|
||||
json!({"surface": 1, "x": 0.0, "scaleX": 100.0}),
|
||||
json!({"surface": 2, "symbol": null}),
|
||||
json!({"shade": false}),
|
||||
json!({"invisible": false}),
|
||||
] {
|
||||
let r = s.execute("threeD.mapArt", &p).unwrap();
|
||||
assert_eq!(r["ids"], json!([]), "{p}");
|
||||
assert_eq!((undo_len(&s), params(&s, id)), (history, same.clone()), "{p}");
|
||||
}
|
||||
// Clearing an object with no map records nothing either.
|
||||
let (mut s, _) = setup("threeD.classicRevolve");
|
||||
let history = undo_len(&s);
|
||||
assert_eq!(s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap()["ids"], json!([]));
|
||||
assert_eq!(undo_len(&s), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_surfaces_symbols_and_values_are_refused() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
let history = undo_len(&s);
|
||||
let maps = params(&s, id)["mapArt"].clone();
|
||||
for (p, error) in [
|
||||
(json!({}), "give `surface`, `clearAll`, `shade` or `invisible`"),
|
||||
(json!({"surface": 0, "symbol": "Mark"}), "`surface` must be a whole number"),
|
||||
(json!({"surface": 1.5, "symbol": "Mark"}), "`surface` must be a whole number"),
|
||||
(json!({"surface": "front", "symbol": "Mark"}), "`surface` must be a whole number"),
|
||||
// The fill's solid has 6 surfaces and the stroke's, a square ring, 10: two caps and the
|
||||
// four walls of each of its two outlines.
|
||||
(json!({"surface": 17, "symbol": "Mark"}), "`surface` must be from 1 to 16"),
|
||||
(json!({"surface": 1, "symbol": "Gone"}), "no symbol named `Gone`"),
|
||||
(json!({"surface": 1, "symbol": 3}), "needs `symbol`"),
|
||||
(json!({"surface": 1}), "surface 1 has no map: give `symbol`"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "scaleX": 0}), "scaleX must be a number from 1 to 10000"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "scaleY": 10001}), "scaleY must be a number from 1 to 10000"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "rotation": -361}), "rotation must be a number from -360 to 360"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "x": 1e7}), "x must be a number"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "y": "up"}), "y must be a number"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "fit": 1}), "fit"),
|
||||
(json!({"surface": 1, "symbol": null, "x": 4.0}), "`symbol: null` removes the map"),
|
||||
(json!({"surface": 1, "symbol": null, "rotation": 30.0}), "`symbol: null` removes the map"),
|
||||
(json!({"surface": 1, "symbol": null, "fit": true}), "`symbol: null` removes the map"),
|
||||
(json!({"symbol": "Mark"}), "need `surface`"),
|
||||
(json!({"fit": true}), "need `surface`"),
|
||||
(json!({"shade": "on"}), "shade"),
|
||||
(json!({"invisible": 1}), "invisible"),
|
||||
(json!({"clearAll": "yes"}), "clearAll"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "face": "front"}), "unknown parameter `face`"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "item": null}), "`item` needs `index`"),
|
||||
(json!({"surface": 1, "symbol": "Mark", "index": 3}), "needs a 3D effect at index 3"),
|
||||
] {
|
||||
let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(error), "{p}: {e}");
|
||||
}
|
||||
assert_eq!((undo_len(&s), params(&s, id)["mapArt"].clone()), (history, maps));
|
||||
// Revolve (Classic) has one surface, and the other 3D effects take no map.
|
||||
let (mut s, _) = setup("threeD.classicRevolve");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
let e = s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`surface` must be from 1 to 1"), "{e}");
|
||||
for effect in ["threeD.classicRotate", "threeD.extrude", "threeD.revolve"] {
|
||||
let (mut s, _) = setup(effect);
|
||||
for p in [json!({"surface": 1, "symbol": "Mark"}), json!({"surface": 1, "symbol": "Mark", "index": 0})] {
|
||||
let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"), "{effect}: {e}");
|
||||
}
|
||||
// The effect's own parameters refuse a map too.
|
||||
let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Mark"}]}}));
|
||||
assert!(e.is_err(), "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mapped_symbol_is_drawn_expanded_renamed_and_kept_in_use() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "scaleX": 300.0})).unwrap();
|
||||
// effect.setParams takes the same maps and refuses a symbol the document does not have.
|
||||
let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Gone"}]}}));
|
||||
assert!(e.unwrap_err().to_string().contains("Gone"));
|
||||
// The symbol counts as used, and renaming it renames it in the map.
|
||||
assert_eq!(s.execute("symbol.unused", &json!({})).unwrap()["names"], json!([]));
|
||||
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Logo"})).unwrap();
|
||||
assert_eq!(params(&s, id)["mapArt"][0]["symbol"], "Logo");
|
||||
// Expand Appearance keeps the mapped art: the red fill is among the expanded paths.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut red = 0;
|
||||
for l in &d.layers {
|
||||
l.walk(&mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Fill(f) = item
|
||||
&& f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.9 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1)
|
||||
&& n.visual_bounds().is_some_and(|b| b.x0 < 250.0)
|
||||
{
|
||||
red += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
assert!(red > 0, "the expanded art holds the mapped symbol's red fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_into_another_document_a_map_brings_its_symbol() {
|
||||
let (mut s, id) = setup("threeD.classicExtrude");
|
||||
s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
// The symbol the pasted object's map names, and the size of that symbol's art.
|
||||
let pasted = |s: &mut Session| {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let n = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
let name = n.appearance.effects[0].params["mapArt"][0]["symbol"].as_str().unwrap().to_string();
|
||||
let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height()));
|
||||
(name, size)
|
||||
};
|
||||
// A document without the symbol gets it.
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0))));
|
||||
// A document whose symbol "Mark" is other art gets the copied symbol under a free name, and
|
||||
// the map names it.
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap();
|
||||
let (name, size) = pasted(&mut s);
|
||||
assert_ne!(name, "Mark");
|
||||
assert_eq!(size, Some((11.0, 21.0)));
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -41,7 +41,7 @@ mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
pub mod hpgl;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
@@ -84,7 +84,7 @@ pub(crate) use load::page_or_editing_data;
|
||||
pub(crate) use load::source;
|
||||
pub use load::{
|
||||
Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image,
|
||||
read_for_open, texture_image,
|
||||
read_for_open, read_for_open_asking, texture_image,
|
||||
};
|
||||
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
@@ -98,7 +98,7 @@ pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
|
||||
pub(crate) use psdlayers::import_active as psd_layers;
|
||||
pub use psdlayers::{PsdInfo, info as psd_info};
|
||||
pub use psdlayers::{LAYER_WARNINGS as PSD_LAYER_WARNINGS, MERGED_WARNING as PSD_MERGED_WARNING, PsdInfo, info as psd_info};
|
||||
pub(crate) use psdslices::over as psd_slices;
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
|
||||
@@ -297,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).
|
||||
@@ -305,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
|
||||
@@ -324,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")]
|
||||
|
||||
@@ -68,6 +68,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("commands".into(), Value::Array(cmds));
|
||||
}
|
||||
if !s.previewing {
|
||||
s.note_shape_drawn("command.batch", &entry);
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
}
|
||||
Ok(json!({ "results": results }))
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a pr
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -878,7 +878,7 @@ fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Optio
|
||||
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
|
||||
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
|
||||
/// contradict it). The image size limits are checked with the scale, as for an artboard.
|
||||
fn page_rect(f: &Format, p: &Value) -> Result<Option<Rect>> {
|
||||
pub(super) fn page_rect(f: &Format, p: &Value) -> Result<Option<Rect>> {
|
||||
let v = match p.get("rect") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(v) => v,
|
||||
|
||||
@@ -6,6 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE};
|
||||
use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::{Result, bad, number_or, switch_or, text_param};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
@@ -92,10 +93,58 @@ fn hex(v: &Value) -> Option<[u8; 3]> {
|
||||
Some([byte(0)?, byte(2)?, byte(4)?])
|
||||
}
|
||||
|
||||
/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with
|
||||
/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let opts = parse(p)?;
|
||||
/// Check the HP-GL options and the artboard choice in `p` for an export of `doc`, as the export
|
||||
/// reads them, without exporting (dialogs keep themselves open on an error).
|
||||
pub fn check(doc: &Document, p: &Value) -> std::result::Result<(), String> {
|
||||
let run = || -> Result<()> {
|
||||
parse(p)?;
|
||||
with_plotted(doc, p, |_, _| Ok(()))
|
||||
};
|
||||
run().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The pen table an export of `doc` with the options and artboard choice in `p`, and no `pens`,
|
||||
/// uses: pen 1's color first, as `#rrggbb` colors. Empty when nothing is plotted; an error when
|
||||
/// the options or the artboard choice are refused.
|
||||
pub fn automatic_pens(doc: &Document, p: &Value) -> std::result::Result<Vec<String>, String> {
|
||||
let run = || -> Result<Vec<[u8; 3]>> {
|
||||
let mut q = p.clone();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("pens");
|
||||
}
|
||||
// The order the paths are drawn in doesn't change which pen a color gets.
|
||||
let opts = HpglOptions { sort: false, inside_first: false, ..parse(&q)? };
|
||||
with_plotted(doc, &q, |doc, regions| {
|
||||
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
Ok(plots.first().map(|o| o.pens.clone()).unwrap_or_default())
|
||||
})
|
||||
};
|
||||
let pens = run().map_err(|e| e.to_string())?;
|
||||
Ok(pens.iter().map(|[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Run `f` on the document an export of `doc` with `p` plots and the regions of its plots: with
|
||||
/// `useArtboards: false`, a copy of `doc` whose one artboard is the bounds of the visible art.
|
||||
/// Like the export, it refuses `rect`, leaves out an opacity-mask or symbol editing layer, and
|
||||
/// measures the bounds without the art a plot draws nothing for.
|
||||
fn with_plotted<T>(doc: &Document, p: &Value, f: impl FnOnce(&Document, Vec<Rect>) -> Result<T>) -> Result<T> {
|
||||
let format = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?;
|
||||
super::encode::page_rect(format, p)?;
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let use_artboards = super::encode::use_artboards(C, p)?;
|
||||
if use_artboards == Some(false)
|
||||
&& let Some((art, q)) = super::encode::art_page(C, doc, p, |n| vectorcraft_cad::hpgl::write::plots_nothing(doc, n))?
|
||||
{
|
||||
let (_, regions) = boards(&art, &q, None)?;
|
||||
return f(&art, regions);
|
||||
}
|
||||
let (_, regions) = boards(doc, p, use_artboards)?;
|
||||
f(doc, regions)
|
||||
}
|
||||
|
||||
/// The artboards a plot of `doc` covers and their regions: the chosen artboard (default the
|
||||
/// first), or with `use_artboards` each chosen one (default all).
|
||||
fn boards(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<(Vec<usize>, Vec<Rect>)> {
|
||||
let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?;
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
@@ -103,10 +152,25 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
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 regions = 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<_>>>()?;
|
||||
// The writer's own region check, so a dialog's check refuses what the writer refuses.
|
||||
for r in ®ions {
|
||||
vectorcraft_cad::hpgl::write::check_region(*r).map_err(|e| bad(C, e))?;
|
||||
}
|
||||
Ok((boards, regions))
|
||||
}
|
||||
|
||||
/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with
|
||||
/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let opts = parse(p)?;
|
||||
let (boards, regions) = boards(doc, p, use_artboards)?;
|
||||
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for (b, out) in boards.into_iter().zip(plots) {
|
||||
@@ -118,9 +182,6 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
}
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let regions: Vec<vectorcraft_geom::Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
Ok(enc)
|
||||
|
||||
@@ -686,6 +686,29 @@ pub struct ReadFile {
|
||||
links: Resolved,
|
||||
/// Whether the color management policies changed the document ([`apply_policies`]).
|
||||
policy_changed: bool,
|
||||
/// The answer to the document's profile question (`profileChoice`, or the app's prompt).
|
||||
choice: Option<crate::cmd::colormgmt::ProfileChoice>,
|
||||
/// What opening still has to do while the app asks about the profile ([`ReadFile::question`]):
|
||||
/// the policies, the color mode, the linked files and the type are left for
|
||||
/// [`ReadFile::answer`] or [`open_read`].
|
||||
rest: Option<Rest>,
|
||||
/// The answer that was used and the question it answered (`document.open`'s `profileChoice`
|
||||
/// reply).
|
||||
answered: Option<Value>,
|
||||
/// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while
|
||||
/// the question is still the same.
|
||||
asked: Option<crate::cmd::colormgmt::ProfileQuestion>,
|
||||
/// Update Links and the low-resolution EPS proxy setting, while the linked files and the type
|
||||
/// are left to do after the answer ([`ReadFile::finish_read`]).
|
||||
links_left: Option<(bool, bool)>,
|
||||
}
|
||||
|
||||
/// The part of [`read_for_open`] a file waiting for a profile answer has left to do.
|
||||
struct Rest {
|
||||
update_links: bool,
|
||||
low_res_proxy_eps: bool,
|
||||
/// The color mode `colorMode` asks for, converted after the policies.
|
||||
color_mode: Option<vectorcraft_doc::ColorMode>,
|
||||
}
|
||||
|
||||
/// Edit › Color Settings: the color management policies keep, take off or convert from the
|
||||
@@ -714,36 +737,145 @@ impl ReadFile {
|
||||
/// reads (`importer` in `p`, or an extension only an importer lists) is read by it
|
||||
/// ([`super::importer`]).
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
|
||||
read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false)
|
||||
}
|
||||
|
||||
/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile
|
||||
/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no
|
||||
/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or
|
||||
/// [`open_read`], with the policy's choice) does the rest.
|
||||
pub fn read_for_open_asking(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
path: Option<String>,
|
||||
p: &Value,
|
||||
update_links: bool,
|
||||
low_res_proxy_eps: bool,
|
||||
ask: bool,
|
||||
) -> Result<ReadFile> {
|
||||
let opts = LoadOptions::from_params("document.open", p)?;
|
||||
let (mut loaded, policy_changed) = if opts.link_pages {
|
||||
let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
let choice = crate::cmd::colormgmt::ProfileChoice::param(p, "document.open")?;
|
||||
let (loaded, color_mode) = if opts.link_pages {
|
||||
(linked_pages(name, bytes, path.as_deref(), &opts)?, None)
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => {
|
||||
let mut loaded = super::importer::load(name, bytes, &plugin, p)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
}
|
||||
None => {
|
||||
// The color mode `p` asks for converts the colors after the policies did, through
|
||||
// the profiles the document keeps.
|
||||
let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) {
|
||||
let doc = &mut loaded.doc;
|
||||
vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || {
|
||||
super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays);
|
||||
});
|
||||
}
|
||||
(loaded, changed)
|
||||
}
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None),
|
||||
// The color mode `p` asks for converts the colors after the policies did, through the
|
||||
// profiles the document keeps.
|
||||
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
|
||||
}
|
||||
};
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut loaded.doc);
|
||||
Ok(ReadFile { loaded, opts, path, links, policy_changed })
|
||||
let mut file = ReadFile {
|
||||
loaded,
|
||||
opts,
|
||||
path,
|
||||
links: Resolved::default(),
|
||||
policy_changed: false,
|
||||
choice,
|
||||
rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }),
|
||||
answered: None,
|
||||
asked: None,
|
||||
links_left: None,
|
||||
};
|
||||
if ask && file.choice.is_none() && file.ask().is_some() {
|
||||
return Ok(file);
|
||||
}
|
||||
file.finish_read()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
impl ReadFile {
|
||||
/// The file's name, for a prompt.
|
||||
pub fn name(&self) -> String {
|
||||
self.path.as_deref().map(file_name).unwrap_or_else(|| self.loaded.doc.title.clone())
|
||||
}
|
||||
|
||||
/// The profile question Edit › Color Settings asks about this file before it opens (its Ask
|
||||
/// When Opening box of that kind is on), while the file waits for the answer
|
||||
/// ([`read_for_open_asking`]); none once it is answered or read through.
|
||||
pub fn question(&self) -> Option<crate::cmd::colormgmt::ProfileQuestion> {
|
||||
self.rest.as_ref()?;
|
||||
let st = vectorcraft_color::cms::working_settings();
|
||||
crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st))
|
||||
}
|
||||
|
||||
/// [`Self::question`], kept as the question asked: [`Self::answer`] takes an answer only while
|
||||
/// the question is still the same. The app calls it when it shows the question.
|
||||
pub fn ask(&mut self) -> Option<crate::cmd::colormgmt::ProfileQuestion> {
|
||||
self.asked = self.question();
|
||||
self.asked.clone()
|
||||
}
|
||||
|
||||
/// Answer the profile question with `choice` and apply it: the policies (the answer in place of
|
||||
/// the one of the document's color mode) and the color mode. The linked files and the type are
|
||||
/// left for [`Self::finish_read`] or [`open_read`]. An error leaves the file waiting: a profile
|
||||
/// to assign that is not one of that model, or Color Settings changed since the question was
|
||||
/// asked ([`Self::ask`]) so that the question, its model, the profile it is about or the working
|
||||
/// space differ.
|
||||
pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> {
|
||||
if let Some(asked) = &self.asked
|
||||
&& self.rest.is_some()
|
||||
{
|
||||
let now = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let key = |q: &crate::cmd::colormgmt::ProfileQuestion| (q.issue, q.model, q.profile.clone(), q.working.clone());
|
||||
if now.as_ref().map(key) != Some(key(asked)) {
|
||||
return Err(bad("document.open", "the profile question changed since it was asked: answer the question it asks now"));
|
||||
}
|
||||
}
|
||||
let before = self.choice.replace(choice);
|
||||
let r = self.apply_answer();
|
||||
if r.is_err() {
|
||||
self.choice = before;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The rest of [`read_for_open_asking`], once: the color management policies with the profile
|
||||
/// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked
|
||||
/// files and the type. The app runs it off the UI thread once the question is answered.
|
||||
pub fn finish_read(&mut self) -> Result<()> {
|
||||
self.apply_answer()?;
|
||||
self.finish_links();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read the linked files and lay out the type of a file whose profile answer is applied
|
||||
/// ([`Self::answer`]), once. A file still waiting for its answer is left as it is.
|
||||
fn finish_links(&mut self) {
|
||||
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
|
||||
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
|
||||
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut self.loaded.doc);
|
||||
}
|
||||
|
||||
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
|
||||
/// linked files and the type are left for [`Self::finish_read`].
|
||||
fn apply_answer(&mut self) -> Result<()> {
|
||||
if self.rest.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// The question the answer was given to, for the reply's `profileChoice`.
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let answered = match (&self.choice, &question) {
|
||||
(Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })),
|
||||
_ => None,
|
||||
};
|
||||
// A failure leaves the file waiting, unchanged.
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?;
|
||||
let Some(rest) = self.rest.take() else { return Ok(()) };
|
||||
self.answered = answered;
|
||||
self.loaded.warnings.extend(notes);
|
||||
self.policy_changed = changed;
|
||||
if let Some(mode) = rest.color_mode.filter(|m| *m != self.loaded.doc.color_mode) {
|
||||
let doc = &mut self.loaded.doc;
|
||||
let grays = self.opts.grays;
|
||||
vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || {
|
||||
super::super::colormgmt::set_color_mode(doc, mode, true, None, grays);
|
||||
});
|
||||
}
|
||||
self.links_left = Some((rest.update_links, rest.low_res_proxy_eps));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents
|
||||
@@ -757,8 +889,15 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions
|
||||
|
||||
/// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active
|
||||
/// document → `document.open`'s result.
|
||||
pub fn open_read(s: &mut Session, file: ReadFile) -> Result<Value> {
|
||||
open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)
|
||||
/// A file still waiting for its profile answer ([`ReadFile::question`]) opens as its policy says.
|
||||
pub fn open_read(s: &mut Session, mut file: ReadFile) -> Result<Value> {
|
||||
file.finish_read()?;
|
||||
let answered = file.answered.take();
|
||||
let mut r = open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)?;
|
||||
if let Some(a) = answered {
|
||||
r["profileChoice"] = a;
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// File → New from Template: any readable file (at `path`, if it is one: its links are looked for
|
||||
@@ -962,7 +1101,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 +1279,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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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()?);
|
||||
|
||||
@@ -684,57 +684,64 @@ struct Counts {
|
||||
clipped_out: usize,
|
||||
}
|
||||
|
||||
/// `n` things: "1 layer was", "2 layers were".
|
||||
fn count(n: usize, one: &str, many: &str) -> String {
|
||||
if n == 1 { format!("1 {one} was") } else { format!("{n} {many} were") }
|
||||
/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place
|
||||
/// of `{n}` when it is more, none when it is 0. Each form is a whole sentence, the key of its own
|
||||
/// catalog row.
|
||||
fn note(out: &mut Vec<String>, n: usize, (one, many): (&str, &str)) {
|
||||
match n {
|
||||
0 => {}
|
||||
1 => out.push(one.to_string()),
|
||||
n => out.push(many.replace("{n}", &n.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer warnings in English, the form for one layer and the form for more, in the order a
|
||||
/// file's warnings list them.
|
||||
pub const LAYER_WARNINGS: [(&str, &str); 10] = [
|
||||
("1 type layer came in as pixels: the text isn't editable", "{n} type layers came in as pixels: the text isn't editable"),
|
||||
("1 adjustment layer was not applied", "{n} adjustment layers were not applied"),
|
||||
(
|
||||
"1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)",
|
||||
"{n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)",
|
||||
),
|
||||
("the layer effects of 1 layer weren't drawn", "the layer effects of {n} layers weren't drawn"),
|
||||
("the vector masks of 1 layer weren't applied", "the vector masks of {n} layers weren't applied"),
|
||||
("the knockout of 1 layer wasn't applied", "the knockout of {n} layers wasn't applied"),
|
||||
(
|
||||
"1 layer was left out (hidden layers and the layers clipped to them)",
|
||||
"{n} layers were left out (hidden layers and the layers clipped to them)",
|
||||
),
|
||||
("1 layer clipped to a fill layer that wasn't drawn was left out", "{n} layers clipped to fill layers that weren't drawn were left out"),
|
||||
(
|
||||
"1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed",
|
||||
"{n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed",
|
||||
),
|
||||
(
|
||||
"1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed",
|
||||
"{n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed",
|
||||
),
|
||||
];
|
||||
|
||||
/// The warning for layers merged with the layers below them, `{modes}` the blend modes' names.
|
||||
pub const MERGED_WARNING: &str = "layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them";
|
||||
|
||||
impl Notes {
|
||||
fn warnings(self) -> Vec<String> {
|
||||
let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS;
|
||||
let mut out = vec![];
|
||||
if self.types > 0 {
|
||||
let n = if self.types == 1 { "1 type layer".to_string() } else { format!("{} type layers", self.types) };
|
||||
out.push(format!("{n} came in as pixels: the text isn't editable"));
|
||||
}
|
||||
if self.adjustments > 0 {
|
||||
out.push(format!("{} not applied", count(self.adjustments, "adjustment layer", "adjustment layers")));
|
||||
}
|
||||
if self.fills > 0 {
|
||||
out.push(format!(
|
||||
"{} not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)",
|
||||
count(self.fills, "fill layer", "fill layers")
|
||||
));
|
||||
}
|
||||
let layers = |n: usize| if n == 1 { "1 layer".to_string() } else { format!("{n} layers") };
|
||||
if self.effects > 0 {
|
||||
out.push(format!("the layer effects of {} weren't drawn", layers(self.effects)));
|
||||
}
|
||||
if self.vector_masks > 0 {
|
||||
out.push(format!("the vector masks of {} weren't applied", layers(self.vector_masks)));
|
||||
}
|
||||
if self.knockouts > 0 {
|
||||
out.push(format!("the knockout of {} wasn't applied", layers(self.knockouts)));
|
||||
}
|
||||
if self.hidden > 0 {
|
||||
out.push(format!("{} left out (hidden layers and the layers clipped to them)", count(self.hidden, "layer", "layers")));
|
||||
}
|
||||
if self.clipped_out == 1 {
|
||||
out.push("1 layer clipped to a fill layer that wasn't drawn was left out".into());
|
||||
} else if self.clipped_out > 1 {
|
||||
out.push(format!("{} layers clipped to fill layers that weren't drawn were left out", self.clipped_out));
|
||||
}
|
||||
note(&mut out, self.types, types);
|
||||
note(&mut out, self.adjustments, adjustments);
|
||||
note(&mut out, self.fills, fills);
|
||||
note(&mut out, self.effects, effects);
|
||||
note(&mut out, self.vector_masks, masks);
|
||||
note(&mut out, self.knockouts, knockouts);
|
||||
note(&mut out, self.hidden, hidden);
|
||||
note(&mut out, self.clipped_out, clipped_out);
|
||||
if !self.merged.is_empty() {
|
||||
out.push(format!("layers in blend modes VectorCraft doesn't have ({}) were merged with the layers below them", self.merged.join(", ")));
|
||||
}
|
||||
if self.unmerged > 0 {
|
||||
out.push(format!(
|
||||
"{} in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed",
|
||||
layers(self.unmerged)
|
||||
));
|
||||
}
|
||||
if self.unclipped > 0 {
|
||||
out.push(format!("{} clipped to the layer below came in unclipped: the merge needs more memory than allowed", layers(self.unclipped)));
|
||||
out.push(MERGED_WARNING.replace("{modes}", &self.merged.join(", ")));
|
||||
}
|
||||
note(&mut out, self.unmerged, unmerged);
|
||||
note(&mut out, self.unclipped, unclipped);
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -175,8 +175,9 @@ fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
|
||||
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
|
||||
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
|
||||
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
|
||||
if list.len() > MAX_SLICES {
|
||||
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
|
||||
let count = list.len();
|
||||
if count > MAX_SLICES {
|
||||
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
|
||||
}
|
||||
let mut out = vec![];
|
||||
for s in list {
|
||||
|
||||
@@ -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))?;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -534,6 +534,104 @@ fn export_options_are_checked() {
|
||||
let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true});
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap();
|
||||
assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;");
|
||||
// The check a dialog runs refuses the same options, and passes the given ones.
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
assert!(hpgl::check(&doc, &json!({"pens": ["#ff0000", "red"]})).unwrap_err().contains("`pens`"));
|
||||
assert!(hpgl::check(&doc, &json!({"curveTolerance": 11})).unwrap_err().contains("`curveTolerance`"));
|
||||
assert_eq!(hpgl::check(&doc, &p), Ok(()));
|
||||
// It checks the artboard choice as the export does: an artboard or range past the document's,
|
||||
// a `useArtboards` that isn't true or false, and the art's bounds when no art shows.
|
||||
let mut blank = Session::new();
|
||||
blank.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let blank_doc = blank.doc().unwrap().doc.clone();
|
||||
for (on_blank, p) in [
|
||||
(false, json!({"format": "hpgl", "artboard": 2})),
|
||||
(false, json!({"format": "hpgl", "useArtboards": true, "range": "1-3"})),
|
||||
(false, json!({"format": "hpgl", "artboards": [0, 1]})),
|
||||
(false, json!({"format": "hpgl", "useArtboards": "yes"})),
|
||||
(true, json!({"format": "hpgl", "useArtboards": false})),
|
||||
] {
|
||||
let (session, d) = if on_blank { (&mut blank, &blank_doc) } else { (&mut s, &doc) };
|
||||
assert!(hpgl::check(d, &p).is_err(), "{p}");
|
||||
assert!(session.execute("document.export", &p).is_err(), "{p}");
|
||||
}
|
||||
// An artboard with no width is refused before the writer refuses it.
|
||||
let mut flat = vectorcraft_doc::Document::clone(&doc);
|
||||
flat.artboards[1].rect = vectorcraft_geom::Rect::new(200.0, 0.0, 200.0, 100.0);
|
||||
assert_eq!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err(), hpgl::check(&flat, &json!({"useArtboards": true})).unwrap_err());
|
||||
assert!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err().contains("the export region is empty"));
|
||||
assert_eq!(hpgl::check(&flat, &json!({})), Ok(()));
|
||||
// A document with no artboard has nothing to plot on one, or on each.
|
||||
flat.artboards.clear();
|
||||
for p in [json!({}), json!({"useArtboards": true})] {
|
||||
assert!(hpgl::check(&flat, &p).unwrap_err().contains("the document has no artboard"), "{p}");
|
||||
}
|
||||
// An area of the page is a raster export's option: the export refuses it, and so does the check.
|
||||
let rect = json!({"format": "hpgl", "rect": [0, 0, 10, 10]});
|
||||
assert!(s.execute("document.export", &rect).is_err());
|
||||
assert!(hpgl::check(&doc, &rect).unwrap_err().contains("rect applies to raster formats"));
|
||||
assert_eq!(hpgl::check(&doc, &json!({"useArtboards": true, "range": "2"})), Ok(()));
|
||||
assert_eq!(hpgl::check(&doc, &json!({"useArtboards": false})), Ok(()));
|
||||
}
|
||||
|
||||
/// The pens an export without a pen table uses: one per color the plotted art draws in, in the
|
||||
/// order it first draws in each, over the artboards or the art's bounds the export plots.
|
||||
#[test]
|
||||
fn automatic_pens_list_the_plotted_art_s_colors_in_pen_order() {
|
||||
let s = two_boards();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let pens = |p: Value| hpgl::automatic_pens(doc, &p).unwrap();
|
||||
assert_eq!(pens(json!({})), ["#000000"], "the first artboard");
|
||||
assert_eq!(pens(json!({"artboard": 1})), ["#ff0000"]);
|
||||
assert_eq!(pens(json!({"useArtboards": true})), ["#000000", "#ff0000"], "one numbering for every file");
|
||||
assert_eq!(pens(json!({"useArtboards": false})), ["#000000", "#ff0000"], "the art's bounds");
|
||||
// The pens given and the path order are not the export's own pens.
|
||||
assert_eq!(pens(json!({"useArtboards": true, "pens": ["#00ff00"], "sortPaths": true})), ["#000000", "#ff0000"]);
|
||||
// A refused artboard choice or option is an error, not an empty table.
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"artboard": 5})).is_err());
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"curveTolerance": 20})).unwrap_err().contains("`curveTolerance`"));
|
||||
// So is an area of the page, which the export and the check refuse for HP-GL.
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"rect": [0, 0, 10, 10]})).unwrap_err().contains("rect applies to raster formats"));
|
||||
|
||||
// Art outside every artboard is plotted only with the art's bounds.
|
||||
let mut off = Session::new();
|
||||
off.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
off.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
off.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
off.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 30, "height": 30})).unwrap();
|
||||
let doc = &off.doc().unwrap().doc;
|
||||
assert_eq!(hpgl::automatic_pens(doc, &json!({})), Ok(vec![]));
|
||||
assert_eq!(hpgl::automatic_pens(doc, &json!({"useArtboards": false})), Ok(vec!["#0000ff".to_string()]));
|
||||
}
|
||||
|
||||
/// A placed document opened with only its preview is plotted with its file's art (the plot reads
|
||||
/// the file), so the check and the pens of a dialog measure that art as the export does.
|
||||
#[test]
|
||||
fn a_placed_document_s_pens_are_those_of_its_file_s_art() {
|
||||
use crate::tests_links::{Folder, open, save, session, write};
|
||||
let dir = Folder::new("hpgl-placed");
|
||||
let src = dir.file("logo.vectorcraft");
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 50.0);
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0));
|
||||
let look = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0);
|
||||
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap();
|
||||
write(&src, &vectorcraft_format::save_file(&d));
|
||||
let mut s = session();
|
||||
s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
|
||||
let poster = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &poster);
|
||||
open(&mut s, &poster);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(doc.images.values().any(vectorcraft_doc::ImageBlob::is_proxy), "opened with the preview only");
|
||||
for p in [json!({}), json!({"useArtboards": false})] {
|
||||
assert_eq!(hpgl::automatic_pens(doc, &p), Ok(vec!["#ff0000".to_string()]), "{p}");
|
||||
assert_eq!(hpgl::check(doc, &p), Ok(()), "{p}");
|
||||
}
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl"})).unwrap())).unwrap();
|
||||
assert!(plot.contains("SP1;") && plot.contains("PD"), "{plot}");
|
||||
}
|
||||
|
||||
/// `insideFirst` draws the square inside the other one first, though it was made last.
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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]> {
|
||||
|
||||
@@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
|
||||
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so
|
||||
/// that the unit setting survives a save/open round-trip. The engine-level test covers the full
|
||||
/// stack (file.new → document.setUnits → document.serialize → document.open).
|
||||
#[test]
|
||||
fn svg_round_trip_preserves_document_units() {
|
||||
// (unit name the engine accepts, expected unit after re-import)
|
||||
let cases: &[(&str, vectorcraft_doc::Unit)] = &[
|
||||
("millimeters", vectorcraft_doc::Unit::Millimeters),
|
||||
("centimeters", vectorcraft_doc::Unit::Centimeters),
|
||||
("inches", vectorcraft_doc::Unit::Inches),
|
||||
("picas", vectorcraft_doc::Unit::Picas),
|
||||
// Points and pixels both serialise as bare user-unit numbers, so both import as Pixels.
|
||||
("pixels", vectorcraft_doc::Unit::Pixels),
|
||||
];
|
||||
for (name, expected) in cases {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": name})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
match *expected {
|
||||
vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"),
|
||||
_ => {}
|
||||
}
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
let doc_state = s.doc().unwrap();
|
||||
assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'");
|
||||
}
|
||||
|
||||
// Points serialise without suffix and re-open as Pixels (equivalent in user units).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": "points"})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}");
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels);
|
||||
}
|
||||
@@ -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 }))
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Loaded 100 of 488 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user