mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 10:23:16 +01:00
Merge main into feat/color-wheel-gamut
This commit is contained in:
commit
2bcd88259f
224 files changed
+14585
-850
No files matched your search
@@ -155,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 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-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-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.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
|
||||
//!
|
||||
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
|
||||
//! and at once when the window moves to another display.
|
||||
//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -31,6 +31,8 @@ pub(crate) struct Reader {
|
||||
looked: Option<f64>,
|
||||
/// A reading is running.
|
||||
busy: Arc<AtomicBool>,
|
||||
/// [`DisplayProfile::attach_reader`] was called.
|
||||
attached: bool,
|
||||
}
|
||||
|
||||
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
|
||||
@@ -45,22 +47,22 @@ impl Drop for Done {
|
||||
impl Reader {
|
||||
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
|
||||
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
|
||||
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
|
||||
return;
|
||||
if !self.attached {
|
||||
profile.attach_reader();
|
||||
self.attached = true;
|
||||
}
|
||||
self.looked = Some(now);
|
||||
let display = window.current_monitor().and_then(|m| m.name());
|
||||
if !due(self.last.as_ref(), now, display.as_deref()) {
|
||||
let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else {
|
||||
return;
|
||||
}
|
||||
self.last = Some((now, display.clone()));
|
||||
};
|
||||
profile.pending();
|
||||
self.busy.store(true, Ordering::Release);
|
||||
let done = Done(self.busy.clone());
|
||||
let (profile, ctx) = (profile.clone(), ctx.clone());
|
||||
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
|
||||
let _done = done;
|
||||
if profile.report(read(display)) {
|
||||
let changed = profile.report(read(display));
|
||||
drop(done);
|
||||
// A request made while this reading ran starts on the next frame.
|
||||
if changed || profile.read_requested() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
@@ -68,6 +70,32 @@ impl Reader {
|
||||
log::warn!("couldn't start reading the display profile: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The display to read at `now` when a reading is to start, looked up with `display`. A
|
||||
/// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once,
|
||||
/// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the
|
||||
/// preference off drops it. A request made with the preference on is kept when the preference
|
||||
/// goes off and on again between two frames.
|
||||
fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option<String>) -> Option<Option<String>> {
|
||||
if !enabled {
|
||||
profile.take_request();
|
||||
return None;
|
||||
}
|
||||
if self.busy.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
let asked = profile.take_request();
|
||||
if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
|
||||
return None;
|
||||
}
|
||||
self.looked = Some(now);
|
||||
let display = display();
|
||||
if !asked && !due(self.last.as_ref(), now, display.as_deref()) {
|
||||
return None;
|
||||
}
|
||||
self.last = Some((now, display.clone()));
|
||||
Some(display)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
|
||||
@@ -570,6 +598,56 @@ mod tests {
|
||||
assert!(due(Some(&last), 50.0, Some("DP-1")));
|
||||
}
|
||||
|
||||
fn attached() -> DisplayProfile {
|
||||
let profile = DisplayProfile::default();
|
||||
profile.attach_reader();
|
||||
profile
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
// Inside the display lookup interval and the reading interval: nothing starts.
|
||||
assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None);
|
||||
assert_eq!(r.start(102.0, true, &profile, dp1), None);
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
assert!(!profile.read_requested(), "the request is taken");
|
||||
// The intervals run again from the requested reading.
|
||||
assert_eq!(r.start(102.2, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(111.0, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_made_while_a_reading_runs_waits_for_it_to_end() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert!(r.start(0.0, true, &profile, dp1).is_some());
|
||||
r.busy.store(true, Ordering::Release);
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(0.1, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(5.0, true, &profile, dp1), None);
|
||||
assert!(profile.read_requested(), "kept while the reading runs");
|
||||
r.busy.store(false, Ordering::Release);
|
||||
assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
assert!(!profile.read_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_is_dropped_when_the_preference_goes_off() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert!(r.start(0.0, true, &profile, dp1).is_some());
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(0.1, false, &profile, dp1), None);
|
||||
assert!(!profile.read_requested());
|
||||
assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it");
|
||||
assert!(profile.request_read(false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
|
||||
let env = |pairs: &'static [(&'static str, &'static str)]| {
|
||||
|
||||
@@ -96,7 +96,24 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
Some(folder) => d.folder(folder),
|
||||
None => d,
|
||||
};
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
if pick.name.is_empty() {
|
||||
return d;
|
||||
}
|
||||
// Windows' save dialog changes the extension when a different file type is chosen only when
|
||||
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
|
||||
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
|
||||
// A remaining dot in the stem would look like another explicit extension to Windows.
|
||||
#[cfg(windows)]
|
||||
if matches!(request, PickRequest::Save(_))
|
||||
&& pick.filters.len() > 1
|
||||
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
|
||||
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
|
||||
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
|
||||
&& !stem.contains('.')
|
||||
{
|
||||
return d.file_name(stem);
|
||||
}
|
||||
d.file_name(&pick.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -796,7 +813,7 @@ mod dialog_tests {
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
@@ -812,7 +829,8 @@ mod dialog_tests {
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.1 = Some(name.to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -869,4 +887,24 @@ mod dialog_tests {
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
|
||||
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
|
||||
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
|
||||
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
|
||||
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
|
||||
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
|
||||
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
walk(n, mode, key);
|
||||
}
|
||||
|
||||
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
|
||||
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
|
||||
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
|
||||
|
||||
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
|
||||
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
|
||||
for n in copies {
|
||||
let turn = rng.range(-amount, amount) as f32;
|
||||
turn_hues(n, turn);
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it
|
||||
/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as
|
||||
/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue:
|
||||
/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink).
|
||||
fn turned(c: &Color, degrees: f32) -> Option<Color> {
|
||||
if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
|
||||
return None;
|
||||
}
|
||||
let turn = |v: [f32; 3]| {
|
||||
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
|
||||
(s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b]))
|
||||
};
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
|
||||
Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
|
||||
Color::Gray { .. } => None,
|
||||
Color::Lab { l, a, b } => {
|
||||
let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
|
||||
let (a, b) = (f64::from(a), f64::from(b));
|
||||
Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_paint(p: &mut Paint, degrees: f32) {
|
||||
if let Paint::Solid { color, .. } = p
|
||||
&& let Some(c) = turned(color, degrees)
|
||||
{
|
||||
*p = Paint::solid(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
|
||||
/// mask's colors are its values, so they stay.
|
||||
fn turn_hues(n: &mut Node, degrees: f32) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
|
||||
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
turn_paint(&mut r.style.fill, degrees);
|
||||
turn_paint(&mut r.style.stroke, degrees);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
turn_hues(Arc::make_mut(c), degrees);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip the brushes from every stroke under `n`, its masks' art included.
|
||||
fn strip_brushes(n: &mut Node) {
|
||||
for it in &mut n.appearance.items {
|
||||
|
||||
@@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation: (-180.0, 180.0),
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::Tints,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
@@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation: (-35.0, 35.0),
|
||||
rotation_relative_to_path: true,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -298,6 +298,12 @@ pub struct Scatter {
|
||||
/// Rotation relative to the path direction (else to the page).
|
||||
pub rotation_relative_to_path: bool,
|
||||
pub colorization: Colorization,
|
||||
/// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after
|
||||
/// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's
|
||||
/// path and the brush name fix the amounts, so a stroke draws the same colors every time.
|
||||
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub hue_jitter: f64,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
@@ -318,6 +324,7 @@ impl Default for Scatter {
|
||||
rotation: (0.0, 0.0),
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}
|
||||
}
|
||||
@@ -326,6 +333,8 @@ impl Default for Scatter {
|
||||
impl Scatter {
|
||||
/// The ranges of size (%), spacing (%), scatter (%) and rotation (°).
|
||||
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
|
||||
/// The range of [`Scatter::hue_jitter`] (°).
|
||||
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
|
||||
|
||||
/// Size, spacing, scatter and rotation, each as its (first, second) values.
|
||||
pub fn values(&self) -> [(f64, f64); 4] {
|
||||
@@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6
|
||||
(within(a, range, fallback), within(b, range, fallback))
|
||||
}
|
||||
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
fn valid_tile_frame(frame: Rect) -> bool {
|
||||
[frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite)
|
||||
&& frame.width().is_finite()
|
||||
@@ -714,6 +727,7 @@ impl Brush {
|
||||
s.spacing = within_pair(s.spacing, spacing, d.spacing.0);
|
||||
s.scatter = within_pair(s.scatter, scatter, 0.0);
|
||||
s.rotation = within_pair(s.rotation, rotation, 0.0);
|
||||
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
|
||||
s.colorization.sanitize();
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
@@ -1093,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
for n in &mut out {
|
||||
colorize(n, colorization, &stroke.paint);
|
||||
}
|
||||
// One piece per copy, in the order the copies run along the path.
|
||||
if let BrushKind::Scatter(s) = &brush.kind
|
||||
&& s.hue_jitter > 0.0
|
||||
{
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
leave_out_brushed(doc, &mut out, &mut Known::new());
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1033,6 +1033,165 @@ fn stain_mixes_type_strokes_too() {
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
}
|
||||
|
||||
/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`.
|
||||
fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush {
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(Paint::solid(fill));
|
||||
Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// The fill color of each copy.
|
||||
fn fill_colors(out: &[Node]) -> Vec<Color> {
|
||||
out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect()
|
||||
}
|
||||
|
||||
/// How far hue `h` is from `from`, in degrees, either way round.
|
||||
fn hue_gap(h: f32, from: f32) -> f32 {
|
||||
let d = (h - from).rem_euclid(360.0);
|
||||
d.min(360.0 - d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_turns_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hues: Vec<f32> = colors.iter().map(|c| c.to_hsb()[0]).collect();
|
||||
assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}");
|
||||
assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}");
|
||||
// Saturation and brightness stay; the copies stay where they were, at their size and angle.
|
||||
assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}");
|
||||
let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_of_zero_changes_nothing() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red));
|
||||
// A brush without hue jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap();
|
||||
assert!(v.get("hue_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["hue_jitter"] = serde_json::json!(45.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, 45.0);
|
||||
// Values outside 0..180 are clamped.
|
||||
for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["hue_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_turns_after_the_colorization() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Tints: black art takes the blue stroke color, which then turns.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hues: Vec<f32> =
|
||||
fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect();
|
||||
assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}");
|
||||
assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}");
|
||||
// A gray stroke color has no hue: its tints stay as they are.
|
||||
let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0);
|
||||
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray);
|
||||
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray);
|
||||
assert_eq!(fill_colors(&turned), fill_colors(&still));
|
||||
// Nor does black ink alone, nor a gray, as a process stroke color.
|
||||
for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] {
|
||||
let key = StrokeLayer::new(Paint::solid(key), 1.0);
|
||||
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key);
|
||||
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key);
|
||||
assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}");
|
||||
}
|
||||
// A turned process color stays a process color, turned over its C, M and Y with its K kept.
|
||||
let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0)));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert_eq!(k, 0.25);
|
||||
// Full ink in one channel and none in another, as the color before it.
|
||||
assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}");
|
||||
}
|
||||
// An RGB color keeps its saturation and brightness in its own values.
|
||||
let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0)));
|
||||
for c in &rgb {
|
||||
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
|
||||
assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}");
|
||||
}
|
||||
// A Lab color keeps its lightness and chroma.
|
||||
let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0)));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
for c in &lab {
|
||||
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
|
||||
assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color
|
||||
/// linked to a swatch (which loses the link); a pattern paint stays.
|
||||
#[test]
|
||||
fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let typed = |hue_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }),
|
||||
};
|
||||
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
|
||||
let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0)));
|
||||
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
|
||||
assert_eq!(turned.len(), still.len());
|
||||
assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}");
|
||||
assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}");
|
||||
// Tints and Shades and Hue Shift: the colors they give turn.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] {
|
||||
let art = Color::rgb(1.0, 0.0, 0.0);
|
||||
let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue));
|
||||
let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue));
|
||||
assert_eq!(turned.len(), still.len());
|
||||
assert_ne!(turned, still, "{colorization:?}");
|
||||
for (t, s) in turned.iter().zip(&still) {
|
||||
assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}");
|
||||
}
|
||||
}
|
||||
// A color linked to a swatch turns and loses the link; a pattern paint stays.
|
||||
let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 };
|
||||
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art.appearance.set_stroke(pattern.clone());
|
||||
let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) };
|
||||
let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0));
|
||||
let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0));
|
||||
assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked));
|
||||
assert_eq!(turned.len(), still.len());
|
||||
for n in &turned {
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
|
||||
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
|
||||
None,
|
||||
}
|
||||
|
||||
impl ArrowStyle {
|
||||
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
|
||||
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
|
||||
match self {
|
||||
Self::Filled => Some(crate::Arrowhead::Triangle),
|
||||
Self::Open => Some(crate::Arrowhead::TriangleOpen),
|
||||
Self::Tick => Some(crate::Arrowhead::Slash),
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the label sits across the dimension line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
|
||||
@@ -339,6 +339,7 @@ impl Document {
|
||||
/// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in
|
||||
/// tree order where `id` appears.
|
||||
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
|
||||
crate::id_index::note_path_lookup();
|
||||
// The cached path, while the node there still has the id ([`id_index`]).
|
||||
let cached = self.index.get();
|
||||
match cached.as_ref().and_then(|m| m.get(&id)) {
|
||||
@@ -423,6 +424,44 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
|
||||
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
|
||||
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
|
||||
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
|
||||
/// them. As for every cached lookup, a second node given an existing id after the cache was
|
||||
/// built is not found while the first one's cached path checks out (see [`id_index`]).
|
||||
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
|
||||
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
|
||||
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
|
||||
// of the document.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
let mut paths = Vec::with_capacity(want.len());
|
||||
let cached = want.iter().all(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
paths.push(p);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if cached {
|
||||
// A node's path sorts after the paths of the nodes before it in tree order, its
|
||||
// ancestors included.
|
||||
paths.sort_unstable();
|
||||
return paths.iter().filter_map(|p| self.node_at(p)).collect();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
self.walk(|n| {
|
||||
if want.contains(&n.id) {
|
||||
out.push(n);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node at index path `path` (as [`Document::index_path`] gives it).
|
||||
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
|
||||
+25
-6
@@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
|
||||
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
|
||||
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
|
||||
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
|
||||
/// touched where the live geometry effects of a clipping path in their art show it, or where the
|
||||
/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except
|
||||
/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
@@ -2265,8 +2267,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
/// compound paths, layers and groups are touched by their box, and an image or a symbol
|
||||
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping
|
||||
/// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region
|
||||
/// ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
// 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`]).
|
||||
@@ -2296,12 +2300,27 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
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)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art. In the art of another instance
|
||||
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
// effects of a clipping path in its art show the art, or where the geometry effects of
|
||||
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
|
||||
// instance walked outside that instance's box, it is touched only by its own art
|
||||
// ([`ArtOnly`]) and those shapes.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r))
|
||||
}
|
||||
// An image is touched by its box, and outside it where its own fills and strokes paint.
|
||||
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
/// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol
|
||||
/// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is
|
||||
/// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when
|
||||
/// `r` meets the reach of `n` ([`Node::reach_bounds_with`]).
|
||||
fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
n.reach_bounds_with(s).is_some_and(meets)
|
||||
&& image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r))
|
||||
}
|
||||
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
|
||||
/// a symbol that draws a straight line) is touched where the marquee crosses it.
|
||||
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
|
||||
@@ -82,6 +82,16 @@ impl Paths {
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.ids.len()
|
||||
}
|
||||
/// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None`
|
||||
/// when it isn't in the table.
|
||||
pub(crate) fn entry(&self, id: &NodeId) -> Option<Option<u32>> {
|
||||
self.ids.get(id).copied()
|
||||
}
|
||||
/// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its
|
||||
/// siblings.
|
||||
pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> {
|
||||
self.at.get(e as usize).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
|
||||
@@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() {
|
||||
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`path_lookups`] of this thread.
|
||||
static PATH_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that
|
||||
/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included.
|
||||
pub fn path_lookups() -> u64 {
|
||||
PATH_LOOKUPS.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_lookups`].
|
||||
pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
|
||||
#[derive(Default)]
|
||||
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
|
||||
|
||||
@@ -21,7 +21,7 @@ pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub use id_index::tree_walks;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
@@ -48,6 +48,8 @@ pub mod marks;
|
||||
mod mem;
|
||||
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
|
||||
pub mod metadata;
|
||||
mod nearest;
|
||||
pub use nearest::NearestFinder;
|
||||
pub mod node;
|
||||
pub mod objects_on_path;
|
||||
pub mod orient;
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The nearest node of a kind at or above each of many objects, found along one index path per
|
||||
//! object.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::id_index::Paths;
|
||||
use crate::{Document, Node, NodeId};
|
||||
|
||||
/// Finds, for one object after another, the nearest node that passes a test: the object itself,
|
||||
/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`].
|
||||
///
|
||||
/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that
|
||||
/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache
|
||||
/// places the object and each id on its path where they are, a lookup reads that one path; an id
|
||||
/// the cache does not place there (one that appears more than once, or a cache older than the
|
||||
/// tree) is looked up with [`Document::node`].
|
||||
pub struct NearestFinder<'a> {
|
||||
doc: &'a Document,
|
||||
cache: Option<Arc<Paths>>,
|
||||
/// The cache entries from the top-level layer down to the object.
|
||||
entries: Vec<u32>,
|
||||
/// The nodes at those entries.
|
||||
nodes: Vec<&'a Node>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// A [`NearestFinder`] for this document.
|
||||
pub fn nearest_finder(&self) -> NearestFinder<'_> {
|
||||
NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> NearestFinder<'a> {
|
||||
/// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred`
|
||||
/// holds; `None` when `id` is not in the tree or no node on its path passes.
|
||||
pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> {
|
||||
let doc = self.doc;
|
||||
let ids: Vec<NodeId> = if self.cached_path(id) {
|
||||
let cache = self.cache.as_deref()?;
|
||||
// The depth of the first id from the object up that the cache does not place there.
|
||||
let mut unplaced = None;
|
||||
for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() {
|
||||
if cache.entry(&node.id) != Some(Some(e)) {
|
||||
unplaced = Some(k);
|
||||
break;
|
||||
}
|
||||
if pred(node) {
|
||||
return Some(node);
|
||||
}
|
||||
}
|
||||
let k = unplaced?;
|
||||
self.nodes[..=k].iter().map(|n| n.id).collect()
|
||||
} else {
|
||||
doc.ancestry(id).unwrap_or_default()
|
||||
};
|
||||
let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n)));
|
||||
// Those lookups may have built the cache again.
|
||||
self.cache = doc.index.get();
|
||||
found
|
||||
}
|
||||
|
||||
/// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for
|
||||
/// it or the path no longer leads to it.
|
||||
fn cached_path(&mut self, id: NodeId) -> bool {
|
||||
self.entries.clear();
|
||||
self.nodes.clear();
|
||||
let Some(cache) = self.cache.as_deref() else { return false };
|
||||
let Some(Some(mut e)) = cache.entry(&id) else { return false };
|
||||
loop {
|
||||
let Some((parent, _)) = cache.place(e) else { return false };
|
||||
self.entries.push(e);
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
// A parent's entry is made before its children's, so the walk up ends.
|
||||
if parent >= e {
|
||||
return false;
|
||||
}
|
||||
e = parent;
|
||||
}
|
||||
self.entries.reverse();
|
||||
let mut siblings: &'a [Arc<Node>] = &self.doc.layers;
|
||||
for &e in &self.entries {
|
||||
let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false };
|
||||
self.nodes.push(&**n);
|
||||
siblings = n.children().map_or(&[], |c| c.as_slice());
|
||||
}
|
||||
self.nodes.last().is_some_and(|n| n.id == id)
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
|
||||
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
|
||||
}
|
||||
|
||||
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
|
||||
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
|
||||
/// as in an exported file. `None` for a language not in the list.
|
||||
pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
|
||||
}
|
||||
|
||||
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
|
||||
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
|
||||
/// first entry); `Err` for a language not in the list.
|
||||
@@ -404,6 +411,16 @@ impl DocSetup {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A document's language is written by its tag, the default's included (#3644).
|
||||
#[test]
|
||||
fn document_languages_have_their_tags() {
|
||||
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
|
||||
assert_eq!(language_tag("French"), Some("fr"));
|
||||
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
|
||||
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
|
||||
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
|
||||
}
|
||||
|
||||
/// Characters store a language of the list by its tag, the default as none.
|
||||
#[test]
|
||||
fn char_languages_are_stored_by_tag() {
|
||||
|
||||
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, by walking the tree.
|
||||
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
out.push(n as *const Node);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
|
||||
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
|
||||
/// walk).
|
||||
#[test]
|
||||
fn nodes_in_order_match_a_walk() {
|
||||
for seed in 1..40 {
|
||||
let (d, ids) = tree(seed);
|
||||
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
d.drop_lookup_cache();
|
||||
} else {
|
||||
d.node(ids[0]);
|
||||
}
|
||||
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
|
||||
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
|
||||
}
|
||||
}
|
||||
// An id that the tree repeats: every node with it.
|
||||
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
|
||||
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
|
||||
// A second node given an id once held once, after the cache was built: the lookup finds the
|
||||
// cached node, which has that id; with the cache built afresh, both.
|
||||
let mut d = d;
|
||||
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
|
||||
let Some(once) = once else { continue };
|
||||
d.node(once);
|
||||
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, copy);
|
||||
}
|
||||
let found = d.nodes_in_order([once]);
|
||||
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
|
||||
d.drop_lookup_cache();
|
||||
d.node(once);
|
||||
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
|
||||
/// node it is in, appears in the tree once.
|
||||
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
|
||||
@@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() {
|
||||
assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was");
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node`
|
||||
/// for each id finds it.
|
||||
fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> {
|
||||
d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node)
|
||||
}
|
||||
|
||||
/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone
|
||||
/// each, so both start from the same cache.
|
||||
fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) {
|
||||
type Pred = fn(&Node) -> bool;
|
||||
let preds: [(&str, Pred); 5] = [
|
||||
("group", |n| matches!(n.kind, NodeKind::Group { .. })),
|
||||
("layer", |n| n.is_layer()),
|
||||
("any", |_| true),
|
||||
("none", |_| false),
|
||||
("id divisible by 3", |n| n.id.0 % 3 == 0),
|
||||
];
|
||||
for (name, pred) in preds {
|
||||
let (a, b) = (d.clone(), d.clone());
|
||||
let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect();
|
||||
let mut find = b.nearest_finder();
|
||||
let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect();
|
||||
assert_eq!(got, want, "{what}: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_finder_matches_the_ancestry_walk() {
|
||||
for seed in 1..30 {
|
||||
let (mut d, ids) = tree(seed);
|
||||
nearest_agrees(&d, &ids, "no cache");
|
||||
d.node(ids[0]);
|
||||
nearest_agrees(&d, &ids, "cached");
|
||||
// Every path in the first layer shifts: the cache is stale there.
|
||||
let extra = d.alloc_id();
|
||||
let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, leaf);
|
||||
}
|
||||
nearest_agrees(&d, &ids, "a stale cache");
|
||||
// A group with the id of a node in the last layer, earlier in tree order than it, put in
|
||||
// after the cache was built.
|
||||
d.drop_lookup_cache();
|
||||
d.node(ids[0]);
|
||||
let last = d.layers.len() - 1;
|
||||
let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id);
|
||||
if let Some(dup) = dup
|
||||
&& let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut()
|
||||
{
|
||||
ch.insert(0, Arc::new(Node::group(dup, vec![])));
|
||||
}
|
||||
nearest_agrees(&d, &ids, "a duplicate put in after the cache was built");
|
||||
d.drop_lookup_cache();
|
||||
nearest_agrees(&d, &ids, "a duplicate, cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// An id on the path that an earlier node of another kind also has: the earlier node is the one
|
||||
/// tested, as `node` gives it.
|
||||
#[test]
|
||||
fn nearest_finder_tests_the_first_node_with_a_repeated_id() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()));
|
||||
d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap();
|
||||
d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
|
||||
// A group that has the path's id, after the path in tree order.
|
||||
d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap();
|
||||
let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. });
|
||||
for cached in [false, true] {
|
||||
d.drop_lookup_cache();
|
||||
if cached {
|
||||
d.node(layer);
|
||||
}
|
||||
let mut find = d.nearest_finder();
|
||||
assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}");
|
||||
assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path");
|
||||
assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the cache built, finding the nearest group of every object of a large tree looks no id up
|
||||
/// and walks the tree no time.
|
||||
#[test]
|
||||
fn nearest_finder_reads_one_path_per_object() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut leaves = vec![];
|
||||
for g in 0..2_000 {
|
||||
let kids: Vec<Arc<Node>> = (0..3)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
leaves.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
d.insert(Some(layer), g, Node::group(gid, kids)).unwrap();
|
||||
}
|
||||
d.drop_lookup_cache();
|
||||
d.node(layer);
|
||||
let (lookups, walks) = (path_lookups(), tree_walks());
|
||||
let mut find = d.nearest_finder();
|
||||
let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count();
|
||||
assert_eq!(found, leaves.len());
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
@@ -189,7 +189,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -103,8 +103,8 @@ pub use solids::{
|
||||
validate_three_d_params, view_options, with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
|
||||
graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
|
||||
graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
|
||||
@@ -6,7 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
use crate::solids::{
|
||||
@@ -168,7 +168,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
// With no member to carry them, the graphics' art must still fit its limits.
|
||||
None => {
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,10 +201,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op
|
||||
let graphics = crate::solids::mapped_graphics(p);
|
||||
let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) };
|
||||
crate::solids::graphics::validate_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p)?;
|
||||
crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?;
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options)?;
|
||||
let mut used = *copies;
|
||||
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) {
|
||||
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) {
|
||||
Some(_) => {
|
||||
*copies = used;
|
||||
Ok(())
|
||||
@@ -523,7 +523,7 @@ fn surface(
|
||||
let mut parts = if graphics.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) {
|
||||
match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) {
|
||||
Some(parts) => {
|
||||
copies.graphics = used;
|
||||
parts
|
||||
|
||||
@@ -520,7 +520,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() {
|
||||
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap();
|
||||
let parts_of = |symbol: &str, copies: &mut usize| {
|
||||
let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]}));
|
||||
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len())
|
||||
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies)
|
||||
.map(|p| p.concat().len())
|
||||
};
|
||||
// Each opaque part copies the paint into its fill and its seam stroke; a part with
|
||||
// transparent stops takes no seam stroke and copies it once.
|
||||
|
||||
+181
-17
@@ -30,7 +30,7 @@ pub use graphics::{
|
||||
};
|
||||
pub use graphics::{
|
||||
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
|
||||
rename_appearance_graphic_symbol,
|
||||
fitting as graphic_fitting_scale, rename_appearance_graphic_symbol,
|
||||
};
|
||||
|
||||
pub(crate) mod shadow;
|
||||
@@ -84,11 +84,14 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
|
||||
}
|
||||
}
|
||||
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
|
||||
// on the back cap are dropped.
|
||||
// on the back cap and on Extrude & Bevel's side are dropped.
|
||||
if (to == ROTATE || to == crate::REVOLVE)
|
||||
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
|
||||
{
|
||||
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
|
||||
list.retain(|g| {
|
||||
let face = g.get("face").and_then(Value::as_str);
|
||||
face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id())
|
||||
});
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
@@ -177,6 +180,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
|
||||
both_sides: flag(p, "bevelBothSides", false),
|
||||
}),
|
||||
hidden: false,
|
||||
map_surface: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,6 +257,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest
|
||||
/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics.
|
||||
fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result<Vec<Facet>, String> {
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p))
|
||||
}
|
||||
|
||||
/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build
|
||||
/// ([`facets_and_faces`]).
|
||||
fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result<CastingSolid, String> {
|
||||
if !cast {
|
||||
return side_facets(path, rule, bounds, p).map(|f| (f, None));
|
||||
}
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let options = Extrude { map_surface: true, ..extrude_options(p) };
|
||||
vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces)))
|
||||
}
|
||||
|
||||
/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side,
|
||||
/// with parameters `p` and built about `bounds`: the first of those with the longest outline
|
||||
/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel
|
||||
/// or has no graphic on its side, or when no part has a side.
|
||||
fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option<usize> {
|
||||
if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) {
|
||||
return None;
|
||||
}
|
||||
let options = extrude_options(p);
|
||||
parts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w)))
|
||||
.fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) })
|
||||
.map(|(k, _)| k)
|
||||
}
|
||||
|
||||
/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of
|
||||
/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0
|
||||
/// that does not reach its cut and as tall as the length across its bevels and walls.
|
||||
fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> {
|
||||
let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?);
|
||||
let options = extrude_options(p);
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options))
|
||||
.fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) })
|
||||
.map(|(_, height, span)| (span, height))
|
||||
}
|
||||
|
||||
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
|
||||
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
|
||||
/// classic effects cast no shadow: they keep no faces.
|
||||
@@ -339,7 +393,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
return check_solids(id, p, &shapes);
|
||||
check_solids(id, p, &shapes)?;
|
||||
return check_side_graphics(doc, n, id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -356,7 +411,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = path.bounds().ok_or_else(anchors)?;
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)
|
||||
check_solids(id, p, &shapes)?;
|
||||
check_side_graphics(doc, n, id, p, &shapes)
|
||||
}
|
||||
|
||||
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
|
||||
@@ -370,6 +426,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
paint_of(item, member).1 > 0.0
|
||||
}
|
||||
|
||||
/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the
|
||||
/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them
|
||||
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
|
||||
/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are
|
||||
/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts
|
||||
/// included. Without `doc` nothing is drawn, and nothing is checked.
|
||||
fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(doc) = doc else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
if side_carrier(id, p, &parts, bounds).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?;
|
||||
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
|
||||
let mut dropped = false;
|
||||
// Art that can't be built draws the source path, without the side's graphics.
|
||||
let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped);
|
||||
if dropped || built.is_none() {
|
||||
return Err("The graphics are too complex: simplify the symbols' art".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
|
||||
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
|
||||
@@ -414,7 +494,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
@@ -688,6 +768,30 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
group
|
||||
}
|
||||
|
||||
/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by
|
||||
/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]):
|
||||
/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it
|
||||
/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group.
|
||||
fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
|
||||
if parts.iter().all(Vec::is_empty) {
|
||||
return surface;
|
||||
}
|
||||
let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface };
|
||||
if children.len() != parts.len() {
|
||||
return surface;
|
||||
}
|
||||
for (child, extra) in children.iter_mut().zip(parts) {
|
||||
if extra.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut list = Vec::with_capacity(extra.len() + 1);
|
||||
list.push(child.clone());
|
||||
list.extend(extra);
|
||||
*child = Arc::new(Node::group(id, list));
|
||||
}
|
||||
surface
|
||||
}
|
||||
|
||||
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
|
||||
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
|
||||
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
|
||||
@@ -802,7 +906,7 @@ fn built_solids<'a>(
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
|
||||
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
|
||||
built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
|
||||
}
|
||||
|
||||
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
|
||||
@@ -813,7 +917,9 @@ type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
|
||||
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
|
||||
|
||||
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
|
||||
/// is cast from, from the same build ([`SolidFaces`]).
|
||||
/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one,
|
||||
/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics
|
||||
/// on Extrude & Bevel's side ([`side_carrier`]).
|
||||
fn built_solids_cast<'a>(
|
||||
id: &'a str,
|
||||
p: &'a Value,
|
||||
@@ -821,6 +927,7 @@ fn built_solids_cast<'a>(
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
cast: bool,
|
||||
side: Option<usize>,
|
||||
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
|
||||
// Inflate's eye is placed for every puff together, as far away as the highest needs.
|
||||
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
|
||||
@@ -834,7 +941,7 @@ fn built_solids_cast<'a>(
|
||||
});
|
||||
let mut kept = 0usize;
|
||||
let mut ended = false;
|
||||
parts.iter().map_while(move |(item, _, area, rule, _, _)| {
|
||||
parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| {
|
||||
if ended {
|
||||
return None;
|
||||
}
|
||||
@@ -846,6 +953,7 @@ fn built_solids_cast<'a>(
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
each.next().unwrap_or_else(|| Ok((vec![], None)))
|
||||
}
|
||||
None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast),
|
||||
None => facets_and_faces(id, area, *rule, bounds, p, cast),
|
||||
};
|
||||
let result = match built {
|
||||
@@ -1098,6 +1206,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op
|
||||
f.depth = s.depth_at(mid).unwrap_or(s.depth);
|
||||
f.contours = vec![points];
|
||||
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
|
||||
// A piece keeps where the whole face lies on the side: the parts of the side's graphics
|
||||
// drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]).
|
||||
Some(f)
|
||||
};
|
||||
Some((piece(1.0)?, piece(-1.0)?))
|
||||
@@ -1776,6 +1886,12 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
|
||||
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
|
||||
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
|
||||
surfaces_with(doc, n, fx, shapes, cast, &mut false)
|
||||
}
|
||||
|
||||
/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past
|
||||
/// their limits on the pieces drawn, and the solid that takes them draws without them.
|
||||
fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option<SurfacesAndFaces> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
|
||||
@@ -1818,9 +1934,13 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
// The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest
|
||||
// outline, whose pieces are built carrying where they lie on it.
|
||||
let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None };
|
||||
let mut solids = vec![];
|
||||
let mut built = vec![];
|
||||
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
|
||||
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier);
|
||||
for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() {
|
||||
let item: &AppearanceItem = item;
|
||||
match f {
|
||||
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
@@ -1830,8 +1950,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
solids.push((item, *opacity, *scopes, f, *member));
|
||||
built.push(faces);
|
||||
}
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws.
|
||||
Ok(None) => built.push(None),
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws, and
|
||||
// the side's graphics on that outline are not drawn.
|
||||
Ok(None) => {
|
||||
built.push(None);
|
||||
*side_dropped |= carrier == Some(k);
|
||||
}
|
||||
// A loaded file or a shape edited past the limits (its own, or those of the object's
|
||||
// solids together) keeps drawing its source path instead of failing the frame;
|
||||
// commands validate the same evaluator and report its errors.
|
||||
@@ -1915,6 +2039,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
// ([`in_one_order`], [`underlaid_surface`]).
|
||||
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
|
||||
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
|
||||
let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default();
|
||||
// The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve.
|
||||
let mut graphic_copies = 0usize;
|
||||
let surfaces: Vec<BuiltSurface> = solids
|
||||
.into_iter()
|
||||
.map(|(item, member, scopes, f, shape)| {
|
||||
@@ -1922,10 +2049,22 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
|
||||
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
// The carrier's pieces draw the parts of the side's graphics that fall on them; past
|
||||
// the graphics' limits the solid draws without them.
|
||||
let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) {
|
||||
vec![]
|
||||
} else {
|
||||
let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination));
|
||||
let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies);
|
||||
*side_dropped |= parts.is_none();
|
||||
parts.unwrap_or_default()
|
||||
};
|
||||
let drawn = parts.iter().any(|p| !p.is_empty());
|
||||
let art = if classic {
|
||||
classic::surface(n, f, &paint, opacity, blend, &p)
|
||||
} else {
|
||||
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
|
||||
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
|
||||
with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
|
||||
};
|
||||
(depths, art, scopes, ends)
|
||||
})
|
||||
@@ -2239,8 +2378,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> b
|
||||
/// Finds a 3D effect in a list of effects, with its index there.
|
||||
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
|
||||
|
||||
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
|
||||
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
|
||||
/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the
|
||||
/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it
|
||||
/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that
|
||||
/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a
|
||||
/// depth, or its art can't be built.
|
||||
pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<(f64, f64)> {
|
||||
let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?;
|
||||
side_size(&crate::merged_params(&fx.id, &fx.params), &shapes)
|
||||
}
|
||||
|
||||
/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from.
|
||||
fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<(Effect, Vec<Profile>)> {
|
||||
let n = &*resolve(doc, n, "").ok()?;
|
||||
let (fx, shapes) = if is_container(n) {
|
||||
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
|
||||
@@ -2264,6 +2413,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((fx.clone(), shapes))
|
||||
}
|
||||
|
||||
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
|
||||
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
|
||||
let (fx, shapes) = frame_shapes(doc, n, item, pick)?;
|
||||
if !takes_graphics(&fx.id) {
|
||||
return None;
|
||||
}
|
||||
@@ -2289,10 +2444,19 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
|
||||
let plane = vectorcraft_three_d::plane_face_map(b, view);
|
||||
return Some(graphics::GraphicFrame::new(b, plane, None));
|
||||
}
|
||||
let (_, bounds) = solid_parts(&shapes, b);
|
||||
let (parts, bounds) = solid_parts(&shapes, b);
|
||||
let options = extrude_options(&p);
|
||||
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
|
||||
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
|
||||
let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back));
|
||||
// With graphics on the side, the part of it the viewer sees places their handles.
|
||||
let side = side_carrier(&fx.id, &p, &parts, bounds)
|
||||
.and_then(|k| parts.get(k))
|
||||
.and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok())
|
||||
.map(|facets| graphics::SideFrame::of(&facets));
|
||||
Some(match side {
|
||||
Some(side) => frame.with_side(side),
|
||||
None => frame,
|
||||
})
|
||||
}
|
||||
|
||||
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
|
||||
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
|
||||
//! plane, turned, foreshortened and shaded with that face and clipped to it.
|
||||
//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials ›
|
||||
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its
|
||||
//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it.
|
||||
//!
|
||||
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
|
||||
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
|
||||
@@ -12,7 +12,10 @@
|
||||
//! On Revolve the graphics lie on the swept side surface, unrolled flat
|
||||
//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the
|
||||
//! middle of that surface, x around the axis and y along the profile, and each face of the side
|
||||
//! draws the part of the graphics that falls on it ([`surface_parts`]).
|
||||
//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude &
|
||||
//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the
|
||||
//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with
|
||||
//! the longest outline.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -110,7 +113,7 @@ impl MappedGraphic {
|
||||
};
|
||||
let face = match m.get("face") {
|
||||
None => PlanarFace::Front,
|
||||
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
|
||||
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?,
|
||||
};
|
||||
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
|
||||
match m.get(key) {
|
||||
@@ -139,7 +142,7 @@ impl MappedGraphic {
|
||||
* Affine::scale(self.scale / 100.0)
|
||||
* Affine::translate(-art.center().to_vec2());
|
||||
match self.face {
|
||||
PlanarFace::Front => place,
|
||||
PlanarFace::Front | PlanarFace::Side => place,
|
||||
// Seen from behind, the back's right is the front's left.
|
||||
PlanarFace::Back => {
|
||||
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
|
||||
@@ -148,8 +151,8 @@ impl MappedGraphic {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve
|
||||
/// (its swept side).
|
||||
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane)
|
||||
/// and Revolve (its swept side).
|
||||
pub fn takes_graphics(id: &str) -> bool {
|
||||
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
|
||||
}
|
||||
@@ -165,7 +168,7 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
|
||||
|
||||
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
|
||||
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
|
||||
/// the front.
|
||||
/// the front. Only Extrude & Bevel takes graphics on its side.
|
||||
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
let list = match p.get(GRAPHICS) {
|
||||
None => return Ok(()),
|
||||
@@ -183,10 +186,10 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
|
||||
}
|
||||
for v in list {
|
||||
let g = MappedGraphic::from_value(v)?;
|
||||
if id == super::ROTATE && g.face == PlanarFace::Back {
|
||||
if id == super::ROTATE && g.face != PlanarFace::Front {
|
||||
return Err("A plane has one face: map its graphics onto the front".into());
|
||||
}
|
||||
if id == crate::REVOLVE && g.face == PlanarFace::Back {
|
||||
if id == crate::REVOLVE && g.face != PlanarFace::Front {
|
||||
return Err("Revolve maps graphics onto its side: map them onto the front".into());
|
||||
}
|
||||
}
|
||||
@@ -598,14 +601,14 @@ struct Unrolled {
|
||||
place: Affine,
|
||||
}
|
||||
|
||||
/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side
|
||||
/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is
|
||||
/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than
|
||||
/// [`MAX_ELEMENTS`] points together.
|
||||
fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> {
|
||||
/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side)
|
||||
/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does
|
||||
/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces
|
||||
/// take more than [`MAX_ELEMENTS`] points together.
|
||||
fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option<Vec<Unrolled>> {
|
||||
let mut pieces = vec![];
|
||||
let mut points = 0usize;
|
||||
for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) {
|
||||
for g in graphics.iter().filter(|g| g.face == face) {
|
||||
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
|
||||
let Ok(art) = pieces_of(doc, symbol) else { continue };
|
||||
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
|
||||
@@ -682,38 +685,96 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>
|
||||
(*points <= MAX_ELEMENTS).then_some(polygons)
|
||||
}
|
||||
|
||||
/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art,
|
||||
/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together.
|
||||
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> {
|
||||
/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit
|
||||
/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface,
|
||||
/// may take up to [`MAX_ELEMENTS`] points together.
|
||||
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> {
|
||||
let list = mapped_graphics(p);
|
||||
if list.is_empty() || unrolled(doc, &list).is_some() {
|
||||
if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
Err("The graphics are too complex: simplify the symbols' art".into())
|
||||
}
|
||||
|
||||
/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing
|
||||
/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces
|
||||
/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows
|
||||
/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it.
|
||||
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
|
||||
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
|
||||
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
|
||||
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
|
||||
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
|
||||
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
|
||||
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
|
||||
pub(crate) fn surface_parts(
|
||||
/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's
|
||||
/// swept side, or a piece of Extrude & Bevel's walls and bevels.
|
||||
pub(crate) trait SurfaceFace {
|
||||
/// Where the face lies on the side unrolled, when it is a face of the side that shows its
|
||||
/// outside to the viewer.
|
||||
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>;
|
||||
/// The outline the face's parts are cut to, when it is not the polygon of its cell's corners:
|
||||
/// its curved outline, when its edges along an end are curved, or the outline of a piece cut
|
||||
/// from a larger face.
|
||||
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>>;
|
||||
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient>;
|
||||
fn light(&self) -> [f64; 3];
|
||||
fn outline_path(&self) -> PathData;
|
||||
}
|
||||
|
||||
impl SurfaceFace for vectorcraft_three_d::Face {
|
||||
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
|
||||
self.surface.as_ref().filter(|c| c.outward && !self.cap)
|
||||
}
|
||||
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
|
||||
self.outline.as_ref().map(std::borrow::Cow::Borrowed)
|
||||
}
|
||||
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
|
||||
self.rgb_gradient
|
||||
}
|
||||
fn light(&self) -> [f64; 3] {
|
||||
self.illumination
|
||||
}
|
||||
fn outline_path(&self) -> PathData {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl SurfaceFace for Facet {
|
||||
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
|
||||
self.surface.as_ref().filter(|c| c.outward)
|
||||
}
|
||||
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
|
||||
if let Some(outline) = &self.outline {
|
||||
return Some(std::borrow::Cow::Borrowed(outline));
|
||||
}
|
||||
// A piece of a stroke's face cut where it passes through a wall keeps its face's cell.
|
||||
let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page));
|
||||
cut.then(|| std::borrow::Cow::Owned(self.path()))
|
||||
}
|
||||
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
|
||||
self.rgb_gradient
|
||||
}
|
||||
fn light(&self) -> [f64; 3] {
|
||||
self.illumination
|
||||
}
|
||||
fn outline_path(&self) -> PathData {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side)
|
||||
/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id
|
||||
/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their
|
||||
/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past
|
||||
/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color
|
||||
/// on a face, as the surface under it is shaded; the colors of gradients and patterns are
|
||||
/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the
|
||||
/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are
|
||||
/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the
|
||||
/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's
|
||||
/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded
|
||||
/// file draws the surface without them.
|
||||
pub(crate) fn surface_parts<F: SurfaceFace>(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
graphics: &[MappedGraphic],
|
||||
faces: &[vectorcraft_three_d::Face],
|
||||
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
|
||||
(graphics, face): (&[MappedGraphic], PlanarFace),
|
||||
faces: &[F],
|
||||
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
|
||||
copies: &mut usize,
|
||||
) -> Option<Vec<Vec<Arc<Node>>>> {
|
||||
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()];
|
||||
let Some(doc) = doc else { return Some(out) };
|
||||
let pieces = unrolled(doc, graphics)?;
|
||||
let pieces = unrolled(doc, graphics, face)?;
|
||||
let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) };
|
||||
// Each piece listed in the buckets of the surface's x its bounds reach across.
|
||||
let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9);
|
||||
@@ -729,11 +790,12 @@ pub(crate) fn surface_parts(
|
||||
let mut cut_points = 0usize;
|
||||
let mut triangle_id = 0usize;
|
||||
for (face, parts) in faces.iter().zip(out.iter_mut()) {
|
||||
let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue };
|
||||
let Some(cell) = face.outer_cell() else { continue };
|
||||
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
|
||||
continue;
|
||||
}
|
||||
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
|
||||
let curved = face.curved();
|
||||
for corners in triangles {
|
||||
triangle_id += 1;
|
||||
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
|
||||
@@ -744,7 +806,7 @@ pub(crate) fn surface_parts(
|
||||
// where the graphic runs past the end of the profile. A four-cornered face is cut into
|
||||
// two triangles along its diagonal from corner 0 to corner 2: each takes the part of
|
||||
// the outline on its own side of it.
|
||||
let window = if face.outline.is_some() { grown(window, 3.0) } else { window };
|
||||
let window = if curved.is_some() { grown(window, 3.0) } else { window };
|
||||
// The pieces are looked up over the whole of the window they are cut to.
|
||||
let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue };
|
||||
if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 {
|
||||
@@ -771,7 +833,7 @@ pub(crate) fn surface_parts(
|
||||
}
|
||||
near.sort_unstable();
|
||||
let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2);
|
||||
let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
|
||||
let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
|
||||
(Some(&toward), Some(&a), Some(&b)) => {
|
||||
let side = side_of(a, b, toward);
|
||||
vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect)
|
||||
@@ -834,21 +896,21 @@ pub(crate) fn surface_parts(
|
||||
|
||||
/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes
|
||||
/// from the unrolled surface onto `face`.
|
||||
fn surface_piece(
|
||||
fn surface_piece<F: SurfaceFace>(
|
||||
id: NodeId,
|
||||
piece: &Unrolled,
|
||||
(path, rule): (BezPath, FillRule),
|
||||
map: Affine,
|
||||
face: &vectorcraft_three_d::Face,
|
||||
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
|
||||
face: &F,
|
||||
shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint,
|
||||
) -> Node {
|
||||
let gradient_map = map * piece.place;
|
||||
// Under several lights a face's light varies across it in each channel: a solid color draws
|
||||
// as the face's own lit art in that color, clipped to the part. An opaque part also draws that
|
||||
// art clipped to a band of the seam stroke's width around its edges, as the other parts take
|
||||
// a stroke over their seams.
|
||||
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) {
|
||||
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light));
|
||||
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) {
|
||||
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light));
|
||||
let clipped = |area: &BezPath, rule: FillRule| {
|
||||
let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default());
|
||||
if let NodeKind::Path { rule: r, .. } = &mut clip.kind {
|
||||
@@ -881,7 +943,7 @@ fn surface_piece(
|
||||
match solid {
|
||||
Some(c) => f.paint = shade(face, c),
|
||||
None => {
|
||||
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination));
|
||||
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -996,23 +1058,106 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
|
||||
/// offsets are from their center) and the maps of its front and back faces, when it has them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
/// offsets are from their center), the maps of its front and back faces, when it has them, and
|
||||
/// the visible part of its side unrolled, when it has graphics there.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GraphicFrame {
|
||||
pub bounds: Rect,
|
||||
front: Option<FaceMap>,
|
||||
back: Option<FaceMap>,
|
||||
side: Option<SideFrame>,
|
||||
}
|
||||
|
||||
/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are
|
||||
/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the
|
||||
/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger
|
||||
/// is nearer).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SideFrame {
|
||||
pieces: Vec<SidePiece>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct SidePiece {
|
||||
uv: Vec<Point>,
|
||||
page: Vec<Point>,
|
||||
outline: Option<BezPath>,
|
||||
depth: f64,
|
||||
}
|
||||
|
||||
impl SideFrame {
|
||||
/// The pieces of `facets` that carry where they lie on the side unrolled and show its outside.
|
||||
pub(super) fn of(facets: &[Facet]) -> Self {
|
||||
let pieces = facets
|
||||
.iter()
|
||||
.filter_map(|f| {
|
||||
let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?;
|
||||
let outline = f.curved().map(|o| o.to_bezpath());
|
||||
Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth })
|
||||
})
|
||||
.collect();
|
||||
Self { pieces }
|
||||
}
|
||||
|
||||
/// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped
|
||||
/// onto the side unrolled, through the nearest piece whose drawn part holds it: within the
|
||||
/// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and
|
||||
/// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it.
|
||||
fn map(&self, p: Point, from_page: bool) -> Option<Point> {
|
||||
let inside = |t: &[Point; 3], q: Point| {
|
||||
let side = |a: Point, b: Point| (b - a).cross(q - a);
|
||||
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
|
||||
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
|
||||
};
|
||||
let mut best: Option<(Point, f64)> = None;
|
||||
for piece in &self.pieces {
|
||||
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
|
||||
let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
|
||||
for corners in triangles {
|
||||
let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]);
|
||||
let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue };
|
||||
let window = if piece.outline.is_some() { grown(a, 3.0) } else { a };
|
||||
if !inside(&window, p) {
|
||||
continue;
|
||||
}
|
||||
// A four-cornered piece's two triangles meet along its diagonal: each holds its side.
|
||||
if triangles.len() == 2
|
||||
&& let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 }))
|
||||
{
|
||||
let across = |q: Point| (d2 - d0).cross(q - d0);
|
||||
if across(p) * across(own) < 0.0 {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue };
|
||||
let on_page = if from_page { p } else { q };
|
||||
if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) {
|
||||
continue;
|
||||
}
|
||||
if best.is_none_or(|(_, depth)| piece.depth > depth) {
|
||||
best = Some((q, piece.depth));
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(q, _)| q)
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphicFrame {
|
||||
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
|
||||
Self { bounds, front, back }
|
||||
Self { bounds, front, back, side: None }
|
||||
}
|
||||
|
||||
/// The frame with the visible part of the side `side`, for its graphics' handles.
|
||||
pub(super) fn with_side(self, side: SideFrame) -> Self {
|
||||
Self { side: Some(side), ..self }
|
||||
}
|
||||
|
||||
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
|
||||
match face {
|
||||
PlanarFace::Front => self.front.as_ref(),
|
||||
PlanarFace::Back => self.back.as_ref(),
|
||||
PlanarFace::Side => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1023,23 +1168,34 @@ impl GraphicFrame {
|
||||
match face {
|
||||
PlanarFace::Front => Point::new(c.x + x, c.y + y),
|
||||
PlanarFace::Back => Point::new(c.x - x, c.y + y),
|
||||
PlanarFace::Side => Point::new(x, y),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
|
||||
/// viewer. `None` when the object has no such face or the point has no page point.
|
||||
/// viewer. `None` when the object has no such face or the point has no page point. A graphic on
|
||||
/// the side lands where its center is on the part of the side the viewer sees, and is `None`
|
||||
/// elsewhere.
|
||||
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
|
||||
if g.face == PlanarFace::Side {
|
||||
return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true));
|
||||
}
|
||||
let map = self.map(g.face)?;
|
||||
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
|
||||
}
|
||||
|
||||
/// The offset of a graphic on `face` whose center lands on page point `page`.
|
||||
/// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only
|
||||
/// a point on the part of the side the viewer sees has one.
|
||||
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
|
||||
let art = self.map(face)?.to_art(page)?;
|
||||
let art = match face {
|
||||
PlanarFace::Side => self.side.as_ref()?.map(page, true)?,
|
||||
_ => self.map(face)?.to_art(page)?,
|
||||
};
|
||||
let c = self.bounds.center();
|
||||
let (x, y) = match face {
|
||||
PlanarFace::Front => (art.x - c.x, art.y - c.y),
|
||||
PlanarFace::Back => (c.x - art.x, art.y - c.y),
|
||||
PlanarFace::Side => (art.x, art.y),
|
||||
};
|
||||
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
|
||||
}
|
||||
@@ -1047,11 +1203,17 @@ impl GraphicFrame {
|
||||
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
|
||||
/// 100: where a newly mapped graphic starts.
|
||||
pub fn fitting_scale(&self, art: Rect) -> f64 {
|
||||
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
|
||||
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
|
||||
fitting(self.bounds.width(), self.bounds.height(), art)
|
||||
}
|
||||
}
|
||||
|
||||
/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at
|
||||
/// most 100.
|
||||
pub fn fitting(width: f64, height: f64, art: Rect) -> f64 {
|
||||
let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9));
|
||||
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
|
||||
}
|
||||
|
||||
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
|
||||
pub fn graphic_symbols(n: &Node) -> Vec<String> {
|
||||
appearance_graphic_symbols(&n.appearance)
|
||||
@@ -1135,3 +1297,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
|
||||
#[cfg(test)]
|
||||
#[path = "tests_graphics.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_graphics_side.rs"]
|
||||
mod tests_side;
|
||||
@@ -774,6 +774,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
surface: None,
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
|
||||
@@ -531,12 +531,13 @@ fn graphics_are_checked() {
|
||||
let n = object(EXTRUDE, json!({}));
|
||||
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
|
||||
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
|
||||
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok());
|
||||
assert!(check(EXTRUDE, json!([])).is_ok());
|
||||
for bad in [
|
||||
json!("Mark"),
|
||||
json!([{"face": "front"}]),
|
||||
json!([{"symbol": ""}]),
|
||||
json!([{"symbol": "Mark", "face": "side"}]),
|
||||
json!([{"symbol": "Mark", "face": "top"}]),
|
||||
json!([{"symbol": "Mark", "scale": 0.0}]),
|
||||
json!([{"symbol": "Mark", "rotation": 400.0}]),
|
||||
json!([{"symbol": "Mark", "x": "1"}]),
|
||||
@@ -546,10 +547,12 @@ fn graphics_are_checked() {
|
||||
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
|
||||
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
|
||||
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
|
||||
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
|
||||
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err());
|
||||
assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
|
||||
// A loaded file's invalid entries are left out when drawn.
|
||||
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
|
||||
@@ -569,10 +572,13 @@ fn the_frame_at_an_index_is_that_effects() {
|
||||
|
||||
#[test]
|
||||
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
|
||||
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
|
||||
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]});
|
||||
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
|
||||
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
|
||||
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
|
||||
// Revolve drops the side's graphics too; Extrude & Bevel keeps every face's.
|
||||
assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
|
||||
assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]);
|
||||
// Back to Extrude & Bevel, the front's graphic stays.
|
||||
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::color::Color;
|
||||
use vectorcraft_doc::{StrokeLayer, Symbol};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in};
|
||||
use super::*;
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
fn square(id: u64, r: Rect, paint: Paint) -> Node {
|
||||
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
|
||||
}
|
||||
|
||||
/// A document with symbol "Mark": a red 10 × 10 square.
|
||||
fn document() -> Document {
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
d.symbols.push(Symbol {
|
||||
dynamic: false,
|
||||
name: "Mark".into(),
|
||||
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
|
||||
});
|
||||
d
|
||||
}
|
||||
|
||||
/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the
|
||||
/// viewer, its front edge at the bottom of the page), with `params` over that.
|
||||
fn object(params: Value) -> Node {
|
||||
let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
|
||||
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
n
|
||||
}
|
||||
|
||||
fn is_red(p: &Paint) -> bool {
|
||||
p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
|
||||
}
|
||||
|
||||
/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline.
|
||||
fn faces_with_parts(art: &Node) -> Vec<Vec<PathData>> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::Group { children, clip: false } = &n.kind
|
||||
&& let Some((face, parts)) = children.split_first()
|
||||
&& matches!(face.kind, NodeKind::Path { .. })
|
||||
&& !parts.is_empty()
|
||||
{
|
||||
let red: Vec<PathData> = parts
|
||||
.iter()
|
||||
.filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint))))
|
||||
.filter_map(|p| p.path_data().cloned())
|
||||
.collect();
|
||||
if red.len() == parts.len() {
|
||||
out.push(red);
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn bounds(parts: &[Vec<PathData>]) -> Rect {
|
||||
parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the
|
||||
/// middle of the side toward the back.
|
||||
#[test]
|
||||
fn a_side_graphic_lies_on_the_wall_at_its_offset() {
|
||||
let d = document();
|
||||
let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let found = faces_with_parts(&art);
|
||||
assert_eq!(found.len(), 1, "drawn once, on the top wall");
|
||||
// Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25).
|
||||
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
|
||||
let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]}));
|
||||
let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap());
|
||||
assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found));
|
||||
// Without the document nothing is drawn; a graphic on the side leaves the caps without one.
|
||||
assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
/// A graphic that reaches past a corner runs on around it onto the next wall.
|
||||
#[test]
|
||||
fn a_side_graphic_runs_around_a_corner() {
|
||||
let d = document();
|
||||
// x = 50 is the top's right end.
|
||||
let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
|
||||
let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap());
|
||||
assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found));
|
||||
// Turned to show the top and the right, both walls draw their part.
|
||||
let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]}));
|
||||
assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2);
|
||||
// Twist and taper carry the graphic; it stays on the side.
|
||||
let twisted =
|
||||
object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]}));
|
||||
let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap());
|
||||
assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))));
|
||||
}
|
||||
|
||||
/// The handle lands where the graphic's center is on the visible side, and a page point there
|
||||
/// gives back its offset; a graphic on a hidden wall has no handle.
|
||||
#[test]
|
||||
fn the_sides_handle_moves_the_graphic_on_its_visible_part() {
|
||||
let d = document();
|
||||
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap();
|
||||
let n = object(json!({"graphics": [g.to_value()]}));
|
||||
let frame = graphic_frame(Some(&d), &n, None).unwrap();
|
||||
let (at, visible) = frame.handle(&g).unwrap();
|
||||
assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}");
|
||||
let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap();
|
||||
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
|
||||
// The bottom's middle, half way around, is hidden from above; so is a page point off the top.
|
||||
let hidden = MappedGraphic { x: 200.0, ..g.clone() };
|
||||
assert!(frame.handle(&hidden).is_none());
|
||||
assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none());
|
||||
// Without a graphic on the side, the frame places no handle there.
|
||||
let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap();
|
||||
assert!(caps.handle(&g).is_none());
|
||||
}
|
||||
|
||||
/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's
|
||||
/// center and a page point there gives back its offset.
|
||||
#[test]
|
||||
fn the_handle_follows_a_curved_side() {
|
||||
let d = document();
|
||||
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap();
|
||||
let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]}));
|
||||
if let NodeKind::Path { path, .. } = &mut n.kind {
|
||||
*path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
}
|
||||
let frame = graphic_frame(Some(&d), &n, None).unwrap();
|
||||
let (at, visible) = frame.handle(&g).unwrap();
|
||||
assert!(visible);
|
||||
let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap();
|
||||
assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}");
|
||||
}
|
||||
|
||||
/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is
|
||||
/// the longest, takes them once.
|
||||
#[test]
|
||||
fn a_hollow_or_stroked_object_takes_a_side_graphic() {
|
||||
let d = document();
|
||||
let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]}));
|
||||
let art = solid_art_in(Some(&d), &hollow).unwrap();
|
||||
assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0)));
|
||||
let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]}));
|
||||
stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0)));
|
||||
let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap());
|
||||
assert_eq!(found.len(), 1, "on the stroke's outer wall only");
|
||||
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
|
||||
// The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the
|
||||
// top's middle: a new graphic fits the 330 pt about x = 0 and the depth.
|
||||
assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0)));
|
||||
}
|
||||
|
||||
/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and
|
||||
/// each piece draws only the part of the graphic within its own outline.
|
||||
#[test]
|
||||
fn a_piece_cut_from_a_face_draws_its_own_part() {
|
||||
let d = document();
|
||||
let facet = |x: f64, normal: [f64; 3], offset: f64| {
|
||||
let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect();
|
||||
Facet {
|
||||
contours: vec![square.clone()],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal,
|
||||
rgb_gradient: None,
|
||||
outline: None,
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
|
||||
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
}
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
|
||||
let r = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)];
|
||||
super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0);
|
||||
assert_eq!(stroke.len(), 2, "cut where it passes through the wall");
|
||||
// The graphic covers the whole face, x 5 to 15 on the page.
|
||||
let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]}));
|
||||
let shade = |_: &Facet, c: Color| Paint::solid(c);
|
||||
let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap();
|
||||
let drawn: Vec<Rect> =
|
||||
parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect();
|
||||
// Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic.
|
||||
let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1));
|
||||
assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}");
|
||||
assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the
|
||||
/// limit of points, though its own path elements are few; on a cap it is accepted.
|
||||
#[test]
|
||||
fn a_side_graphic_past_its_limits_is_refused() {
|
||||
let mut d = document();
|
||||
// 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut.
|
||||
let mut subpaths = vec![];
|
||||
for k in 0..200 {
|
||||
let x = f64::from(k);
|
||||
subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths);
|
||||
}
|
||||
let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) });
|
||||
let n = object(json!({}));
|
||||
let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]});
|
||||
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err());
|
||||
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok());
|
||||
assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok());
|
||||
}
|
||||
|
||||
/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces
|
||||
/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object
|
||||
/// casts without a graphic.
|
||||
#[test]
|
||||
fn a_side_graphic_keeps_its_place_with_the_shadow_on() {
|
||||
let d = document();
|
||||
let shadow = |art: &Node| {
|
||||
let first = &art.children().unwrap()[0];
|
||||
let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") };
|
||||
assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}");
|
||||
first.path_data().and_then(PathData::bounds).unwrap()
|
||||
};
|
||||
let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0});
|
||||
let mut with_graphic = lit.clone();
|
||||
with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]);
|
||||
let n = object(with_graphic);
|
||||
super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0));
|
||||
super::super::SOLIDS_BUILT.with(|b| b.set(0));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get));
|
||||
assert_eq!(builds, (1, 1), "one build for the faces and the shadow");
|
||||
let found = faces_with_parts(&art);
|
||||
assert_eq!(found.len(), 1, "drawn once, on the top wall");
|
||||
assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found));
|
||||
let without = solid_art_in(Some(&d), &object(lit)).unwrap();
|
||||
assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without));
|
||||
}
|
||||
@@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() {
|
||||
let p = crate::merged_params(id, &json!({"shadow": true}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut built: Vec<Option<SolidFaces>> =
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
|
||||
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
|
||||
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
|
||||
|
||||
@@ -407,7 +407,18 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
/// The command `id`: a built-in one, or a command an installed plug-in adds
|
||||
/// ([`plugin::command_specs`]).
|
||||
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
|
||||
static INDEX: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static CommandSpec>> = std::sync::OnceLock::new();
|
||||
INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id))
|
||||
}
|
||||
|
||||
/// `specs` by id. An id that more than one spec has names the first of them, as a search of
|
||||
/// `specs` in order finds.
|
||||
pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> {
|
||||
let mut index = std::collections::HashMap::with_capacity(specs.len());
|
||||
for spec in specs {
|
||||
index.entry(spec.id).or_insert(spec);
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
|
||||
@@ -829,6 +840,8 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
|
||||
//! ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
mod bridge;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
mod effect_tests;
|
||||
@@ -183,6 +185,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(corners::specs());
|
||||
v.extend(shared_edge::specs());
|
||||
v.extend(trim::specs());
|
||||
v.extend(bridge::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both
|
||||
//! circles, replacing the circles or added above them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
|
||||
use super::super::super::pathops::{Beside, remove_each};
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or};
|
||||
use super::given;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The command, and its undo step's name.
|
||||
const C: &str = "addon.pathtools.bridge";
|
||||
const LABEL: &str = "Smooth Bridge";
|
||||
/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range.
|
||||
const RADIUS: f64 = 100.0;
|
||||
const RADII: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.pathtools.bridge",
|
||||
"Smooth Bridge",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{radius?: % 1..1000 (100; the radius of 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}",
|
||||
has_selection,
|
||||
bridge
|
||||
)]
|
||||
}
|
||||
|
||||
fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS);
|
||||
let keep = switch_or(p, "keepOriginals", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let circles: Vec<(NodeId, pt::Circle)> = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
d.paint_order(roots.iter().copied())
|
||||
.into_iter()
|
||||
.filter_map(|id| match &d.node(id)?.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
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"));
|
||||
}
|
||||
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 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;
|
||||
}
|
||||
remove_each(d, &[below])?;
|
||||
above
|
||||
};
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius,
|
||||
//! and what it refuses.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const BRIDGE: &str = "addon.pathtools.bridge";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A circle about (`x`, `y`) with radius `r`.
|
||||
fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId {
|
||||
let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap();
|
||||
NodeId(id)
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn top_level(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
fn area(s: &Session, id: NodeId) -> f64 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, p: Value) -> String {
|
||||
s.execute(BRIDGE, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_circles_become_one_outline_in_the_upper_ones_place() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 160.0, 100.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute(BRIDGE, &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(b.0));
|
||||
assert_eq!(top_level(&s), [b]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") };
|
||||
assert!(live.is_none(), "a plain path now");
|
||||
assert!(path.subpaths.len() == 1 && path.subpaths[0].closed);
|
||||
let bounds = path.bounds().unwrap();
|
||||
assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}");
|
||||
// Both circles and the bridge between them: more than the two circles' area.
|
||||
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(top_level(&s), [a, b]);
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_originals_adds_the_outline_above_the_upper_circle() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 30.0);
|
||||
let b = circle(&mut s, 170.0, 100.0, 10.0);
|
||||
let c = circle(&mut s, 300.0, 250.0, 5.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [a, b, id, c]);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle");
|
||||
assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are");
|
||||
assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }));
|
||||
let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap();
|
||||
assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_outline_gets_its_own_mask_art() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap();
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id);
|
||||
let (kept, copied) = (art(b).unwrap(), art(id).unwrap());
|
||||
assert_ne!(kept, copied, "the outline's mask art has ids of its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_makes_a_wider_bridge() {
|
||||
let area_at = |radius: f64| {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 15.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
area(&s, id)
|
||||
};
|
||||
let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0));
|
||||
assert!(default < wider && wider < widest, "{default} {wider} {widest}");
|
||||
let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0));
|
||||
assert!(narrow < default && default < wide, "{narrow} {default} {wide}");
|
||||
// The default is 100%: the smaller circle's radius.
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 15.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!((area(&s, id) - default).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_touching_circles_are_joined() {
|
||||
for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 140.0 + gap, 100.0, 20.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [id], "gap {gap}");
|
||||
}
|
||||
// Unequal overlapping circles at every radius, the largest included.
|
||||
for radius in [1.0, 100.0, 300.0, 1000.0] {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut s, 125.0, 100.0, 30.0);
|
||||
let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(top_level(&s), [id], "radius {radius}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_apart_nested_and_other_objects_are_refused() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 50.0, 100.0, 10.0);
|
||||
let far = circle(&mut s, 250.0, 100.0, 10.0);
|
||||
let near = circle(&mut s, 110.0, 100.0, 10.0);
|
||||
let inner = circle(&mut s, 52.0, 100.0, 4.0);
|
||||
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = top_level(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can.
|
||||
assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius"));
|
||||
assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above
|
||||
// ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested.
|
||||
for radius in [100, 1000] {
|
||||
let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius}));
|
||||
assert!(e.ends_with("the circles are too far apart for this radius"), "{e}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other"));
|
||||
for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] {
|
||||
assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}");
|
||||
}
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false"));
|
||||
assert_eq!(top_level(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_circles_are_not_bridged() {
|
||||
let mut s = session();
|
||||
let a = circle(&mut s, 100.0, 100.0, 20.0);
|
||||
let b = circle(&mut s, 150.0, 100.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two 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"));
|
||||
}
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -211,7 +211,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -265,7 +265,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}",
|
||||
"{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}",
|
||||
has_selection,
|
||||
symbol_update
|
||||
),
|
||||
|
||||
@@ -32,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = name_param(p, "brush.get")?;
|
||||
let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?;
|
||||
Ok(serde_json::to_value(b).unwrap_or_default())
|
||||
let mut v = serde_json::to_value(&b).unwrap_or_default();
|
||||
// A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way.
|
||||
if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) {
|
||||
o.entry("hue_jitter").or_insert(json!(sc.hue_jitter));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]).
|
||||
|
||||
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
|
||||
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
|
||||
let keep_art = switch_or(p, "keepArt", false, C)?;
|
||||
let iso = s.doc()?.isolation;
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.set_symbol_pixel_aligned(&name, pixel);
|
||||
if keep_art {
|
||||
// The art stays where it is and stays selected, apart from art that is hidden or
|
||||
// locked, in a hidden or locked group or layer, or on a locked artboard.
|
||||
let locks = d.locked_artboards();
|
||||
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
|
||||
return Ok(None);
|
||||
}
|
||||
let id = instance_in_place(d, &ids, &name, place)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"name": name,
|
||||
"id": id.0,
|
||||
"id": id.map(|i| i.0),
|
||||
"registration": reg.0,
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
@@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Redefining the symbol being edited leaves symbol editing mode in the same step.
|
||||
let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name);
|
||||
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
|
||||
let keep_art = switch_or(p, "keepArt", false, C)?;
|
||||
if session.is_some() {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
s.end_text_edit();
|
||||
@@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
|
||||
// Nor can art that holds an instance of it, directly or through the symbols it nests.
|
||||
if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) {
|
||||
return Err(EngineError::Other("a symbol can't hold an instance of itself".into()));
|
||||
}
|
||||
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
|
||||
let (art, size, c) = normalize(art)?;
|
||||
let old = natural_size(&s.doc()?.doc, &name);
|
||||
let editing = session.is_some();
|
||||
// The isolation the kept art is selected in: the one from before symbol editing mode when
|
||||
// the step leaves it.
|
||||
let iso = match &session {
|
||||
Some(se) => se.back_isolation,
|
||||
None => s.doc()?.isolation,
|
||||
};
|
||||
let id = s.edit("Redefine Symbol", |d, sel| {
|
||||
if editing {
|
||||
crate::cmd::symboledit::finish(d, sel);
|
||||
@@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Each instance keeps its appearance changes to the objects the new art still has.
|
||||
fit_overrides(d, &instances);
|
||||
if keep_art {
|
||||
// The art stays where it is and stays selected, apart from art that is hidden or
|
||||
// locked, in a hidden or locked group or layer, or on a locked artboard.
|
||||
let locks = d.locked_artboards();
|
||||
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
|
||||
return Ok(None);
|
||||
}
|
||||
let reg = d.symbol_registration(&name);
|
||||
let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
if let Some(se) = &session {
|
||||
crate::cmd::symboledit::leave_editing(s, se)?;
|
||||
}
|
||||
Ok(json!({ "name": name, "id": id.0 }))
|
||||
Ok(json!({ "name": name, "id": id.map(|i| i.0) }))
|
||||
}
|
||||
|
||||
/// How many levels of nested instances Delete Symbol expands before it gives up.
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -940,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
if p.get("font").is_some() || p.get("style").is_some() {
|
||||
// A face from a redefined [Normal Character Style] is checked too, as one given here is.
|
||||
let normal_face = s
|
||||
.doc()
|
||||
.ok()
|
||||
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
|
||||
.is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style"));
|
||||
if p.get("font").is_some() || p.get("style").is_some() || normal_face {
|
||||
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
|
||||
_ => Default::default(),
|
||||
@@ -968,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
|
||||
|
||||
/// The paragraph alignment, leading model and character alignment new type starts with (`t`'s
|
||||
/// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel`
|
||||
/// and `charAlign` from `p`, else em box top to top and em box centre while the
|
||||
/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a
|
||||
/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that
|
||||
/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432),
|
||||
/// else the Roman baseline for both. Noted in the journal, so a
|
||||
/// replay sets the same whatever the interface.
|
||||
pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> {
|
||||
use vectorcraft_doc::{CharAlign, LeadingModel};
|
||||
@@ -989,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
l
|
||||
}
|
||||
};
|
||||
let align = match super::textedit::char_align_param(p, cmd)? {
|
||||
// A redefined [Normal Character Style] that sets Character Alignment gives it to new type.
|
||||
let normal_align = s
|
||||
.doc()
|
||||
.ok()
|
||||
.and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR))
|
||||
.filter(|m| m.contains_key("charAlign"))
|
||||
.and(t.runs.first().map(|r| r.style.char_align));
|
||||
let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline };
|
||||
@@ -1017,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
|
||||
/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill,
|
||||
/// #7975), in the document's
|
||||
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else
|
||||
/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined;
|
||||
/// never the current fill, #7975), in the style's language, else the document's. A `size` outside
|
||||
/// [`super::typecmd::TYPE_SIZES`] is an error.
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
|
||||
let mut style = CharStyle::default();
|
||||
let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc));
|
||||
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
|
||||
style.size = super::typecmd::given_type_size(sz, cmd)?;
|
||||
}
|
||||
if str_param(p, "font").is_some() || str_param(p, "style").is_some() {
|
||||
// A face given to the command takes its own version and axis settings, as a font change
|
||||
// does, not those [Normal Character Style] gave another face.
|
||||
style.font_version = None;
|
||||
style.font_axes.clear();
|
||||
}
|
||||
if let Some(f) = str_param(p, "font") {
|
||||
style.font_family = f.to_string();
|
||||
// A family alone starts in Regular, whatever style [Normal Character Style] has.
|
||||
style.font_style = CharStyle::default().font_style;
|
||||
}
|
||||
if let Some(f) = str_param(p, "style") {
|
||||
style.font_style = f.to_string();
|
||||
@@ -1037,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharSt
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)),
|
||||
None => style.fill,
|
||||
};
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
// In the language a redefined [Normal Character Style] gives, else the one Document Setup chose,
|
||||
// else Preferences › Hyphenation › Default Language; none for the default. Type already in a
|
||||
// document keeps its own.
|
||||
if style.language.is_none() {
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
}
|
||||
Ok(style)
|
||||
}
|
||||
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{
|
||||
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
|
||||
};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
|
||||
LineType::Solid => None,
|
||||
};
|
||||
if arrows {
|
||||
let head = match o.arrow_style {
|
||||
ArrowStyle::Filled => Some(Arrowhead::Triangle),
|
||||
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
|
||||
ArrowStyle::Tick => Some(Arrowhead::Slash),
|
||||
ArrowStyle::None => None,
|
||||
};
|
||||
let head = o.arrow_style.arrowhead();
|
||||
st.start_arrow = head.clone();
|
||||
st.end_arrow = head;
|
||||
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
|
||||
|
||||
@@ -238,7 +238,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Guide",
|
||||
[],
|
||||
None,
|
||||
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
|
||||
"{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies",
|
||||
guides_unlocked,
|
||||
guide_move
|
||||
),
|
||||
@@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dx = number_or(p, "dx", 0.0, "guide.move")?;
|
||||
let dy = number_or(p, "dy", 0.0, "guide.move")?;
|
||||
let copy = switch_or(p, "copy", false, "guide.move")?;
|
||||
switch_or(p, "interpolate", false, "guide.move")?;
|
||||
if !s.doc()?.selection.is_empty() {
|
||||
let ids = super::edit::selected_roots(s)?;
|
||||
return super::object::apply_transform(
|
||||
|
||||
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Map Graphic",
|
||||
[],
|
||||
None,
|
||||
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
|
||||
has_doc,
|
||||
map_graphic
|
||||
),
|
||||
@@ -113,22 +113,32 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !effects::takes_graphics(&effect.id) {
|
||||
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
|
||||
}
|
||||
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
|
||||
// but has no cap to show a new one on.
|
||||
// A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned
|
||||
// on again, but has no cap to show a new one on. Its side takes graphics.
|
||||
let merged = effects::merged_params(&effect.id, &effect.params);
|
||||
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
|
||||
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
|
||||
let side = base.face == effects::PlanarFace::Side;
|
||||
if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
|
||||
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
|
||||
}
|
||||
// With a depth of 0 the art is a plane, which has only a front.
|
||||
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
|
||||
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
|
||||
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
|
||||
}
|
||||
let mut graphic = base.clone();
|
||||
if p.get("scale").is_none()
|
||||
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
|
||||
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
|
||||
{
|
||||
graphic.scale = frame.fitting_scale(art);
|
||||
// A graphic on the side starts fitting inside the side unrolled about x = 0, short of
|
||||
// its cut; one on a cap inside the object's bounds.
|
||||
let fit = if side {
|
||||
effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art))
|
||||
} else {
|
||||
effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art))
|
||||
};
|
||||
if let Some(fit) = fit {
|
||||
graphic.scale = fit;
|
||||
}
|
||||
}
|
||||
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
|
||||
effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?;
|
||||
|
||||
@@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
|
||||
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() {
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
// A hollow Extrude & Bevel takes a graphic on its side.
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap();
|
||||
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}]));
|
||||
// A plane, and a depth of 0, have no side.
|
||||
let (mut s, plane) = setup("threeD.rotate");
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("one face"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
let (mut s, flat) = setup("threeD.extrude");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("one face"), "{e}");
|
||||
assert_eq!(undo_len(&s), history);
|
||||
// A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is
|
||||
// about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is
|
||||
// 11 × 21.
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap();
|
||||
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
|
||||
assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}");
|
||||
// A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the
|
||||
// part about x = 0 is three quarters of the outline.
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap();
|
||||
s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap();
|
||||
let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap();
|
||||
assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}");
|
||||
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
|
||||
assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_params_edits_graphics_and_checks_them() {
|
||||
let (mut s, id) = setup("threeD.extrude");
|
||||
|
||||
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
|
||||
}
|
||||
|
||||
/// Does a file of a document with `artboards` artboards, written in format `format` with options
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
|
||||
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
|
||||
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
|
||||
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
|
||||
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
|
||||
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
|
||||
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
|
||||
match format {
|
||||
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
|
||||
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
|
||||
"ai" | "ait" => {
|
||||
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
|
||||
!legacy && !(format == "ai" && art_page()) && every_artboard()
|
||||
@@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
|
||||
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
|
||||
/// always, unless read roots are in force, the file carries the native document (a native file or
|
||||
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
|
||||
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
|
||||
/// plug-in's file, as
|
||||
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
|
||||
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
|
||||
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
|
||||
|
||||
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
|
||||
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
|
||||
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
|
||||
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
|
||||
/// one named after the document) with that path's extension when the plug-in lists it, else its
|
||||
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
|
||||
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
|
||||
/// names (else one named after the document) with that path's extension when the plug-in lists it,
|
||||
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
use vectorcraft_plugins::{Error, export};
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let doc = doc.without_edit_modes();
|
||||
let doc = &*super::access::with_readable_settings_folder(&doc);
|
||||
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let path = p.get("path").and_then(Value::as_str);
|
||||
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
|
||||
|
||||
@@ -29,6 +29,8 @@ mod commands;
|
||||
mod common;
|
||||
mod envelope;
|
||||
mod mesh;
|
||||
#[cfg(test)]
|
||||
mod selected_tests;
|
||||
|
||||
pub(crate) use blend::expand_blends;
|
||||
pub use commands::specs;
|
||||
|
||||
@@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Is any selected blend one made without a spine?
|
||||
fn any_without_spine(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
pub(super) fn any_without_spine(s: &Session) -> bool {
|
||||
super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine))
|
||||
}
|
||||
|
||||
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::mesh::whole;
|
||||
use super::{
|
||||
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
|
||||
@@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let mut sel = Selection::default();
|
||||
sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer())));
|
||||
let ordered = sel.in_paint_order(&st.doc);
|
||||
let given: HashSet<NodeId> = ordered.iter().copied().collect();
|
||||
// Drop ids nested inside other given ids.
|
||||
return Ok(ordered
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
let anc = st.doc.ancestry(*id).unwrap_or_default();
|
||||
!anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a))
|
||||
!anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a))
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
@@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
/// dynamic symbol instance's art is selected.
|
||||
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut find = st.doc.nearest_finder();
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
if st.doc.node(a).is_some_and(pred) {
|
||||
if !out.contains(&a) {
|
||||
out.push(a);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some(n) = find.nearest(*id, pred)
|
||||
&& seen.insert(n.id)
|
||||
{
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the
|
||||
/// first one that does.
|
||||
pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false };
|
||||
let mut find = st.doc.nearest_finder();
|
||||
st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test))
|
||||
}
|
||||
|
||||
pub(super) fn is_blend(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Blend { .. })
|
||||
}
|
||||
@@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
|
||||
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
|
||||
if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) }
|
||||
}
|
||||
|
||||
/// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was.
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones
|
||||
//! the lookup of every ancestor by id found: the same ids in the same order, the same availability
|
||||
//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart};
|
||||
|
||||
use super::Session;
|
||||
use super::blend::any_without_spine;
|
||||
use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of};
|
||||
|
||||
/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from
|
||||
/// the object up, repeats dropped by a scan of the list.
|
||||
fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
if st.doc.node(a).is_some_and(pred) {
|
||||
if !out.contains(&a) {
|
||||
out.push(a);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`].
|
||||
fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> {
|
||||
super::has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`].
|
||||
fn without_spine_by_ids(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
}
|
||||
|
||||
/// Every check on the current selection gives what the lookups by id gave.
|
||||
fn agree(s: &Session, what: &str) {
|
||||
type Has = fn(&Session) -> std::result::Result<(), String>;
|
||||
for (name, pred, has, msg) in [
|
||||
("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"),
|
||||
("envelope", is_envelope, has_envelope, "select an envelope"),
|
||||
("mesh", is_mesh, has_mesh, "select a gradient mesh"),
|
||||
] {
|
||||
let want = selected_of_by_ids(s, pred);
|
||||
assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s");
|
||||
assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}");
|
||||
assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}");
|
||||
}
|
||||
assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine");
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId {
|
||||
select(s, ids);
|
||||
id_of(&s.execute(cmd, &p).unwrap())
|
||||
}
|
||||
|
||||
/// Every node id under the layers, parents before children (as Direct Selection can pick them).
|
||||
fn all_ids(s: &Session) -> Vec<NodeId> {
|
||||
fn walk(nodes: &[std::sync::Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
for n in nodes {
|
||||
out.push(n.id);
|
||||
if let Some(ch) = n.children() {
|
||||
walk(ch, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The active document, to change in place.
|
||||
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
}
|
||||
|
||||
/// Set the selection's objects as given, stale and repeated ids included.
|
||||
fn set_objects(s: &mut Session, ids: Vec<NodeId>) {
|
||||
s.doc_mut().unwrap().selection.objects = ids;
|
||||
}
|
||||
|
||||
/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine.
|
||||
/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key
|
||||
/// of `a`.
|
||||
fn document() -> (Session, [NodeId; 6]) {
|
||||
let mut s = session();
|
||||
let r: Vec<NodeId> = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect();
|
||||
let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({}));
|
||||
let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({}));
|
||||
let g = run(&mut s, "object.group", &[a, r[4]], json!({}));
|
||||
let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({}));
|
||||
let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50}));
|
||||
select(&mut s, &[r[7]]);
|
||||
s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap();
|
||||
if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) {
|
||||
spec.no_spine = true;
|
||||
}
|
||||
(s, [a, b, c, g, e, r[0]])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() {
|
||||
let (mut s, [a, b, c, g, e, inner_key]) = document();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
agree(&s, "select all");
|
||||
let all = all_ids(&s);
|
||||
let keys: Vec<NodeId> = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect();
|
||||
set_objects(&mut s, keys.clone());
|
||||
agree(&s, "keys, as Direct Selection picks them");
|
||||
set_objects(&mut s, all.iter().rev().copied().collect());
|
||||
agree(&s, "every node, children first");
|
||||
set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]);
|
||||
agree(&s, "repeated and stale ids, in first-seen order");
|
||||
assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order");
|
||||
set_objects(&mut s, vec![NodeId(999_999)]);
|
||||
agree(&s, "only a stale id");
|
||||
set_objects(&mut s, vec![]);
|
||||
agree(&s, "nothing");
|
||||
// A blend in another blend's key group: the inner one.
|
||||
set_objects(&mut s, vec![inner_key]);
|
||||
agree(&s, "a key of a blend nested in another's key group");
|
||||
assert_eq!(selected_of(&s, is_blend), vec![a]);
|
||||
// An object of a dynamic symbol instance's art: nothing.
|
||||
set_objects(&mut s, all.clone());
|
||||
s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] });
|
||||
agree(&s, "a symbol part");
|
||||
assert!(selected_of(&s, is_blend).is_empty());
|
||||
}
|
||||
|
||||
/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's
|
||||
/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is
|
||||
/// built again.
|
||||
#[test]
|
||||
fn a_repeated_id_counts_as_its_first_node() {
|
||||
let (mut s, [a, _, c, _, _, inner_key]) = document();
|
||||
let all = all_ids(&s);
|
||||
s.doc().unwrap().doc.node(a);
|
||||
let doc = doc_mut(&mut s);
|
||||
if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() {
|
||||
ch.insert(0, std::sync::Arc::new(Node::group(a, vec![])));
|
||||
}
|
||||
set_objects(&mut s, all.clone());
|
||||
agree(&s, "a repeated id, the cache older than the tree");
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
agree(&s, "a repeated id, no cache");
|
||||
s.doc().unwrap().doc.node(a);
|
||||
agree(&s, "a repeated id, cached afresh");
|
||||
set_objects(&mut s, vec![inner_key]);
|
||||
assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts");
|
||||
}
|
||||
|
||||
/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and
|
||||
/// the checks stop at the first selected object that has one.
|
||||
#[test]
|
||||
fn selected_blends_take_no_lookups_by_id() {
|
||||
let mut s = session();
|
||||
let mut keys = vec![];
|
||||
for i in 0..300 {
|
||||
let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0));
|
||||
run(&mut s, "object.blend.make", &[x, y], json!({}));
|
||||
keys.extend([x, y]);
|
||||
}
|
||||
for i in 0..1_000 {
|
||||
rect(&mut s, i as f64);
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
s.doc().unwrap().doc.node(keys[0]);
|
||||
let before = vectorcraft_doc::path_lookups();
|
||||
assert_eq!(selected_of(&s, is_blend).len(), 300);
|
||||
assert!(!any_selected_of(&s, is_mesh, |_| true));
|
||||
set_objects(&mut s, keys.clone());
|
||||
assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys");
|
||||
assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id");
|
||||
// The first key is in a blend: the check tests that key and its blend only.
|
||||
static TESTED: AtomicUsize = AtomicUsize::new(0);
|
||||
fn counted(n: &Node) -> bool {
|
||||
TESTED.fetch_add(1, Ordering::Relaxed);
|
||||
is_blend(n)
|
||||
}
|
||||
assert!(any_selected_of(&s, counted, |_| true));
|
||||
assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested");
|
||||
}
|
||||
|
||||
/// `n` and everything under it with new ids.
|
||||
fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = d.alloc_id();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
*c = std::sync::Arc::new(renumber(d, c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// This thread's CPU time in nanoseconds, where the system reports it (Linux).
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it,
|
||||
/// otherwise in wall-clock time.
|
||||
fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..calls {
|
||||
f();
|
||||
}
|
||||
let ms = match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1e3,
|
||||
};
|
||||
ms / f64::from(calls)
|
||||
}
|
||||
|
||||
/// The medians of 7 runs of `a` and of `b`, the runs taking turns.
|
||||
fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) {
|
||||
let (mut ta, mut tb) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
ta.push(ms_per_call(calls, a));
|
||||
tb.push(ms_per_call(calls, b));
|
||||
}
|
||||
ta.sort_by(f64::total_cmp);
|
||||
tb.sort_by(f64::total_cmp);
|
||||
(ta[3], tb[3])
|
||||
}
|
||||
|
||||
/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers,
|
||||
/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with
|
||||
/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand"]
|
||||
fn timing_of_the_selected_blend_checks() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0));
|
||||
let square = rect(&mut s, 120.0);
|
||||
let blend = run(&mut s, "object.blend.make", &[a, b], json!({}));
|
||||
let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50}));
|
||||
let doc = doc_mut(&mut s);
|
||||
let templates: Vec<Node> = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect();
|
||||
let mut layers = vec![];
|
||||
for l in 0..10 {
|
||||
let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0));
|
||||
let mut kids = vec![];
|
||||
for _ in 0..10_000 {
|
||||
kids.push(std::sync::Arc::new(renumber(doc, &templates[0])));
|
||||
}
|
||||
for i in 0..200 {
|
||||
let b = renumber(doc, &templates[1]);
|
||||
let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b };
|
||||
kids.push(std::sync::Arc::new(b));
|
||||
}
|
||||
for _ in 0..20 {
|
||||
kids.push(std::sync::Arc::new(renumber(doc, &templates[2])));
|
||||
}
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = kids;
|
||||
}
|
||||
layers.push(std::sync::Arc::new(layer));
|
||||
}
|
||||
doc.layers = layers;
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let first = s.doc().unwrap().selection.objects[0];
|
||||
s.doc().unwrap().doc.drop_lookup_cache();
|
||||
s.doc().unwrap().doc.node(first);
|
||||
println!("{} objects selected", s.doc().unwrap().selection.objects.len());
|
||||
type Check = fn(&Session) -> bool;
|
||||
let checks: [(&str, Check, Check); 5] = [
|
||||
("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()),
|
||||
("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()),
|
||||
("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()),
|
||||
(
|
||||
"selected blends (object.blend.info and the Blend commands)",
|
||||
|s| !selected_of_by_ids(s, is_blend).is_empty(),
|
||||
|s| !selected_of(s, is_blend).is_empty(),
|
||||
),
|
||||
("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine),
|
||||
];
|
||||
assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend));
|
||||
println!("| Check | Lookups by id (ms) | One path (ms) |");
|
||||
println!("|---|---:|---:|");
|
||||
for (name, by_ids, one_path) in checks {
|
||||
assert_eq!(by_ids(&s), one_path(&s), "{name}");
|
||||
let (old, new) = medians(
|
||||
15,
|
||||
&|| {
|
||||
std::hint::black_box(by_ids(&s));
|
||||
},
|
||||
&|| {
|
||||
std::hint::black_box(one_path(&s));
|
||||
},
|
||||
);
|
||||
println!("| {name} | {old:.3} | {new:.3} |");
|
||||
}
|
||||
}
|
||||
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
pub use transform::{reflect_axis, scale_factors, shear_tangent};
|
||||
@@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let refi = reference_index(p)?;
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
|
||||
let how = s.bounds_measure();
|
||||
if anchors
|
||||
&& transforms_objects(p)
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform",
|
||||
[],
|
||||
None,
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
has_doc,
|
||||
transform
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Shift+M"),
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection_or_guides,
|
||||
move_cmd
|
||||
),
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shear…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
shear
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform Again",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+D"),
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
has_selection,
|
||||
transform_again
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Nudge",
|
||||
[],
|
||||
None,
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
has_selection_or_guides,
|
||||
nudge
|
||||
),
|
||||
@@ -295,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
@@ -193,6 +193,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
|
||||
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
|
||||
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
|
||||
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
|
||||
// its span (its end angle less its start angle, counterclockwise).
|
||||
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
|
||||
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
|
||||
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
|
||||
}
|
||||
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
|
||||
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
|
||||
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
|
||||
@@ -204,7 +210,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// ellipse as 0° to 360°).
|
||||
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
|
||||
let pie_of = |pie: (f64, f64)| {
|
||||
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
let pie = match (constrain, pie_start, pie_end) {
|
||||
// The angle it already has: nothing moves.
|
||||
(true, Some(a), _) if a == pie.0 => pie,
|
||||
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
|
||||
// A whole ellipse (a span of 0) stays whole.
|
||||
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
|
||||
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
|
||||
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
|
||||
};
|
||||
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
|
||||
};
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
|
||||
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
|
||||
let d = &s.doc()?.doc;
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
let none = paths.is_empty() && !has_guides;
|
||||
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
|
||||
let mut interpolate = None;
|
||||
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
|
||||
options["strokes"] = json!(sc.strokes);
|
||||
options["corners"] = json!(!sc.keep_corners);
|
||||
}
|
||||
if let Some(on) = interpolate {
|
||||
options["interpolate"] = json!(on);
|
||||
}
|
||||
st.last_transform = Some(LastTransform::Matrix(xf, options));
|
||||
st.last_perspective = None;
|
||||
}
|
||||
@@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
|
||||
|
||||
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
|
||||
// is left as it is, and the reply's warning goes to the status bar.
|
||||
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.move")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
|
||||
check_switches(p, &["interpolate"], "object.move")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
|
||||
}
|
||||
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
|
||||
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.nudge")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
|
||||
check_switches(p, &["big"], "object.nudge")?;
|
||||
check_switches(p, &["big", "interpolate"], "object.nudge")?;
|
||||
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
|
||||
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
|
||||
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
|
||||
@@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
return ok();
|
||||
}
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
|
||||
}
|
||||
if s.doc()?.selection.is_empty() {
|
||||
let copy = bool_or(p, "copy", false);
|
||||
@@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
|
||||
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(bad("object.scale", "scale must be non-zero"));
|
||||
}
|
||||
let sx = f64_req(p, "sx", "object.scale")?;
|
||||
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
|
||||
let frame = basis_frame(s, p, "object.scale", &ids)?;
|
||||
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
|
||||
}
|
||||
|
||||
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
|
||||
/// either factor is 0.
|
||||
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
|
||||
let (sx, sy) = (sx / 100.0, sy / 100.0);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err("scale must be non-zero".into());
|
||||
}
|
||||
Ok((sx, sy))
|
||||
}
|
||||
|
||||
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
|
||||
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
|
||||
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
|
||||
@@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
|
||||
let named = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
|
||||
Some(Value::Number(_)) => None,
|
||||
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
|
||||
}
|
||||
};
|
||||
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
|
||||
let m = match named {
|
||||
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
|
||||
None => {
|
||||
@@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_transform(s, "Reflect", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
|
||||
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
|
||||
/// which is a line on the page; or the error for any other value.
|
||||
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
|
||||
match axis {
|
||||
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
|
||||
Some(Value::Number(_)) => Ok(None),
|
||||
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
|
||||
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
|
||||
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
|
||||
/// angle outside -359 to 359, or ±90 or ±270, is an error.
|
||||
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
|
||||
if !(-359.0..=359.0).contains(&angle) {
|
||||
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
|
||||
}
|
||||
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
|
||||
let flat = angle.rem_euclid(180.0);
|
||||
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
|
||||
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
|
||||
}
|
||||
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
|
||||
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
|
||||
}
|
||||
|
||||
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["angle"], "object.shear")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
|
||||
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
|
||||
let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical");
|
||||
let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) };
|
||||
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
|
||||
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
|
||||
let m = match p.get("axis") {
|
||||
None | Some(Value::Null) => horizontal,
|
||||
Some(Value::String(a)) if a == "horizontal" => horizontal,
|
||||
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
|
||||
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
|
||||
// y is down, so the page's counter-clockwise angle turns the other way on screen.
|
||||
let r = -n.as_f64().unwrap_or(0.0).to_radians();
|
||||
Affine::rotate(r) * horizontal * Affine::rotate(-r)
|
||||
}
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
|
||||
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
|
||||
}
|
||||
};
|
||||
apply_transform(s, "Shear", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
|
||||
const SHEAR_AXIS_MAX: f64 = 359.0;
|
||||
|
||||
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
|
||||
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
|
||||
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
|
||||
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
|
||||
check_switches(p, &["interpolate"], "object.transformAgain")?;
|
||||
if let Some(again) = s.doc()?.last_perspective.clone() {
|
||||
return crate::cmd::distortcmds::transform_again(s, &again);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -113,27 +113,65 @@ thread_local! {
|
||||
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
|
||||
}
|
||||
let data =
|
||||
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
|
||||
vectorcraft_format::load(&data?).ok()
|
||||
/// The native document a linked file is or carries ([`carried_document`]).
|
||||
enum Carried {
|
||||
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
|
||||
/// without editing data.
|
||||
Absent,
|
||||
/// The native document, read.
|
||||
Readable(Box<Document>),
|
||||
/// The file is a native document, or carries one, that can't be read: a damaged native file,
|
||||
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
|
||||
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
|
||||
/// whose attachments are too many to search to their end, or editing data that doesn't read as
|
||||
/// a native document.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
|
||||
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
|
||||
}
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
// A PDF that can't be opened may carry editing data all the same.
|
||||
return match vectorcraft_pdf::open_pdf(bytes, None) {
|
||||
// Attachments left unsearched may list another editing file, which can't be checked.
|
||||
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
|
||||
// An editing file listed whose data can't be resolved can't be checked either.
|
||||
Ok(opened) => match opened.editing() {
|
||||
Some(e) => read(&e.data),
|
||||
None if opened.has_editing_file() => Carried::Unreadable,
|
||||
None => Carried::Absent,
|
||||
},
|
||||
Err(_) => Carried::Unreadable,
|
||||
};
|
||||
}
|
||||
if !vectorcraft_eps::has_native(bytes) {
|
||||
return Carried::Absent;
|
||||
}
|
||||
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy whose native document can't be read to
|
||||
/// check the files and folders it names against the read roots.
|
||||
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
|
||||
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
|
||||
/// relative path taken from the file's folder): the copy would name it.
|
||||
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
|
||||
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
|
||||
/// whose native document can't be read is refused, as its links can't be checked. The error names
|
||||
/// no file or folder.
|
||||
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
None => Ok(()),
|
||||
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
Carried::Absent => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
|
||||
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
|
||||
Err(bad(C, FOLDER_OUTSIDE))
|
||||
}
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -498,6 +539,9 @@ pub struct Package {
|
||||
root: Option<PathBuf>,
|
||||
info: Option<String>,
|
||||
doc: std::sync::Arc<Document>,
|
||||
/// The read roots in force where the package was prepared: [`Package::write`] collects under
|
||||
/// them.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
|
||||
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
|
||||
}
|
||||
|
||||
impl Package {
|
||||
/// Collect the linked files and fonts and write the package's files with `write` into
|
||||
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
|
||||
/// `file.package`.
|
||||
/// `file.package`, with the read roots in force where it was prepared, on any thread.
|
||||
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
collect_and_write(self, write)
|
||||
self.scope.clone().run(|| collect_and_write(self, write))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Package::write`].
|
||||
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
|
||||
let mut doc = (*original).clone();
|
||||
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
|
||||
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
|
||||
|
||||
@@ -274,8 +274,9 @@ impl DocState {
|
||||
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
|
||||
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
|
||||
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
|
||||
/// each selected object's own stack is compared. One walk of the document, so callers that ask
|
||||
/// every frame cache it by revision.
|
||||
/// each selected object's own stack is compared. The selected objects are found through the id
|
||||
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
|
||||
/// of the document, so callers that ask every frame cache it by revision.
|
||||
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
|
||||
self.proxy_mixed_with(item, &[])
|
||||
}
|
||||
@@ -290,15 +291,17 @@ impl DocState {
|
||||
if self.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
self.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
#[cfg(test)]
|
||||
tests::note_gathered();
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
@@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.execute("object.setProps", &Value::Object(q))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
|
||||
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
|
||||
//! reads only those.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
/// [`gathered`] of this thread.
|
||||
static GATHERED: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
|
||||
pub(super) fn note_gathered() {
|
||||
GATHERED.set(GATHERED.get() + 1);
|
||||
}
|
||||
|
||||
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
|
||||
fn gathered() -> u64 {
|
||||
GATHERED.get()
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
|
||||
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
|
||||
if st.selection.is_empty() {
|
||||
return (false, false);
|
||||
}
|
||||
if st.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
});
|
||||
let Some(p0) = paints.next() else { return false };
|
||||
paints.any(|p| !same_in_proxy(&p0, &p))
|
||||
};
|
||||
(differ(false), differ(true))
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
|
||||
/// and with and without `points`, with the id cache built and without it.
|
||||
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
|
||||
for points in [points, &[]] {
|
||||
assert_eq!(
|
||||
st.proxy_mixed_with(item, points),
|
||||
walked(st, item, points),
|
||||
"{what}: item {item:?}, {} picked points, cold cache {cold}",
|
||||
points.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn id_of(v: &serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
|
||||
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
|
||||
/// different fills or strokes, a group with different contents, a group with one of its objects,
|
||||
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
|
||||
/// gradient mesh with points picked beside another object, ids not in the document and an id that
|
||||
/// appears twice (a damaged file) with different paints.
|
||||
#[test]
|
||||
fn the_question_marks_match_a_walk_of_the_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
|
||||
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
|
||||
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
|
||||
// Two fills: [Fill, Stroke, Fill].
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
|
||||
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
|
||||
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
|
||||
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
|
||||
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
|
||||
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
|
||||
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
|
||||
let missing = NodeId(999_999);
|
||||
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
|
||||
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
|
||||
let points = vec![(mesh, vec![p00, p01])];
|
||||
let points_alike = vec![(mesh, vec![p01, p11])];
|
||||
|
||||
let selections = [
|
||||
vec![a],
|
||||
vec![a, b],
|
||||
vec![b, a],
|
||||
vec![a, h],
|
||||
vec![g],
|
||||
vec![g, e],
|
||||
vec![e, g],
|
||||
vec![f, e],
|
||||
vec![c],
|
||||
vec![c, a],
|
||||
vec![a, c],
|
||||
vec![mesh],
|
||||
vec![mesh, a],
|
||||
vec![a, mesh, h],
|
||||
vec![hidden],
|
||||
vec![hidden, b],
|
||||
vec![missing],
|
||||
vec![missing, a],
|
||||
vec![a, missing, b],
|
||||
vec![a, a],
|
||||
];
|
||||
let check = |s: &mut Session, what: &str| {
|
||||
for sel in &selections {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
agree(st, &points, &format!("{what}: {sel:?}"));
|
||||
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
|
||||
};
|
||||
check(&mut s, "unique ids");
|
||||
|
||||
// A second node with a's id and another fill, at the end of the tree.
|
||||
let st = s.active_mut().unwrap();
|
||||
let mut copy = st.doc.node(a).unwrap().clone();
|
||||
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let doc = Arc::make_mut(&mut st.doc);
|
||||
let last = doc.layers.len() - 1;
|
||||
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
|
||||
doc.drop_lookup_cache();
|
||||
check(&mut s, "a repeated id");
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![a];
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
|
||||
}
|
||||
|
||||
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
|
||||
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
|
||||
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
d.layers.clear();
|
||||
let mut rects = vec![];
|
||||
for l in 0..layers {
|
||||
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
|
||||
for _ in 0..groups {
|
||||
let children = (0..per_group)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
let mut ap = Appearance::default_art();
|
||||
let red = rects.len() % 2 == 0;
|
||||
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
|
||||
rects.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
|
||||
})
|
||||
.collect();
|
||||
let group = Node::group(d.alloc_id(), children);
|
||||
layer.children_mut().unwrap().push(Arc::new(group));
|
||||
}
|
||||
d.layers.push(Arc::new(layer));
|
||||
}
|
||||
(d, rects)
|
||||
}
|
||||
|
||||
fn state(doc: Document) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
|
||||
s.active_mut().unwrap().doc = Arc::new(doc);
|
||||
s
|
||||
}
|
||||
|
||||
/// With one object selected, the "?" reads only that object, not every node of the document, and
|
||||
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
|
||||
/// once.
|
||||
#[test]
|
||||
fn the_question_marks_read_only_the_selected_objects() {
|
||||
let (doc, rects) = big(2, 40, 25);
|
||||
let mut s = state(doc);
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![rects[777]];
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
assert_eq!(gathered() - read, 1, "only the selected object is read");
|
||||
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
|
||||
|
||||
st.selection.objects = vec![rects[3], rects[1500]];
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
|
||||
|
||||
st.selection.objects = rects.clone();
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!(gathered() - read, rects.len() as u64);
|
||||
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
|
||||
}
|
||||
|
||||
/// Random selections of a document with nested groups answer as a walk does.
|
||||
#[test]
|
||||
fn random_selections_match_a_walk_of_the_document() {
|
||||
let (doc, rects) = big(3, 12, 6);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
|
||||
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
|
||||
let mut r = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut next = |n: usize| {
|
||||
r ^= r << 13;
|
||||
r ^= r >> 7;
|
||||
r ^= r << 17;
|
||||
(r % n as u64) as usize
|
||||
};
|
||||
for round in 0..200 {
|
||||
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
|
||||
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<std::time::Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> std::time::Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = std::time::Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
|
||||
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand"]
|
||||
fn proxy_mixed_timing() {
|
||||
let (doc, rects) = big(5, 100, 100);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let cases: [(&str, Vec<NodeId>); 5] = [
|
||||
("1 object", vec![rects[25_000]]),
|
||||
("2 objects, different fills", vec![rects[10], rects[40_001]]),
|
||||
("a group of 100", vec![groups[250]]),
|
||||
("all 500 groups", groups.clone()),
|
||||
("all 50,000 objects", rects.clone()),
|
||||
];
|
||||
const CALLS: usize = 200;
|
||||
let median = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
|
||||
println!("|---|---|---|---|---|");
|
||||
for (name, sel) in &cases {
|
||||
for cold in [false, true] {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let calls = if cold { CALLS / 10 } else { CALLS };
|
||||
for _ in 0..7 {
|
||||
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
|
||||
let d = time(|| {
|
||||
for _ in 0..calls {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
|
||||
}
|
||||
});
|
||||
times.push(d.as_secs_f64() * 1e6 / calls as f64);
|
||||
}
|
||||
}
|
||||
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
|
||||
println!(
|
||||
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
|
||||
if cold { "dropped before each call" } else { "built" },
|
||||
median(old.clone()),
|
||||
median(new.clone()),
|
||||
runs(&old),
|
||||
runs(&new)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
-10
@@ -1,10 +1,10 @@
|
||||
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
|
||||
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use super::create::anchor_from_json;
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
|
||||
check_switches(p, &["patterns"], "path.moveAnchors")?;
|
||||
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
// Objects selected whole move as objects, and their pattern tiles move with them when
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let whole = s.doc()?.selection.whole();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
|
||||
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?;
|
||||
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
|
||||
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
|
||||
// Transform Again repeats a move that moved something; a drag records it when it commits.
|
||||
let st = s.doc_mut()?;
|
||||
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
|
||||
let options = json!({ "copy": false, "patterns": sc.patterns });
|
||||
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
|
||||
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
|
||||
st.last_perspective = None;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
|
||||
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
|
||||
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
|
||||
/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the
|
||||
/// preference existed, so it moves the handles as it did then, without re-mapping them.
|
||||
pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let default = s.prefs.interpolate_control_points && !s.replaying();
|
||||
let on = switch_or(p, "interpolate", default, cmd)?;
|
||||
s.note_journal("interpolate", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
|
||||
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
|
||||
/// another selected object, such as a path in a selected group, moves once, with that object.
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> {
|
||||
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
|
||||
/// are re-mapped ([`move_interpolating_handles`]).
|
||||
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
|
||||
let sel = s.doc()?.selection.clone();
|
||||
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
|
||||
let c = xf.as_coeffs();
|
||||
@@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
match sel.anchors.get(id) {
|
||||
Some(set) => {
|
||||
let path = path_mut(doc, *id)?;
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
// Only an exact move takes the interpolating path: a near-identity scale or
|
||||
// turn still transforms the anchors as asked.
|
||||
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
move_interpolating_handles(path, set, delta);
|
||||
} else {
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
|
||||
@@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
})
|
||||
}
|
||||
|
||||
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
|
||||
/// of each segment with exactly one moved end by the map that takes the segment's old ends to its
|
||||
/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its
|
||||
/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place
|
||||
/// before or after the move, moves as it does without the preference. A smooth anchor keeps its
|
||||
/// two handles in line ([`line_up_handles`]).
|
||||
fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet<AnchorRef>, d: Vec2) {
|
||||
// (subpath, anchor, outgoing handle?, new position)
|
||||
let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new();
|
||||
if d != Vec2::ZERO {
|
||||
// Only the segments beside a moved anchor can have one moved end: (subpath, first anchor).
|
||||
let mut segments: BTreeSet<AnchorRef> = BTreeSet::new();
|
||||
for &(si, ai) in set {
|
||||
let Some(sp) = path.subpaths.get(si) else { continue };
|
||||
let n = sp.anchors.len();
|
||||
if ai >= n || n < 2 {
|
||||
continue;
|
||||
}
|
||||
if ai > 0 || sp.closed {
|
||||
segments.insert((si, (ai + n - 1) % n));
|
||||
}
|
||||
if ai + 1 < n || sp.closed {
|
||||
segments.insert((si, ai));
|
||||
}
|
||||
}
|
||||
for (si, from) in segments {
|
||||
let Some(sp) = path.subpaths.get(si) else { continue };
|
||||
let to = (from + 1) % sp.anchors.len().max(1);
|
||||
let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to)));
|
||||
if moved_from == moved_to {
|
||||
continue;
|
||||
}
|
||||
let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue };
|
||||
let old = b.p - a.p;
|
||||
let len2 = old.hypot2();
|
||||
if len2 <= 1e-12 || !len2.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let start = if moved_from { a.p + d } else { a.p };
|
||||
let end = if moved_to { b.p + d } else { b.p };
|
||||
let new = end - start;
|
||||
// A move that puts the two ends at the same place would collapse both handles onto
|
||||
// them, past recovering by moving back.
|
||||
if new.hypot2() <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
// `new / old` as complex numbers: the turn and scale between the two chords.
|
||||
let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2);
|
||||
let map = |h: Point| {
|
||||
let v = h - a.p;
|
||||
start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re)
|
||||
};
|
||||
// A retracted handle goes to its anchor's new place exactly: mapped, it could land a
|
||||
// rounding error away, which `line_up_handles` would read as a direction.
|
||||
let h_out = if a.h_out == a.p { start } else { map(a.h_out) };
|
||||
let h_in = if b.h_in == b.p { end } else { map(b.h_in) };
|
||||
if h_out.is_finite() && h_in.is_finite() {
|
||||
placed.push((si, from, true, h_out));
|
||||
placed.push((si, to, false, h_in));
|
||||
}
|
||||
}
|
||||
}
|
||||
for &(si, ai) in set {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
a.translate(d);
|
||||
}
|
||||
}
|
||||
// For each anchor with a re-mapped handle: its handles as the plain move left them, and which
|
||||
// of them (outgoing, incoming) were re-mapped.
|
||||
let mut touched: BTreeMap<AnchorRef, (Point, Point, bool, bool)> = BTreeMap::new();
|
||||
for &(si, ai, out, pos) in &placed {
|
||||
if let Some(a) = path.anchor_mut(si, ai) {
|
||||
let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false));
|
||||
if out {
|
||||
a.h_out = pos;
|
||||
e.2 = true;
|
||||
} else {
|
||||
a.h_in = pos;
|
||||
e.3 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched {
|
||||
let Some(a) = path.anchor_mut(si, ai) else { continue };
|
||||
if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) {
|
||||
a.h_out = rigid_out;
|
||||
a.h_in = rigid_in;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`]
|
||||
/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle
|
||||
/// turns to point away from the other handle, at its own new length; when both were re-mapped,
|
||||
/// both point along the mean of their directions. A retracted handle is left as it is. False when
|
||||
/// both were re-mapped to point the same way, which has no mean direction: the caller then moves
|
||||
/// both handles with the anchor.
|
||||
fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool {
|
||||
let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p);
|
||||
let (l_out, l_in) = (v_out.hypot(), v_in.hypot());
|
||||
if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() {
|
||||
return true;
|
||||
}
|
||||
let dir = match (out, inn) {
|
||||
(true, true) => v_out / l_out - v_in / l_in,
|
||||
(true, false) => -v_in / l_in,
|
||||
(false, true) => v_out / l_out,
|
||||
(false, false) => return true,
|
||||
};
|
||||
let l = dir.hypot();
|
||||
if l <= 1e-12 || !l.is_finite() {
|
||||
return false;
|
||||
}
|
||||
let dir = dir / l;
|
||||
if out {
|
||||
a.h_out = a.p + dir * l_out;
|
||||
}
|
||||
if inn {
|
||||
a.h_in = a.p - dir * l_in;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
|
||||
|
||||
@@ -161,6 +161,8 @@ pub struct FilterRun {
|
||||
parent: Option<NodeId>,
|
||||
/// The document it was made from, and that document's revision then.
|
||||
document: (u64, u64),
|
||||
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
|
||||
limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
|
||||
@@ -245,7 +247,11 @@ impl FilterRun {
|
||||
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
|
||||
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
|
||||
let document = (st.uid, st.revision);
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
|
||||
let limits = match s.prefs.plugin_instruction_budget {
|
||||
crate::PluginBudget::Normal => plugin.limits().clone(),
|
||||
crate::PluginBudget::Large => plugin.large_limits(),
|
||||
};
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
|
||||
}
|
||||
|
||||
/// The plug-in, for its name and budget.
|
||||
@@ -274,7 +280,13 @@ impl FilterRun {
|
||||
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
|
||||
/// two slices of its budget.
|
||||
pub fn run(&self) -> Result<Vec<u8>> {
|
||||
self.plugin.run(&self.input, &self.params).map_err(err)
|
||||
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
|
||||
}
|
||||
|
||||
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
|
||||
/// it was made.
|
||||
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
|
||||
@@ -289,7 +301,7 @@ impl FilterRun {
|
||||
let may = self.plugin.manifest().permissions();
|
||||
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
|
||||
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
|
||||
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
|
||||
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
|
||||
}
|
||||
|
||||
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.bridge",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.commonTangents",
|
||||
"addon.pathtools.corner",
|
||||
|
||||
@@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)),
|
||||
p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)),
|
||||
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
|
||||
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
|
||||
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
|
||||
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
|
||||
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
|
||||
@@ -323,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
|
||||
// Plug-ins & Scratch Disks
|
||||
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
|
||||
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
|
||||
p!(
|
||||
"pluginInstructionBudget",
|
||||
"Plug-ins & Scratch Disks",
|
||||
"Plug-ins",
|
||||
"Plug-in Instruction Budget",
|
||||
choice(&[("normal", "Normal"), ("large", "Large")])
|
||||
),
|
||||
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
|
||||
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
|
||||
// User Interface
|
||||
|
||||
@@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option<NodeId>, locks: Option<&Locked
|
||||
}
|
||||
}
|
||||
|
||||
/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest
|
||||
/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects
|
||||
/// and sublayers are passed over. Only the siblings are read, not the rest of the document.
|
||||
fn step_target(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
|
||||
let path = d.index_path(cur)?;
|
||||
let (&idx, up) = path.split_last()?;
|
||||
// The objects that hold `cur` and its siblings, from the top-level layer down.
|
||||
let mut holders = Vec::with_capacity(up.len());
|
||||
let mut siblings = &d.layers;
|
||||
for &i in up {
|
||||
let n = siblings.get(i)?;
|
||||
holders.push(n.as_ref());
|
||||
siblings = n.children()?;
|
||||
}
|
||||
let iso = iso.and_then(|i| d.node(i));
|
||||
let locks = d.locked_artboards();
|
||||
let visits = |n: &Node| walk_visits(&holders, n, iso, &locks);
|
||||
let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) };
|
||||
next.map(|n| n.id)
|
||||
}
|
||||
|
||||
/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its
|
||||
/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first
|
||||
/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike
|
||||
/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk
|
||||
/// looks through or leaves out.
|
||||
fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool {
|
||||
let len = holders.len() + 1;
|
||||
let at = |i: usize| holders.get(i).copied().unwrap_or(n);
|
||||
let open = |i: usize| at(i).visible && !at(i).locked;
|
||||
let start = match iso {
|
||||
Some(c) => {
|
||||
let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false };
|
||||
if !(0..=p).all(|i| open(i) && !at(i).is_template()) {
|
||||
return false;
|
||||
}
|
||||
// A single object isolated is all there is to select.
|
||||
if !c.is_container() {
|
||||
return p + 1 == len;
|
||||
}
|
||||
p + 1
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
// The object Select All takes: the first one that is not a layer, inside visible, unlocked
|
||||
// layers and sublayers that are not template layers.
|
||||
let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false };
|
||||
(start..top).all(|i| open(i) && !at(i).is_template())
|
||||
&& !at(top).is_ruler_guide()
|
||||
&& (top..len).all(open)
|
||||
&& (iso.is_some() || locks.is_empty() || !locks.holds(at(top)))
|
||||
}
|
||||
|
||||
/// The first selected object, in selection order, that [`is_selectable`] accepts.
|
||||
pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> {
|
||||
let locks = st.doc.locked_artboards();
|
||||
@@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn step(s: &mut Session, dir: i64) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let Some(cur) = st.selection.objects.first().copied() else { return ok() };
|
||||
let Some((par, idx, _)) = st.doc.position(cur) else { return ok() };
|
||||
let Some(siblings) = st.doc.children(par) else { return ok() };
|
||||
// The nearest sibling in that direction that `walk_selectable` visits: hidden and locked
|
||||
// objects and sublayers are passed over.
|
||||
let can = selectable_ids(&st.doc, st.isolation);
|
||||
let next = if dir > 0 {
|
||||
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
|
||||
} else {
|
||||
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
|
||||
};
|
||||
let Some(id) = next.map(|n| n.id) else { return ok() };
|
||||
let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() };
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
ok()
|
||||
}
|
||||
@@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod same_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod step_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,347 @@
|
||||
//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of
|
||||
//! the selected object, against a copy of the search that collected every object
|
||||
//! [`walk_selectable`] visits on each step.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{selectable_ids, step_target, walk_visits};
|
||||
use crate::Session;
|
||||
|
||||
/// The search as it was before it read only the siblings: the nearest sibling in that direction
|
||||
/// that `walk_selectable` visits, from the set of every object it visits.
|
||||
fn step_base(d: &Document, iso: Option<NodeId>, cur: NodeId, dir: i64) -> Option<NodeId> {
|
||||
let (par, idx, _) = d.position(cur)?;
|
||||
let siblings = d.children(par)?;
|
||||
let can = selectable_ids(d, iso);
|
||||
let next = if dir > 0 {
|
||||
siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id))
|
||||
} else {
|
||||
siblings.iter().take(idx).rev().find(|n| can.contains(&n.id))
|
||||
};
|
||||
next.map(|n| n.id)
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so that each seed gives the same document every run.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
|
||||
/// True `pct` times in 100.
|
||||
fn chance(&mut self, pct: u64) -> bool {
|
||||
self.below(100) < pct
|
||||
}
|
||||
}
|
||||
|
||||
fn rect_node(d: &mut Document, x: f64, y: f64) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default())
|
||||
}
|
||||
|
||||
fn layer_node(d: &mut Document, children: Vec<Node>) -> Node {
|
||||
let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
ch.extend(children.into_iter().map(Arc::new));
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn ruler_guide(d: &mut Document, pos: f64) -> Node {
|
||||
Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None })
|
||||
}
|
||||
|
||||
/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides,
|
||||
/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more
|
||||
/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make,
|
||||
/// so that every shape of tree is compared.
|
||||
fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec<Node> {
|
||||
(0..r.below(7))
|
||||
.map(|_| {
|
||||
let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0);
|
||||
let mut n = match r.below(if depth == 0 { 6 } else { 10 }) {
|
||||
0..=3 => rect_node(d, x, y),
|
||||
4 => {
|
||||
let mut n = rect_node(d, x, y);
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n
|
||||
}
|
||||
5 => ruler_guide(d, x),
|
||||
6 | 7 => {
|
||||
let kids = objects(r, d, depth - 1);
|
||||
Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect())
|
||||
}
|
||||
_ => {
|
||||
let kids = objects(r, d, depth - 1);
|
||||
layer_node(d, kids)
|
||||
}
|
||||
};
|
||||
n.visible = !r.chance(10);
|
||||
n.locked = r.chance(10);
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = r.chance(15);
|
||||
}
|
||||
n
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A document of one to three layers, some hidden, locked or template layers, holding
|
||||
/// [`objects`], with its artboard locked in some seeds.
|
||||
fn random_document(seed: u64) -> Document {
|
||||
let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let layers = (0..1 + r.below(3))
|
||||
.map(|_| {
|
||||
let kids = objects(&mut r, &mut d, 3);
|
||||
let mut l = layer_node(&mut d, kids);
|
||||
l.visible = !r.chance(10);
|
||||
l.locked = r.chance(10);
|
||||
if let NodeKind::Layer { template, .. } = &mut l.kind {
|
||||
*template = r.chance(10);
|
||||
}
|
||||
Arc::new(l)
|
||||
})
|
||||
.collect();
|
||||
d.layers = layers;
|
||||
if let Some(a) = d.artboards.first_mut() {
|
||||
a.locked = r.chance(40);
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Every node of `d`, layers included, in tree order.
|
||||
fn all_ids(d: &Document) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
d.walk(|n| ids.push(n.id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The objects that hold `id`, outermost first, and the node itself.
|
||||
fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) {
|
||||
let a = d.ancestry(id).unwrap();
|
||||
let (last, up) = a.split_last().unwrap();
|
||||
(up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap())
|
||||
}
|
||||
|
||||
/// For every node of random documents, outside isolation mode and with each of several nodes
|
||||
/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and
|
||||
/// Next Object Above and Below from it give what the search over that set gave.
|
||||
#[test]
|
||||
fn next_object_gives_what_the_search_over_every_selectable_object_gave() {
|
||||
let (mut steps, mut moved, mut isolated) = (0, 0, 0);
|
||||
for seed in 0..300 {
|
||||
let d = random_document(seed);
|
||||
let ids = all_ids(&d);
|
||||
let mut r = Rng(seed + 7);
|
||||
let mut isos = vec![None];
|
||||
isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize])));
|
||||
let locks = d.locked_artboards();
|
||||
for iso in isos {
|
||||
let can = selectable_ids(&d, iso);
|
||||
let iso_node = iso.and_then(|i| d.node(i));
|
||||
for &id in &ids {
|
||||
let (up, n) = holders(&d, id);
|
||||
assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}");
|
||||
}
|
||||
for &cur in &ids {
|
||||
for dir in [1, -1] {
|
||||
let want = step_base(&d, iso, cur, dir);
|
||||
assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}");
|
||||
steps += 1;
|
||||
moved += usize::from(want.is_some());
|
||||
isolated += usize::from(want.is_some() && iso.is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The documents give many steps that select something, inside isolation mode too.
|
||||
eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode");
|
||||
assert!(moved > 5_000, "{moved} of {steps} steps select an object");
|
||||
assert!(isolated > 500, "{isolated} steps select an object in isolation mode");
|
||||
}
|
||||
|
||||
/// A session holding `d`, with `iso` isolated and `cur` selected.
|
||||
fn session(d: Document, iso: Option<NodeId>, cur: NodeId) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
let st = s.doc_mut().unwrap();
|
||||
st.isolation = iso;
|
||||
st.selection.set([cur]);
|
||||
s
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.to_vec()
|
||||
}
|
||||
|
||||
/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object,
|
||||
/// as the walk looks through it.
|
||||
#[test]
|
||||
fn next_object_passes_over_a_sublayer_in_an_isolated_layer() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let a = rect_node(&mut d, 0.0, 0.0);
|
||||
let inner = rect_node(&mut d, 100.0, 0.0);
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let sub = layer_node(&mut d, vec![inner]);
|
||||
let (a_id, b_id) = (a.id, b.id);
|
||||
let l = layer_node(&mut d, vec![a, sub, b]);
|
||||
let layer = l.id;
|
||||
d.layers = vec![Arc::new(l)];
|
||||
assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id));
|
||||
let mut s = session(d, Some(layer), a_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
s.execute("select.nextBelow", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a_id]);
|
||||
}
|
||||
|
||||
/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the
|
||||
/// guide is the object isolated.
|
||||
#[test]
|
||||
fn next_object_passes_over_a_ruler_guide_of_the_layer() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let a = rect_node(&mut d, 0.0, 0.0);
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let guide = ruler_guide(&mut d, 100.0);
|
||||
let (a_id, b_id, guide_id) = (a.id, b.id, guide.id);
|
||||
let l = layer_node(&mut d, vec![a, b, guide]);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
// Nothing above the rectangle but the guide: the selection stays.
|
||||
assert_eq!(step_base(&d, None, b_id, 1), None);
|
||||
let mut s = session(d.clone(), None, b_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
s.execute("select.nextBelow", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a_id]);
|
||||
// The guide isolated on its own is what there is to select.
|
||||
assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id));
|
||||
assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id));
|
||||
}
|
||||
|
||||
/// The first selected object anchors the search even when it can no longer be selected itself.
|
||||
#[test]
|
||||
fn next_object_steps_from_a_hidden_first_selected_object() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let mut a = rect_node(&mut d, 0.0, 0.0);
|
||||
a.visible = false;
|
||||
let b = rect_node(&mut d, 200.0, 0.0);
|
||||
let (a_id, b_id) = (a.id, b.id);
|
||||
let l = layer_node(&mut d, vec![a, b]);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
assert_eq!(step_base(&d, None, a_id, 1), Some(b_id));
|
||||
let mut s = session(d, None, a_id);
|
||||
s.execute("select.nextAbove", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![b_id]);
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when
|
||||
/// `groups` is 0 → the document and the object in the middle of the layer.
|
||||
fn wide(groups: usize, per: usize) -> (Document, NodeId) {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let mut top = vec![];
|
||||
if groups == 0 {
|
||||
top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0)));
|
||||
} else {
|
||||
for g in 0..groups {
|
||||
let kids: Vec<Arc<Node>> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect();
|
||||
top.push(Node::group(d.alloc_id(), kids));
|
||||
}
|
||||
}
|
||||
let mid = top[top.len() / 2].id;
|
||||
let l = layer_node(&mut d, top);
|
||||
d.layers = vec![Arc::new(l)];
|
||||
(d, mid)
|
||||
}
|
||||
|
||||
/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`].
|
||||
type Step = fn(&Document, Option<NodeId>, NodeId, i64) -> Option<NodeId>;
|
||||
|
||||
/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of
|
||||
/// the layer, by the search over every selectable object (200 steps a run) and by the siblings
|
||||
/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000
|
||||
/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by
|
||||
/// default; it prints the median, fastest and slowest time per step and sets no bound on them:
|
||||
/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn next_object_perf() {
|
||||
const RUNS: usize = 7;
|
||||
const OLD_STEPS: usize = 200;
|
||||
const NEW_STEPS: usize = 200_000;
|
||||
let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64;
|
||||
eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)");
|
||||
for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] {
|
||||
let (d, mid) = wide(groups, per);
|
||||
let walk = |f: Step, steps: usize| {
|
||||
let mut cur = mid;
|
||||
let mut seen = Vec::with_capacity(steps);
|
||||
for i in 0..steps {
|
||||
cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur);
|
||||
seen.push(cur);
|
||||
}
|
||||
std::hint::black_box(seen)
|
||||
};
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(time(|| a = walk(step_base, OLD_STEPS)));
|
||||
new.push(time(|| b = walk(step_target, NEW_STEPS)));
|
||||
} else {
|
||||
new.push(time(|| b = walk(step_target, NEW_STEPS)));
|
||||
old.push(time(|| a = walk(step_base, OLD_STEPS)));
|
||||
}
|
||||
assert_eq!(a[..], b[..OLD_STEPS], "{name}");
|
||||
assert_ne!(a[0], mid, "{name}: the first step selects another object");
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
eprintln!(
|
||||
"next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})",
|
||||
per_step(old[RUNS / 2], OLD_STEPS),
|
||||
per_step(old[0], OLD_STEPS),
|
||||
per_step(old[RUNS - 1], OLD_STEPS),
|
||||
per_step(new[RUNS / 2], NEW_STEPS),
|
||||
per_step(new[0], NEW_STEPS),
|
||||
per_step(new[RUNS - 1], NEW_STEPS),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value {
|
||||
|
||||
fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "graphicStyle.redefine";
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
// The style to replace, its new look, and the object that look comes from (none for another style's look).
|
||||
let (i, look, src) = match p.get("from") {
|
||||
Some(from) => {
|
||||
let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?;
|
||||
if p.get("id").is_some() {
|
||||
return Err(bad(cmd, "pass `id` or `from`, not both"));
|
||||
}
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (i, j) = (style_index(d, name)?, style_index(d, from)?);
|
||||
// A style dropped on itself, or on a style with the same look, stays as it is.
|
||||
let target = &d.graphic_styles[i];
|
||||
let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() };
|
||||
if i == j || look == *target {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
(i, look, None)
|
||||
}
|
||||
None => {
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
};
|
||||
(i, GraphicStyle::of(String::new(), captured(n), n), Some(src))
|
||||
}
|
||||
};
|
||||
let look = GraphicStyle::of(String::new(), captured(n), n);
|
||||
let name = d.graphic_styles[i].name.clone();
|
||||
let name = s.doc()?.doc.graphic_styles[i].name.clone();
|
||||
let chars = s.prefs.override_char_color;
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
@@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
@@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
@@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
if let Some(src) = src {
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
@@ -314,12 +314,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds
|
||||
/// instances of?
|
||||
fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
|
||||
/// Does `n` hold an instance of symbol `name` (opacity masks included), directly or through the art
|
||||
/// of the symbols it holds instances of?
|
||||
pub(crate) fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet<String>) -> bool {
|
||||
let mut found = false;
|
||||
let mut nested = vec![];
|
||||
n.walk(&mut |c| {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
if symbol == name {
|
||||
found = true;
|
||||
|
||||
@@ -522,14 +522,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// The fill of `[Normal Character Style]` in `d`: black, or the fill a redefinition gave it. New
|
||||
/// type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html):
|
||||
/// new type's defaults are changed by editing it), so it takes this fill, not the current fill
|
||||
/// left from the last shape (#7975).
|
||||
pub(crate) fn normal_char_fill(d: &Document) -> vectorcraft_color::Paint {
|
||||
/// `[Normal Character Style]` in `d`: the defaults, with whatever a redefinition gave it (font,
|
||||
/// size, fill…). New type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html):
|
||||
/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html)
|
||||
/// and [Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html):
|
||||
/// new type's defaults, its font included, are changed by editing it), so it takes this style's
|
||||
/// font and fill, not the current fill left from the last shape (#7975). Attributes that don't
|
||||
/// pass its checks leave the defaults.
|
||||
pub(crate) fn normal_char_style(d: &Document) -> CharStyle {
|
||||
let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill)
|
||||
with_attrs(&CharStyle::default(), &normal, "text.create").unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
|
||||
@@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the
|
||||
/// thread as it was: every frame stays a frame of the thread with the text it holds, and the
|
||||
/// symbol's art holds a copy of the text the frame shows.
|
||||
#[test]
|
||||
fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() {
|
||||
for command in ["symbol.new", "symbol.update"] {
|
||||
let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0);
|
||||
let shown = frames.map(|id| text(&s, id));
|
||||
let name = if command == "symbol.update" {
|
||||
let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
"Mark"
|
||||
} else {
|
||||
"Story"
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap();
|
||||
let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap();
|
||||
assert!(r["id"].is_null(), "{command}: {r}");
|
||||
assert_eq!(threads(&s), [frames], "{command}: the thread is as it was");
|
||||
assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text");
|
||||
assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows");
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the
|
||||
/// mask art too.
|
||||
#[test]
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -325,27 +325,39 @@ pub struct ColorTable {
|
||||
pub web_shift: Vec<String>,
|
||||
#[serde(serialize_with = "ser_key", deserialize_with = "de_key")]
|
||||
pub sort: ColorSort,
|
||||
/// Taken out of the table: their pixels take the nearest color left. A deleted color is no
|
||||
/// longer locked, transparent or web-shifted.
|
||||
pub deleted: Vec<String>,
|
||||
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
|
||||
/// table when the first color was deleted. Empty: the reduction makes the palette.
|
||||
pub custom_palette: Vec<String>,
|
||||
}
|
||||
|
||||
/// The most colours a colour table list holds.
|
||||
const MAX_TABLE: usize = 256;
|
||||
|
||||
/// The error for a deletion that would leave the color table no color for the pixels.
|
||||
pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table";
|
||||
|
||||
impl ColorTable {
|
||||
/// Whether the table is a Custom one: a color was deleted or the palette is fixed.
|
||||
pub fn is_custom(&self) -> bool {
|
||||
!self.deleted.is_empty() || !self.custom_palette.is_empty()
|
||||
}
|
||||
|
||||
fn colors(list: &[String], what: &str) -> std::result::Result<Vec<[u8; 3]>, String> {
|
||||
if list.len() > MAX_TABLE {
|
||||
return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours"));
|
||||
}
|
||||
list.iter()
|
||||
.map(|h| {
|
||||
vectorcraft_color::Color::from_hex(h)
|
||||
.filter(|_| !super::hex_with_alpha(h))
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
.ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))
|
||||
})
|
||||
.collect()
|
||||
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
|
||||
}
|
||||
|
||||
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
|
||||
fn rgb(h: &str) -> Option<[u8; 3]> {
|
||||
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,7 +457,13 @@ impl WebSettings {
|
||||
}
|
||||
}
|
||||
}
|
||||
let s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
|
||||
let mut s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?;
|
||||
// Another reduction makes a new palette: the deletions and the fixed palette go, unless
|
||||
// the params give the color table too.
|
||||
if p.get("reduction").is_some() && p.get("colorTable").is_none() && s.reduction != self.reduction {
|
||||
s.color_table.deleted.clear();
|
||||
s.color_table.custom_palette.clear();
|
||||
}
|
||||
s.checked()
|
||||
}
|
||||
|
||||
@@ -463,11 +481,19 @@ impl WebSettings {
|
||||
return Err("width and height are at least 1 pixel".into());
|
||||
}
|
||||
self.matte_rgb()?;
|
||||
let table = &mut self.color_table;
|
||||
for (list, what) in
|
||||
[(&self.color_table.locked, "locked"), (&self.color_table.transparent, "transparent"), (&self.color_table.web_shift, "webShift")]
|
||||
[(&table.locked, "locked"), (&table.transparent, "transparent"), (&table.web_shift, "webShift"), (&table.custom_palette, "customPalette")]
|
||||
{
|
||||
ColorTable::colors(list, what)?;
|
||||
}
|
||||
// A deleted color is no longer locked, transparent or web-shifted.
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
if !deleted.is_empty() {
|
||||
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
|
||||
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -741,7 +767,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
};
|
||||
let mut ix = quantize::quantize_locked(rgba, w, h, &o, &locked);
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
let before = ix.palette.clone();
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
@@ -789,6 +815,45 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
Ok(PaletteImage { ix, colors, mapped })
|
||||
}
|
||||
|
||||
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
|
||||
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
|
||||
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
|
||||
/// transparent.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
let custom = ColorTable::colors(&table.custom_palette, "customPalette")?;
|
||||
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
|
||||
let opaque_left = |left: &[[u8; 3]]| left.iter().any(|c| !to_clear.contains(c));
|
||||
if custom.is_empty() {
|
||||
let ix = quantize::quantize_locked(rgba, w, h, o, locked);
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c);
|
||||
if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) {
|
||||
return Ok(ix);
|
||||
}
|
||||
let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect();
|
||||
if left.is_empty() || !opaque_left(&left) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &left));
|
||||
}
|
||||
// A fixed palette holds at most `colors` entries, the transparent one included.
|
||||
let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128);
|
||||
let removed = custom.iter().any(|c| deleted.contains(c));
|
||||
let mut left: Vec<[u8; 3]> = vec![];
|
||||
for c in custom {
|
||||
if !deleted.contains(&c) && !left.contains(&c) {
|
||||
left.push(c);
|
||||
}
|
||||
}
|
||||
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
|
||||
if left.is_empty() || (removed && !opaque_left(&left)) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
Ok(quantize::quantize_to(rgba, w, h, o, &left))
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
pub fn decode(o: &Optimized) -> std::result::Result<(Vec<u8>, u32, u32), String> {
|
||||
let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?;
|
||||
|
||||
@@ -415,7 +415,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::PreviewCopies;
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, Prefs};
|
||||
pub use prefs::{DrawMode, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -10,6 +10,26 @@ pub enum DrawMode {
|
||||
Inside,
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run
|
||||
/// may use ([`vectorcraft_plugins::Plugin::large_limits`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PluginBudget {
|
||||
/// The plug-in's own limits.
|
||||
#[default]
|
||||
Normal,
|
||||
/// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of
|
||||
/// input; the time budget is unchanged.
|
||||
Large,
|
||||
}
|
||||
|
||||
/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the
|
||||
/// other preferences are read as they are.
|
||||
fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<PluginBudget, D::Error> {
|
||||
let saved = <Value as serde::Deserialize>::deserialize(d)?;
|
||||
Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal })
|
||||
}
|
||||
|
||||
/// A saved Default Language as its tag: older preferences hold the language's name, and one the list
|
||||
/// no longer has reads as the default.
|
||||
fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
|
||||
@@ -29,6 +49,12 @@ pub struct Prefs {
|
||||
pub constrain_angle: f64,
|
||||
pub corner_radius: f64,
|
||||
pub disable_auto_add_delete: bool,
|
||||
/// General › Interpolate Control Points When Moving Anchors: the default of the `interpolate`
|
||||
/// param of the commands that move direct-selected anchors (a Direct Selection drag, the arrow
|
||||
/// keys, Move, Transform Again). On, the handles of each segment with one moved end are
|
||||
/// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the
|
||||
/// default), the handles of a moved anchor move with it and the other handles stay.
|
||||
pub interpolate_control_points: bool,
|
||||
pub use_precise_cursors: bool,
|
||||
pub show_tool_tips: bool,
|
||||
/// Other Script… warns before it runs a chosen script.
|
||||
@@ -173,6 +199,11 @@ pub struct Prefs {
|
||||
pub fonts_folder: String,
|
||||
// Plug-ins & Scratch Disks
|
||||
pub plugins_folder: String,
|
||||
/// Plug-in Instruction Budget: the instructions each object filter run gets, from
|
||||
/// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers
|
||||
/// keep their own budgets.
|
||||
#[serde(deserialize_with = "plugin_budget")]
|
||||
pub plugin_instruction_budget: PluginBudget,
|
||||
pub scratch_primary: String,
|
||||
pub scratch_secondary: String,
|
||||
// User Interface
|
||||
@@ -397,6 +428,7 @@ impl Default for Prefs {
|
||||
constrain_angle: 0.0,
|
||||
corner_radius: 12.0,
|
||||
disable_auto_add_delete: false,
|
||||
interpolate_control_points: false,
|
||||
use_precise_cursors: false,
|
||||
show_tool_tips: true,
|
||||
show_external_script_warning: true,
|
||||
@@ -489,6 +521,7 @@ impl Default for Prefs {
|
||||
hyphenation_exceptions: String::new(),
|
||||
fonts_folder: String::new(),
|
||||
plugins_folder: String::new(),
|
||||
plugin_instruction_budget: PluginBudget::Normal,
|
||||
scratch_primary: s("Startup"),
|
||||
scratch_secondary: s("None"),
|
||||
ui_brightness: s("mediumDark"),
|
||||
|
||||
@@ -442,8 +442,10 @@ impl Session {
|
||||
// selected): Transform Again moves the selected anchors and the objects selected whole
|
||||
// by the same distance. A drag that ends where it began leaves the last transform.
|
||||
let mut options = serde_json::json!({ "copy": false });
|
||||
if let Some(patterns) = preview.1.get("patterns") {
|
||||
options["patterns"] = patterns.clone();
|
||||
for key in ["patterns", "interpolate"] {
|
||||
if let Some(v) = preview.1.get(key) {
|
||||
options[key] = v.clone();
|
||||
}
|
||||
}
|
||||
st.last_transform = Some(LastTransform::Matrix(vectorcraft_geom::Affine::translate(moved), options));
|
||||
st.last_perspective = None;
|
||||
|
||||
@@ -85,6 +85,7 @@ mod history_mem;
|
||||
mod ids_without_selection;
|
||||
mod inline;
|
||||
mod interactivity;
|
||||
mod interpolate_handles;
|
||||
mod intertwine;
|
||||
mod journal;
|
||||
mod keyanchor;
|
||||
@@ -3219,6 +3220,101 @@ fn every_command_has_unique_id_and_doc() {
|
||||
assert!(command_specs().iter().all(|c| !c.params.is_empty() && !c.label.is_empty()));
|
||||
}
|
||||
|
||||
/// Ids that name no built-in command: commands only the app runs, near misses of real ids and
|
||||
/// plug-in command ids of plug-ins that are not installed.
|
||||
const NOT_BUILT_IN: &[&str] =
|
||||
&["", "file.save", "file.open", "edit.preferences", "select", "select.none.", "SELECT.NONE", " select.none", "plugin.nobody.cmd", "plugin."];
|
||||
|
||||
/// The spec a search of the built-in list in order finds for `id`.
|
||||
fn first_built_in(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_command_finds_the_spec_a_search_of_the_list_finds() {
|
||||
let misses: Vec<String> = NOT_BUILT_IN.iter().map(|id| (*id).to_string()).chain((0..200).map(|i| format!("missing.command{i}"))).collect();
|
||||
for id in command_specs().iter().map(|c| c.id.to_string()).chain(misses) {
|
||||
let (found, first) = (find_command(&id), first_built_in(&id));
|
||||
assert!(found.map(std::ptr::from_ref) == first.map(std::ptr::from_ref), "{id:?}");
|
||||
assert_eq!(found.is_none(), NOT_BUILT_IN.contains(&id.as_str()) || id.starts_with("missing."), "{id:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_index_keeps_the_first_spec_of_an_id() {
|
||||
let base = &command_specs()[0];
|
||||
let specs = [
|
||||
CommandSpec { id: "test.twice", label: "First", ..*base },
|
||||
CommandSpec { id: "test.once", ..*base },
|
||||
CommandSpec { id: "test.twice", label: "Second", ..*base },
|
||||
];
|
||||
let index = crate::cmd::index_by_id(&specs);
|
||||
assert_eq!(index.len(), 2);
|
||||
assert!(index.get("test.twice").is_some_and(|c| std::ptr::eq(*c, &specs[0])));
|
||||
assert!(index.get("test.once").is_some_and(|c| std::ptr::eq(*c, &specs[1])));
|
||||
assert!(!index.contains_key("test.none"));
|
||||
}
|
||||
|
||||
/// Times [`find_command`] against a search of the built-in list in order (the lookup before the
|
||||
/// index), in one process, over every built-in id and 200 ids that name no command, and
|
||||
/// `select.none` run 100,000 times on a document with one rectangle.
|
||||
/// Run with `cargo test --release -p vectorcraft-engine --lib command_lookup_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn command_lookup_timing() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
let hits: Vec<&str> = command_specs().iter().map(|c| c.id).collect();
|
||||
let missing: Vec<String> = (0..200 - NOT_BUILT_IN.len()).map(|i| format!("missing.command{i}")).collect();
|
||||
let misses: Vec<&str> = NOT_BUILT_IN.iter().copied().chain(missing.iter().map(String::as_str)).collect();
|
||||
let linear = |id: &str| first_built_in(id).or_else(|| crate::cmd::plugin::find_spec(id));
|
||||
for id in hits.iter().chain(&misses) {
|
||||
assert!(find_command(id).map(std::ptr::from_ref) == linear(id).map(std::ptr::from_ref), "{id:?}");
|
||||
}
|
||||
let per_lookup = |ids: &[&str], f: &dyn Fn(&str) -> Option<&'static CommandSpec>| {
|
||||
let rounds = 50;
|
||||
let start = Instant::now();
|
||||
for _ in 0..rounds {
|
||||
for id in ids {
|
||||
black_box(f(black_box(id)));
|
||||
}
|
||||
}
|
||||
start.elapsed().as_nanos() as f64 / (rounds * ids.len()) as f64
|
||||
};
|
||||
let median = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!("{} built-in ids, {} ids that name no command", hits.len(), misses.len());
|
||||
for (what, ids) in [("built-in id", &hits), ("no such command", &misses)] {
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
for run in 0..7 {
|
||||
// Alternates which lookup goes first, so a change in machine load falls on both.
|
||||
if run % 2 == 0 {
|
||||
old.push(per_lookup(ids, &linear));
|
||||
new.push(per_lookup(ids, &find_command));
|
||||
} else {
|
||||
new.push(per_lookup(ids, &find_command));
|
||||
old.push(per_lookup(ids, &linear));
|
||||
}
|
||||
}
|
||||
println!("{what}: search of the list {old:.0?} ns, median {:.0}; index {new:.0?} ns, median {:.0}", median(old.clone()), median(new.clone()));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let runs: Vec<f64> = (0..7)
|
||||
.map(|_| {
|
||||
let start = Instant::now();
|
||||
for _ in 0..100_000 {
|
||||
black_box(s.execute("select.none", &json!({})).unwrap());
|
||||
}
|
||||
start.elapsed().as_nanos() as f64 / 100_000.0
|
||||
})
|
||||
.collect();
|
||||
println!("select.none: {runs:.0?} ns a command, median {:.0}", median(runs.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_survives_empty_params() {
|
||||
// Robustness: no command may panic on {} (with and without a selection).
|
||||
|
||||
@@ -1697,6 +1697,46 @@ fn brush_options_set_variation_modes() {
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": "Dots"})).unwrap()["modes"], modes);
|
||||
}
|
||||
|
||||
/// The fill colors of the copies brushed path `id` draws in `doc`, as `#rrggbb`.
|
||||
fn piece_fills(doc: &Document, id: NodeId) -> Vec<String> {
|
||||
let pieces = vectorcraft_brush::node_pieces(doc, doc.node(id).unwrap()).expect("brushed");
|
||||
pieces.iter().map(|n| n.appearance.fill_paint().color().unwrap().to_hex()).collect()
|
||||
}
|
||||
|
||||
/// Scatter Brush Options' `hue_jitter`: shown by `brush.get`, set by `brush.options`, saved with the
|
||||
/// document, and the turned colors drawn the same after Open and written by SVG export.
|
||||
#[test]
|
||||
fn scatter_hue_jitter_saves_and_exports() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let id = line(&mut s);
|
||||
select(&mut s, &[id]);
|
||||
s.execute("brush.apply", &json!({ "name": name })).unwrap();
|
||||
let plain = piece_fills(&s.doc().unwrap().doc, id);
|
||||
assert!(plain.len() > 10 && plain.iter().all(|c| c == "#ff0000"), "{plain:?}");
|
||||
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(0.0), "brush.get shows the option at 0");
|
||||
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 120}})).unwrap();
|
||||
assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(120.0));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let turned = piece_fills(&doc, id);
|
||||
assert_eq!(turned.len(), plain.len());
|
||||
let distinct: std::collections::HashSet<&String> = turned.iter().collect();
|
||||
assert!(distinct.len() > 5, "{turned:?}");
|
||||
// Saved and opened again, the stroke draws the same colors.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
assert_eq!(piece_fills(&back, id), turned);
|
||||
// SVG export writes each copy's turned color.
|
||||
let svg = vectorcraft_svg::export(&doc, &Default::default());
|
||||
for c in &distinct {
|
||||
assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG");
|
||||
}
|
||||
// Back to 0, the copies draw the art's own color.
|
||||
s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 0}})).unwrap();
|
||||
assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain);
|
||||
}
|
||||
|
||||
/// The bounds of the brush art `id`'s strokes draw.
|
||||
fn brushed_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
let st = s.doc().unwrap();
|
||||
@@ -2159,6 +2199,212 @@ fn break_link_then_update_redefines_all_instances() {
|
||||
assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Redefine Symbol with `keepArt: true` updates the symbol and its instances from the selection,
|
||||
/// and the selected art stays ordinary art in its place, with its ids, still selected; the result
|
||||
/// has no instance id. One undo step takes the definition back. Without `keepArt`, or with false,
|
||||
/// the art becomes an instance.
|
||||
#[test]
|
||||
fn redefine_with_keep_art_leaves_the_art_as_ordinary_art() {
|
||||
let mut s = session();
|
||||
let (inst, name, _) = make_symbol(&mut s);
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
|
||||
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
|
||||
let symbol_art = |s: &Session| s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
|
||||
let old_art = symbol_art(&s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute("symbol.update", &json!({"name": name, "keepArt": true})).unwrap();
|
||||
assert_eq!(r, json!({"name": name, "id": null}));
|
||||
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
|
||||
let instances = |s: &Session| {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
|
||||
n
|
||||
};
|
||||
assert_eq!(instances(&s), 1, "no new instance");
|
||||
// The instance shows the new art: the 120 × 50 pair.
|
||||
let w = bounds(&s, inst);
|
||||
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(symbol_art(&s), old_art, "undo takes the definition back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!((bounds(&s, inst).width() - 120.0).abs() < 1e-6, "{:?}", bounds(&s, inst));
|
||||
// false, like no keepArt, makes the art an instance.
|
||||
for p in [json!({"name": name, "ids": [a.0], "keepArt": false}), json!({"name": name, "ids": [b.0]})] {
|
||||
let r = s.execute("symbol.update", &p).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().expect("an instance id"));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
/// Redefine Symbol with `keepArt: true` and explicit ids keeps the named art selected only where
|
||||
/// it can be selected: locked or hidden art is left out. A `keepArt` that is not true or false is
|
||||
/// refused, with no change and no undo step.
|
||||
#[test]
|
||||
fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
|
||||
let mut s = session();
|
||||
let (_, name, _) = make_symbol(&mut s);
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
|
||||
{
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(locked).unwrap().locked = true;
|
||||
doc.node_mut(hidden).unwrap().visible = false;
|
||||
}
|
||||
for bad in [json!("true"), json!(1), json!([true])] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("symbol.update", &json!({"name": name, "ids": [a.0], "keepArt": bad})).unwrap_err();
|
||||
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
|
||||
}
|
||||
select(&mut s, &[]);
|
||||
s.execute("symbol.update", &json!({"name": name, "ids": [a.0, locked.0, hidden.0], "keepArt": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "only the selectable art is selected");
|
||||
for id in [a, locked, hidden] {
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of symbol instances in the document.
|
||||
fn instance_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
|
||||
n
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current
|
||||
/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the
|
||||
/// result has no instance id and nothing places the symbol. One undo step takes the symbol away
|
||||
/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
|
||||
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap();
|
||||
assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}");
|
||||
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
|
||||
assert_eq!(instance_count(&s), 0, "no instance");
|
||||
let list = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0)));
|
||||
// The symbol's art is the pair: an instance placed from it is 120 × 50.
|
||||
let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap());
|
||||
let w = bounds(&s, placed);
|
||||
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away");
|
||||
assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo");
|
||||
assert_eq!(instance_count(&s), 0, "redo places no instance");
|
||||
// false, like no keepArt, makes the art an instance.
|
||||
for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] {
|
||||
let r = s.execute("symbol.new", &p).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().expect("an instance id"));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it
|
||||
/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the
|
||||
/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and
|
||||
/// no undo step.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
|
||||
let mut s = session();
|
||||
let (inst, _, _) = make_symbol(&mut s);
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
|
||||
{
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(locked).unwrap().locked = true;
|
||||
doc.node_mut(hidden).unwrap().visible = false;
|
||||
}
|
||||
for bad in [json!("true"), json!(1), json!([true])] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err();
|
||||
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
|
||||
}
|
||||
select(&mut s, &[]);
|
||||
let symbols = s.doc().unwrap().doc.symbols.len();
|
||||
let ids = [a.0, locked.0, hidden.0, inst.0];
|
||||
s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1);
|
||||
let selected = &s.doc().unwrap().selection.objects;
|
||||
assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}");
|
||||
for id in [a, locked, hidden] {
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
|
||||
}
|
||||
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance");
|
||||
assert_eq!(instance_count(&s), 1, "no new instance");
|
||||
}
|
||||
|
||||
/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a
|
||||
/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and
|
||||
/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines
|
||||
/// it.
|
||||
#[test]
|
||||
fn redefine_refuses_art_holding_an_instance_of_the_symbol() {
|
||||
let mut s = session();
|
||||
let (inst, name, _) = make_symbol(&mut s);
|
||||
// Ring's art is an instance of Box.
|
||||
let ring = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "ids": [inst.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
let place =
|
||||
|s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()["id"].as_u64().unwrap());
|
||||
let direct = place(&mut s, 300.0);
|
||||
let plain = rect(&mut s, 20.0, 220.0, 30.0, 30.0);
|
||||
let grouped = place(&mut s, 100.0);
|
||||
// A rectangle whose opacity mask is a Box instance.
|
||||
let masked = rect(&mut s, 60.0, 260.0, 30.0, 30.0);
|
||||
let mut mask_art = node(&s, direct);
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
mask_art.id = doc.alloc_id();
|
||||
doc.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true)));
|
||||
let cases = [
|
||||
("a Box instance", vec![direct.0]),
|
||||
("Ring, whose art holds Box", vec![ring.0]),
|
||||
("art with a Box instance", vec![plain.0, grouped.0]),
|
||||
("art masked by a Box instance", vec![masked.0]),
|
||||
];
|
||||
for (case, ids) in cases {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("symbol.update", &json!({"name": name, "ids": ids})).unwrap_err();
|
||||
assert!(e.to_string().contains("can't hold an instance of itself"), "{case}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{case}: the document is unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{case}: no undo step");
|
||||
}
|
||||
// An instance of a symbol that does not hold Box redefines it.
|
||||
let dot = rect(&mut s, 200.0, 20.0, 10.0, 10.0);
|
||||
let dot = NodeId(s.execute("symbol.new", &json!({"name": "Dot", "ids": [dot.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
let r = s.execute("symbol.update", &json!({"name": name, "ids": [dot.0]})).unwrap();
|
||||
assert_eq!(r["name"], json!(name));
|
||||
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap();
|
||||
assert!(matches!(&art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{}", art.kind_label());
|
||||
}
|
||||
|
||||
/// A linked opacity mask of a 10 × 10 square at (100, 50).
|
||||
fn square_mask(s: &mut Session) -> Box<vectorcraft_doc::OpacityMask> {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
|
||||
@@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
|
||||
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
|
||||
}
|
||||
|
||||
/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115;
|
||||
/// the fill's shape is 9 pt larger on each side.
|
||||
fn image_with_shaped_fill(s: &mut Session) -> NodeId {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(s, "select.set", json!({"ids": [im.0]}));
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
im
|
||||
}
|
||||
|
||||
/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in
|
||||
/// outline with `outline`.
|
||||
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
|
||||
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
|
||||
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline)
|
||||
}
|
||||
|
||||
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
|
||||
/// art outside its box, as a click there selects it, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), []);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill");
|
||||
assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill");
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", false);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke");
|
||||
assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = nested_instance_with_row(&mut s);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art");
|
||||
}
|
||||
|
||||
/// A marquee touches an image where the shape of its own fill lies outside its frame, and an
|
||||
/// instance of a symbol made of that image where the instance's fill effect grows that shape, as
|
||||
/// clicks there select them, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_on_the_shape_of_an_image_fill_selects_it() {
|
||||
let mut s = session();
|
||||
let im = image_with_shaped_fill(&mut s);
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame");
|
||||
assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape");
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame");
|
||||
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill");
|
||||
assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill");
|
||||
}
|
||||
|
||||
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
|
||||
/// effect grows what that fill paints, and a click there selects the instance.
|
||||
#[test]
|
||||
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
|
||||
let mut s = session();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
// The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side.
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [im.0]}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
image_with_shaped_fill(&mut s);
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
//! #7832: General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`).
|
||||
//! With it on, a Direct Selection drag or an arrow-key nudge of selected anchors re-maps the
|
||||
//! handles of each segment with one moved end, so the segment keeps its shape relative to its
|
||||
//! ends. Off (the default), the handles of a moved anchor move with it and the others stay.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point};
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use super::history;
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn interpolate(s: &mut Session, on: bool) {
|
||||
s.execute("prefs.set", &json!({"key": "interpolateControlPoints", "value": on})).unwrap();
|
||||
}
|
||||
|
||||
fn path_of(s: &Session, id: NodeId) -> PathData {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
}
|
||||
|
||||
fn anchor(s: &Session, id: NodeId, ai: usize) -> Anchor {
|
||||
path_of(s, id).subpaths[0].anchors[ai]
|
||||
}
|
||||
|
||||
fn create(s: &mut Session, anchors: serde_json::Value) -> NodeId {
|
||||
NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A curve from (100, 100) to (300, 100) whose handles lie on its chord.
|
||||
fn curve(s: &mut Session) -> NodeId {
|
||||
create(s, json!([{"x": 100, "y": 100, "out": [150, 100]}, {"x": 300, "y": 100, "in": [250, 100]}]))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value) {
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": "set"})).unwrap();
|
||||
}
|
||||
|
||||
/// A Direct Selection click on (`x`, `y`), then a drag from there to (`to_x`, `to_y`).
|
||||
fn drag(s: &mut Session, (x, y): (f64, f64), (to_x, to_y): (f64, f64)) {
|
||||
let v = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, to_x, to_y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, to_x, to_y), v).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preference_is_off_by_default_and_the_handles_then_move_rigidly() {
|
||||
let mut s = session();
|
||||
assert!(!s.prefs.interpolate_control_points);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!(a.p, Point::new(120.0, 108.0));
|
||||
assert_eq!(a.h_out, Point::new(170.0, 108.0), "the moved anchor's handle moves with it");
|
||||
assert_eq!(b.h_in, Point::new(250.0, 100.0), "the other end's handle stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let before = history(&s).0;
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
assert_eq!(history(&s).0, before + 1, "one undo step");
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
// The chord goes from (200, 0) to (180, -8): a scale by 0.9 and a turn, so the handles a
|
||||
// quarter of the way from each end stay on the new chord, a quarter of the way along it.
|
||||
assert_eq!(a.p, Point::new(120.0, 108.0));
|
||||
assert_eq!(a.h_in, a.p, "a retracted handle stays retracted");
|
||||
assert_eq!(a.h_out, Point::new(165.0, 106.0));
|
||||
assert_eq!(b.p, Point::new(300.0, 100.0));
|
||||
assert_eq!(b.h_in, Point::new(255.0, 102.0));
|
||||
assert_eq!(b.h_out, b.p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
let original = path_of(&s, id);
|
||||
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!(a.p, Point::new(120.0, 108.0));
|
||||
assert_eq!(a.h_out, Point::new(165.0, 106.0));
|
||||
assert_eq!(b.h_in, Point::new(255.0, 102.0));
|
||||
// One undo step puts the path back as it was before the drag.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path_of(&s, id), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_selection_drag_with_the_preference_off_keeps_the_rigid_move() {
|
||||
let mut s = session();
|
||||
let id = curve(&mut s);
|
||||
drag(&mut s, (100.0, 100.0), (120.0, 108.0));
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!(a.h_out, Point::new(170.0, 108.0));
|
||||
assert_eq!(b.h_in, Point::new(250.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_with_both_ends_moved_moves_rigidly() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 100, "y": 100, "out": [150, 60]},
|
||||
{"x": 300, "y": 100, "in": [250, 60], "out": [350, 150]},
|
||||
{"x": 500, "y": 100, "in": [450, 140]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 0], [0, 1]]));
|
||||
s.execute("object.nudge", &json!({"dx": 10, "dy": 5})).unwrap();
|
||||
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
|
||||
assert_eq!((a.p, a.h_out), (Point::new(110.0, 105.0), Point::new(160.0, 65.0)));
|
||||
assert_eq!((b.p, b.h_in), (Point::new(310.0, 105.0), Point::new(260.0, 65.0)));
|
||||
// The segment to the unmoved third anchor is re-mapped: its chord goes from (200, 0) to
|
||||
// (190, -5), a scale by 0.95 with a turn of -0.025 per unit.
|
||||
close(b.h_out, Point::new(358.75, 151.25));
|
||||
close(c.h_in, Point::new(453.5, 139.25));
|
||||
assert_eq!(c.p, Point::new(500.0, 100.0));
|
||||
}
|
||||
|
||||
fn close(p: Point, q: Point) {
|
||||
assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} is not {q:?}");
|
||||
}
|
||||
|
||||
/// A closed square from (100, 100) to (300, 300) whose handles lie on its sides, a quarter of
|
||||
/// the way along.
|
||||
fn square(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([
|
||||
{"x": 100, "y": 100, "in": [100, 150], "out": [150, 100]},
|
||||
{"x": 300, "y": 100, "in": [250, 100], "out": [300, 150]},
|
||||
{"x": 300, "y": 300, "in": [300, 250], "out": [250, 300]},
|
||||
{"x": 100, "y": 300, "in": [150, 300], "out": [100, 250]},
|
||||
]);
|
||||
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_first_anchor_of_a_closed_path_re_maps_the_closing_segment_too() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = square(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": -200})).unwrap();
|
||||
let (a, b, c, d) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2), anchor(&s, id, 3));
|
||||
assert_eq!(a.p, Point::new(100.0, -100.0));
|
||||
// The segment to the second anchor: its chord goes from (200, 0) to (200, 200).
|
||||
close(a.h_out, Point::new(150.0, -50.0));
|
||||
close(b.h_in, Point::new(250.0, 50.0));
|
||||
// The closing segment from the fourth anchor: its chord goes from (0, -200) to (0, -400).
|
||||
close(d.h_out, Point::new(100.0, 200.0));
|
||||
close(a.h_in, Point::new(100.0, 0.0));
|
||||
// The segment between the third and fourth anchors is not beside the moved anchor.
|
||||
assert_eq!((c.h_out, d.h_in), (Point::new(250.0, 300.0), Point::new(150.0, 300.0)));
|
||||
assert_eq!((b.h_out, c.h_in), (Point::new(300.0, 150.0), Point::new(300.0, 250.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_last_anchor_of_an_open_path_re_maps_only_the_segment_before_it() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 100, "y": 100, "out": [150, 100]},
|
||||
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 50]},
|
||||
{"x": 500, "y": 100, "in": [450, 100], "out": [550, 50]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 2]]));
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": 200})).unwrap();
|
||||
let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2));
|
||||
assert_eq!(c.p, Point::new(500.0, 300.0));
|
||||
// The chord from the second (corner) anchor goes from (200, 0) to (200, 200).
|
||||
close(b.h_out, Point::new(400.0, 100.0));
|
||||
close(c.h_in, Point::new(450.0, 250.0));
|
||||
// The last anchor's own outgoing handle leads to no segment and moves with it.
|
||||
assert_eq!(c.h_out, Point::new(550.0, 250.0));
|
||||
assert_eq!((a.h_out, b.h_in), (Point::new(150.0, 100.0), Point::new(250.0, 100.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_transform_of_anchors_re_map_the_handles_in_one_undo_step() {
|
||||
for (cmd, params) in [("object.move", json!({"dx": 20, "dy": 8})), ("object.transform", json!({"matrix": [1, 0, 0, 1, 20, 8], "anchors": true}))]
|
||||
{
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let (before, original) = (history(&s).0, path_of(&s, id));
|
||||
s.execute(cmd, ¶ms).unwrap();
|
||||
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
|
||||
close(a.h_out, Point::new(165.0, 106.0));
|
||||
close(b.h_in, Point::new(255.0, 102.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_and_guide_move_of_anchors_follow_the_preference_and_the_param() {
|
||||
for (pref, param, re_mapped) in [(false, None, false), (true, None, true), (true, Some(false), false), (false, Some(true), true)] {
|
||||
for cmd in ["object.setBounds", "guide.move"] {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, pref);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let mut params = if cmd == "object.setBounds" {
|
||||
json!({"x": 120, "y": 108})
|
||||
} else {
|
||||
let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [g], "toggle": true})).unwrap();
|
||||
json!({"dx": 20, "dy": 8})
|
||||
};
|
||||
if let Some(on) = param {
|
||||
params["interpolate"] = json!(on);
|
||||
}
|
||||
let (before, original) = (history(&s).0, path_of(&s, id));
|
||||
s.execute(cmd, ¶ms).unwrap();
|
||||
assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step");
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}");
|
||||
if re_mapped {
|
||||
close(a.h_out, Point::new(165.0, 106.0));
|
||||
close(b.h_in, Point::new(255.0, 102.0));
|
||||
} else {
|
||||
assert_eq!((a.h_out, b.h_in), (Point::new(170.0, 108.0), Point::new(250.0, 100.0)), "{cmd}, pref {pref}, param {param:?}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path_of(&s, id), original, "{cmd}: undone");
|
||||
}
|
||||
}
|
||||
let mut s = session();
|
||||
let id = curve(&mut s);
|
||||
// Both anchors, so that a new width scales them and does not only move them.
|
||||
select(&mut s, id, json!([[0, 0], [0, 1]]));
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
|
||||
let original = path_of(&s, id);
|
||||
for (cmd, params) in [
|
||||
("object.setBounds", json!({"x": 120, "interpolate": "yes"})),
|
||||
("object.setBounds", json!({"width": 50, "interpolate": 1})),
|
||||
("guide.move", json!({"dx": 1, "interpolate": "yes"})),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
|
||||
}
|
||||
assert_eq!(path_of(&s, id), original);
|
||||
// With only guides selected, guide.move rejects the value too and leaves the guide.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
let e = s.execute("guide.move", &json!({"dx": 1, "interpolate": "yes"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`interpolate` must be true or false"), "guide.move: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_interpolate_param_overrides_the_preference_and_rejects_other_values() {
|
||||
for (pref, param, re_mapped) in [(true, false, false), (false, true, true)] {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, pref);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("path.moveAnchors", &json!({"dx": 20, "dy": 8, "interpolate": param})).unwrap();
|
||||
let b = anchor(&s, id, 1);
|
||||
assert_eq!(b.h_in != Point::new(250.0, 100.0), re_mapped, "pref {pref}, param {param}: {:?}", b.h_in);
|
||||
}
|
||||
let mut s = session();
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let original = path_of(&s, id);
|
||||
for (cmd, params) in [
|
||||
("path.moveAnchors", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
|
||||
("object.nudge", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
|
||||
("object.move", json!({"dx": 1, "dy": 0, "interpolate": "yes"})),
|
||||
("object.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "anchors": true, "interpolate": 1})),
|
||||
("object.transformAgain", json!({"interpolate": "yes"})),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}");
|
||||
}
|
||||
assert_eq!(path_of(&s, id), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replayed_move_re_maps_the_handles_as_it_did_whatever_the_preference_is_then() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let start = s.journal.len();
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
let moved = path_of(&s, id);
|
||||
let (cmd, params) = s.journal.since(start).last().cloned().unwrap();
|
||||
assert_eq!(params["interpolate"], json!(true), "{cmd}: journaled");
|
||||
// Undo, turn the preference off and play the journal entry again.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
interpolate(&mut s, false);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.replay(&cmd, ¶ms).unwrap();
|
||||
assert_eq!(path_of(&s, id), moved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_step_without_interpolate_moves_the_handles_rigidly_whatever_the_preference() {
|
||||
// A step recorded before the preference existed has no `interpolate`; with the preference on,
|
||||
// it still plays as it did when it was recorded.
|
||||
for cmd in ["path.moveAnchors", "object.nudge", "object.move"] {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.replay(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_ne!(a.p, Point::new(100.0, 100.0), "{cmd}: the anchor moves");
|
||||
assert_eq!((a.h_out.x - a.p.x, a.h_out.y - a.p.y), (50.0, 0.0), "{cmd}: the moved anchor's handle moves with it");
|
||||
assert_eq!(b.h_in, Point::new(250.0, 100.0), "{cmd}: the other end's handle stays");
|
||||
// Run directly, the same params follow the preference.
|
||||
s.execute(cmd, &json!({"dx": 1, "dy": 1})).unwrap();
|
||||
assert_ne!(anchor(&s, id, 1).h_in, Point::new(250.0, 100.0), "{cmd}: executed, the handles are re-mapped");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_again_keeps_the_setting_its_move_used() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
interpolate(&mut s, false);
|
||||
s.execute("object.transformAgain", &json!({})).unwrap();
|
||||
let mut t = session();
|
||||
interpolate(&mut t, true);
|
||||
let other = curve(&mut t);
|
||||
select(&mut t, other, json!([[0, 0]]));
|
||||
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
assert_eq!(path_of(&s, id), path_of(&t, other));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_whose_ends_are_at_the_same_place_moves_rigidly() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(&mut s, json!([{"x": 100, "y": 100, "out": [150, 50]}, {"x": 100, "y": 100, "in": [50, 150]}]));
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 10, "dy": 0})).unwrap();
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!((a.p, a.h_out), (Point::new(110.0, 100.0), Point::new(160.0, 50.0)));
|
||||
assert_eq!((b.p, b.h_in), (Point::new(100.0, 100.0), Point::new(50.0, 150.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_onto_the_other_end_moves_the_handles_rigidly() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 200, "dy": 0})).unwrap();
|
||||
let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1));
|
||||
assert_eq!((a.p, a.h_out), (Point::new(300.0, 100.0), Point::new(350.0, 100.0)));
|
||||
assert_eq!(b.h_in, Point::new(250.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nudge_of_zero_with_the_preference_on_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let (before, original) = (history(&s), path_of(&s, id));
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": 0})).unwrap();
|
||||
assert_eq!(history(&s), before);
|
||||
assert_eq!(path_of(&s, id), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_smooth_anchor_keeps_its_handles_in_line() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 100, "y": 100, "out": [150, 100]},
|
||||
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
|
||||
{"x": 500, "y": 100, "in": [450, 100]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
|
||||
let b = anchor(&s, id, 1);
|
||||
assert_eq!(b.p, Point::new(300.0, 100.0));
|
||||
// The segment to the third anchor did not move, so its handle stays where it was.
|
||||
assert_eq!(b.h_out, Point::new(350.0, 100.0));
|
||||
// The incoming handle grows with the chord from the moved anchor (from 200 to 100√5) and
|
||||
// turns back in line with the outgoing one.
|
||||
assert_eq!(b.h_in.y, 100.0, "in line: {:?}", b.h_in);
|
||||
assert!((300.0 - b.h_in.x - 25.0 * 5f64.sqrt()).abs() < 1e-9, "{:?}", b.h_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_smooth_anchor_keeps_a_retracted_handle_exactly_retracted() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 0, "y": 100, "out": [50, 100]},
|
||||
{"x": 200, "y": 100, "in": [200, 100], "out": [250, 150], "smooth": true},
|
||||
{"x": 400, "y": 100, "in": [350, 100]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 1]]));
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8.1})).unwrap();
|
||||
let b = anchor(&s, id, 1);
|
||||
assert_eq!(b.p, Point::new(220.0, 108.1));
|
||||
// Re-mapping the retracted handle by its segment's map would leave it a rounding error away
|
||||
// from the anchor, and lining the handles up would then turn the outgoing one by that error.
|
||||
assert_eq!(b.h_in, b.p, "the retracted handle stays retracted");
|
||||
// The chord to the third anchor goes from (200, 0) to (180, -8.1).
|
||||
close(b.h_out, Point::new(267.025, 151.075));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_again_repeats_a_move_with_the_handles_re_mapped() {
|
||||
let twice = |again: bool| {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
if again {
|
||||
s.execute("object.transformAgain", &json!({})).unwrap();
|
||||
} else {
|
||||
s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap();
|
||||
}
|
||||
path_of(&s, id)
|
||||
};
|
||||
let (repeated, nudged) = (twice(true), twice(false));
|
||||
assert_eq!(repeated.subpaths[0].anchors[0].p, Point::new(140.0, 116.0));
|
||||
assert_eq!(repeated, nudged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_that_scales_by_a_hair_still_scales_the_anchors() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = curve(&mut s);
|
||||
select(&mut s, id, json!([[0, 0]]));
|
||||
let k = 1.000_000_000_5;
|
||||
s.execute("object.transform", &json!({"matrix": [k, 0, 0, 1, 0, 0], "anchors": true})).unwrap();
|
||||
let a = anchor(&s, id, 0);
|
||||
assert_eq!(a.p, Point::new(100.0 * k, 100.0));
|
||||
assert_eq!(a.h_out, Point::new(150.0 * k, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_smooth_anchor_whose_re_mapped_handles_point_the_same_way_moves_them_with_it() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 100, "y": 100, "out": [150, 100]},
|
||||
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
|
||||
{"x": 500, "y": 100, "in": [450, 100]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 1]]));
|
||||
s.execute("object.nudge", &json!({"dx": 300, "dy": 0})).unwrap();
|
||||
// Both chords re-map their handle to the left of the anchor, which has no direction between
|
||||
// them: both handles move with the anchor, as with the preference off.
|
||||
let b = anchor(&s, id, 1);
|
||||
assert_eq!(b.p, Point::new(600.0, 100.0));
|
||||
assert_eq!(b.h_out, Point::new(650.0, 100.0));
|
||||
assert_eq!(b.h_in, Point::new(550.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_smooth_anchor_between_two_re_mapped_segments_keeps_its_handles_in_line() {
|
||||
let mut s = session();
|
||||
interpolate(&mut s, true);
|
||||
let id = create(
|
||||
&mut s,
|
||||
json!([
|
||||
{"x": 100, "y": 100, "out": [150, 100]},
|
||||
{"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true},
|
||||
{"x": 500, "y": 100, "in": [450, 100]},
|
||||
]),
|
||||
);
|
||||
select(&mut s, id, json!([[0, 1]]));
|
||||
s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap();
|
||||
let b = anchor(&s, id, 1);
|
||||
let (v_in, v_out) = (b.h_in - b.p, b.h_out - b.p);
|
||||
assert_eq!(b.p, Point::new(300.0, 0.0));
|
||||
// The two chords turn by the same angle in opposite directions, so the handles point along
|
||||
// the mean of the two: across, at the length each chord gives them.
|
||||
assert!(v_in.cross(v_out).abs() < 1e-9, "the handles stay in line: {:?} {:?}", b.h_in, b.h_out);
|
||||
assert!(v_in.dot(v_out) < 0.0, "on opposite sides of the anchor");
|
||||
assert!(v_out.y.abs() < 1e-9 && v_out.x > 0.0, "{:?}", b.h_out);
|
||||
assert!((v_out.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9 && (v_in.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9);
|
||||
}
|
||||
@@ -392,6 +392,67 @@ fn an_ellipse_takes_pie_angles_and_inverts() {
|
||||
assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err());
|
||||
}
|
||||
|
||||
/// Constrain Pie Angle (`constrainPie`): a new Pie Start or End Angle moves the other angle by as
|
||||
/// much, so each selected ellipse keeps its own span, across 0° too; a whole ellipse stays whole;
|
||||
/// after Invert Pie the inverted span is kept; one undo step for all of them; the angle each
|
||||
/// already has records nothing; and `constrainPie` with both angles, with neither, with Invert Pie
|
||||
/// or as text is an error that changes nothing.
|
||||
#[test]
|
||||
fn constrain_pie_keeps_each_ellipses_span() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let [a, b, c] = [0, 100, 200].map(|y| id(s.execute("shape.ellipse", &json!({"x": 0, "y": y, "width": 200, "height": 80})).unwrap()));
|
||||
run(&mut s, json!({"ids": [a.0], "pieStart": 300, "pieEnd": 60}));
|
||||
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "pieEnd": 90}));
|
||||
let pies = |s: &Session| {
|
||||
[a, b, c].map(|i| match &s.doc().unwrap().doc.node(i).unwrap().kind {
|
||||
NodeKind::Path { live: Some(l), .. } => match &**l {
|
||||
LiveShape::Ellipse { pie, .. } => *pie,
|
||||
k => panic!("{k:?}"),
|
||||
},
|
||||
k => panic!("{k:?}"),
|
||||
})
|
||||
};
|
||||
let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9;
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let n = undo(&s);
|
||||
// 300° to 60° spans 120°, through 0°; 0° to 90° spans 90°; the third ellipse is whole.
|
||||
run(&mut s, json!({"ids": [a.0, b.0, c.0], "pieStart": 350, "constrainPie": true}));
|
||||
let [pa, pb, pc] = pies(&s);
|
||||
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
|
||||
assert!(near(pc, (350.0, 350.0)), "{pc:?}");
|
||||
assert_eq!(s.doc().unwrap().doc.node(c).unwrap().path_data().unwrap().anchor_count(), 4, "the whole ellipse stays whole");
|
||||
assert_eq!(undo(&s), n + 1, "one undo step");
|
||||
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 20, "constrainPie": true}));
|
||||
let [pa, pb, _] = pies(&s);
|
||||
assert!(near(pa, (260.0, 20.0)) && near(pb, (290.0, 20.0)), "{pa:?} {pb:?}");
|
||||
let n = undo(&s);
|
||||
run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 380, "constrainPie": true}));
|
||||
assert_eq!(undo(&s), n, "the end each already has: no undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let [pa, pb, _] = pies(&s);
|
||||
assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}");
|
||||
// Inverted, 80° to 350° spans 270°, and a linked edit keeps that.
|
||||
run(&mut s, json!({"ids": [b.0], "invertPie": true}));
|
||||
run(&mut s, json!({"ids": [b.0], "pieStart": 0, "constrainPie": true}));
|
||||
assert!(near(pies(&s)[1], (0.0, 270.0)), "{:?}", pies(&s)[1]);
|
||||
let before = (undo(&s), pies(&s));
|
||||
for (p, want) in [
|
||||
(json!({"ids": [b.0], "pieStart": 10, "pieEnd": 20, "constrainPie": true}), "needs one of"),
|
||||
(json!({"ids": [b.0], "constrainPie": true}), "needs one of"),
|
||||
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": true, "invertPie": true}), "needs one of"),
|
||||
(json!({"ids": [b.0], "pieStart": 10, "constrainPie": "yes"}), "`constrainPie` must be true or false"),
|
||||
] {
|
||||
let r = s.execute("object.setLiveShape", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}");
|
||||
assert_eq!((undo(&s), pies(&s)), before, "{p}");
|
||||
}
|
||||
// Off, each angle is set on its own, as before.
|
||||
run(&mut s, json!({"ids": [b.0], "pieStart": 90, "constrainPie": false}));
|
||||
assert!(near(pies(&s)[1], (90.0, 270.0)), "{:?}", pies(&s)[1]);
|
||||
}
|
||||
|
||||
/// Invert Pie and Make Sides Equal given as text or as another value that is not true or false are
|
||||
/// an error naming the key: the ellipse's pie, the polygon and the undo history stay as they were.
|
||||
/// True makes the change, and false and null leave the shape as it is.
|
||||
|
||||
@@ -745,6 +745,56 @@ fn the_profile_follows_the_preset_access_and_reset() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The first run's style of text object `id`.
|
||||
fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle {
|
||||
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).cloned().unwrap();
|
||||
let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { panic!("not type: {n:?}") };
|
||||
t.runs[0].style.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profiles_normal_character_style_is_the_default_font() {
|
||||
let (mut s, dir) = with_profiles("default-font");
|
||||
// The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt.
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"});
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
|
||||
// New type in a document from the profile takes the font, size and Character Alignment.
|
||||
s.execute("file.new", &json!({"preset": "A4"})).unwrap();
|
||||
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Serif"})).unwrap();
|
||||
assert!(made.get("warning").is_none(), "{made}");
|
||||
let st = first_run(&s, &made["id"]);
|
||||
assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Source Serif 4", "Regular", 9.0));
|
||||
assert_eq!(st.char_align, vectorcraft_doc::CharAlign::EmBoxBottom);
|
||||
// A font, size or Character Alignment given to the command still wins.
|
||||
let made = s
|
||||
.execute("text.create", &json!({"x": 20, "y": 80, "text": "Sans", "font": "Source Sans 3", "size": 14, "charAlign": "romanBaseline"}))
|
||||
.unwrap();
|
||||
let st = first_run(&s, &made["id"]);
|
||||
assert_eq!((st.font_family.as_str(), st.size, st.char_align), ("Source Sans 3", 14.0, vectorcraft_doc::CharAlign::RomanBaseline));
|
||||
// A family given alone starts in Regular, not the style's Bold, and without its axis settings.
|
||||
let attrs = json!({"font_style": "Bold", "fontAxes": {"wght": 700}});
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap();
|
||||
let made = s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Inter", "font": "Inter"})).unwrap();
|
||||
let st = first_run(&s, &made["id"]);
|
||||
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Inter", "Regular"));
|
||||
assert!(st.font_axes.is_empty(), "{:?}", st.font_axes);
|
||||
// A font of the style that isn't available is reported, as one given to the command is.
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"font_family": "No Such Family 7498"}})).unwrap();
|
||||
let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Missing"})).unwrap();
|
||||
assert!(made["warning"].as_str().is_some_and(|w| w.contains("No Such Family 7498")), "{made}");
|
||||
|
||||
// A document from a profile left as shipped starts type in the default font and size.
|
||||
s.execute("file.new", &json!({"profile": "Web"})).unwrap();
|
||||
let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Default"})).unwrap();
|
||||
let st = first_run(&s, &made["id"]);
|
||||
let default = vectorcraft_doc::CharStyle::default();
|
||||
assert_eq!((st.font_family, st.size), (default.font_family, default.size));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
|
||||
let (mut s, dir) = with_profiles("errors");
|
||||
|
||||
@@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
}
|
||||
|
||||
/// A confined request packages no linked file whose native document it can't read to check against
|
||||
/// its read roots: a PDF that needs a password to open, and a native document that doesn't load,
|
||||
/// even inside the roots. The package is refused before anything is written, with an error that
|
||||
/// names no file or folder. A PDF without editing data is copied, and the person's package copies
|
||||
/// every file.
|
||||
#[test]
|
||||
fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() {
|
||||
let home = Folder::new("package-unreadable-home");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let out = home.file("out");
|
||||
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = package(s, p.clone()).expect_err("refused");
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}");
|
||||
assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}");
|
||||
assert!(!std::path::Path::new(&out).exists(), "{p}");
|
||||
};
|
||||
let mut part = session();
|
||||
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
|
||||
std::fs::create_dir_all(home.0.join("art")).unwrap();
|
||||
let native = home.file("art/part.vectorcraft");
|
||||
let pdf = home.file("art/part.pdf");
|
||||
save(&mut part, &native);
|
||||
let pdf_of =
|
||||
|part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let editable = pdf_of(&mut part, json!({"format": "pdf"}));
|
||||
let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}}));
|
||||
assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data");
|
||||
let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false}));
|
||||
let poster = |placed: &str| {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
s
|
||||
};
|
||||
write(&pdf, &editable);
|
||||
let mut s = poster(&pdf);
|
||||
write(&pdf, &locked);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
// A package prepared in the confined request and written on another thread.
|
||||
let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap();
|
||||
let e =
|
||||
std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused");
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}");
|
||||
assert!(!std::path::Path::new(&out).exists());
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF listing the editing file without its data (`EF` renamed, the same length).
|
||||
let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF");
|
||||
let mut detached = editable.clone();
|
||||
detached[at..at + 3].copy_from_slice(b"/XF");
|
||||
assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved");
|
||||
write(&pdf, &detached);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF without editing data.
|
||||
write(&pdf, &plain);
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
std::fs::remove_dir_all(&out).unwrap();
|
||||
// A PDF whose attachments are too many to search to their end, with a readable editing file
|
||||
// listed before the ones left unsearched.
|
||||
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
|
||||
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
|
||||
write(&pdf, &cut);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A native document that doesn't load, rewritten or copied as it is.
|
||||
let mut s = poster(&native);
|
||||
write(&native, b"not a document");
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"folder": out, "relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
}
|
||||
|
||||
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
|
||||
/// whose second subtree has 70,000 nodes, more than are searched.
|
||||
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
|
||||
let name = vectorcraft_pdf::EDITING_FILE;
|
||||
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
|
||||
stream.extend_from_slice(native);
|
||||
stream.extend_from_slice(b"\nendstream");
|
||||
let objects = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
|
||||
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
|
||||
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
|
||||
stream,
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
|
||||
for at in &offsets {
|
||||
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
|
||||
@@ -430,6 +430,7 @@ fn set_live_shape_refuses_an_unknown_key() {
|
||||
json!({"id": 3, "radius": 5}),
|
||||
json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}),
|
||||
json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}),
|
||||
json!({"pieEnd": 90, "constrainPie": true}),
|
||||
json!({"ids": [3], "lineLength": 72, "lineAngle": 90}),
|
||||
json!({"items": null}),
|
||||
] {
|
||||
|
||||
@@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter
|
||||
/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as
|
||||
/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's
|
||||
/// larger budget stay as they are, and setting Normal again applies to the next run.
|
||||
#[test]
|
||||
fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let mut s = session();
|
||||
let id = "test.engine.largebudget";
|
||||
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string();
|
||||
// More steps than a light budget pays for, fewer than 5 times it.
|
||||
install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output));
|
||||
let p = json!({"id": id, "ids": []});
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"}));
|
||||
let light = vectorcraft_plugins::Limits::default();
|
||||
let large = FilterRun::prepare(&s, &p).unwrap().limits().clone();
|
||||
assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() });
|
||||
assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms));
|
||||
// Cancel still stops it, and it changes nothing.
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
let made = run(&mut s, "plugin.run", p.clone())["ids"].clone();
|
||||
assert_eq!(made.as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
|
||||
// A heavy filter keeps its larger budget with either choice.
|
||||
let heavy_id = "test.engine.largebudget.heavy";
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true}));
|
||||
let hp = json!({"id": heavy_id, "ids": []});
|
||||
for budget in ["large", "normal"] {
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget}));
|
||||
let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone();
|
||||
let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS);
|
||||
assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}");
|
||||
}
|
||||
|
||||
// Normal again: the next run runs out of instructions.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
|
||||
}
|
||||
|
||||
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
|
||||
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
|
||||
@@ -4511,9 +4564,10 @@ fn plugin_commands_are_registered_run_and_removed() {
|
||||
install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1));
|
||||
assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none());
|
||||
install_wat(&mut s, &grower(id));
|
||||
assert!(listed(&s, grow).is_some());
|
||||
assert!(listed(&s, grow).is_some() && crate::cmd::find_command(grow).is_some());
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none());
|
||||
assert!(crate::cmd::find_command(grow).is_none() && crate::cmd::find_command(tidy).is_none());
|
||||
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
|
||||
}
|
||||
|
||||
|
||||
@@ -464,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
|
||||
assert_eq!(s.prefs.gpu_preference, "automatic");
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or
|
||||
/// label, kept through a save and load, and reset with its category. Setting another value is an
|
||||
/// error that changes nothing; a saved value that is missing, unknown or of another type reads as
|
||||
/// Normal and leaves the other saved preferences as they are.
|
||||
#[test]
|
||||
fn plugin_instruction_budget_defaults_to_normal_and_validates() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal"));
|
||||
set_pref(&mut s, "pluginInstructionBudget", json!("Large"));
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large"));
|
||||
for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] {
|
||||
assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}");
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}");
|
||||
}
|
||||
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
|
||||
assert_eq!(back.plugin_instruction_budget, PluginBudget::Large);
|
||||
let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")];
|
||||
let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v}));
|
||||
for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) {
|
||||
let read: Prefs = serde_json::from_value(saved.clone()).unwrap();
|
||||
assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}");
|
||||
}
|
||||
let l = s.execute("prefs.list", &json!({})).unwrap();
|
||||
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone();
|
||||
assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins")));
|
||||
assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large")));
|
||||
s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
}
|
||||
|
||||
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
|
||||
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
|
||||
/// reset with it.
|
||||
|
||||
@@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() {
|
||||
assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance));
|
||||
}
|
||||
|
||||
/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id,
|
||||
/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as
|
||||
/// they are, in one undo step. A style replaced by itself or by a style with the same look records
|
||||
/// nothing, and bad parameters are errors that change nothing.
|
||||
#[test]
|
||||
fn redefine_from_a_style_gives_the_style_that_look() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = linked_three(&mut s);
|
||||
let d = rect(&mut s, 300.0);
|
||||
set_fill(&mut s, d, "#0000ff");
|
||||
run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
|
||||
set_fill(&mut s, c, "#00ff00");
|
||||
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s));
|
||||
assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S");
|
||||
assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() });
|
||||
assert_eq!(names(&s), order);
|
||||
let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for id in [a, b] {
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply));
|
||||
}
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
// The edited object keeps its look and is unlinked; Blue and its object are as they were.
|
||||
assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap()));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, None);
|
||||
assert_eq!(style(&s, "Blue"), blue);
|
||||
assert_eq!(linked(&mut s, "Blue"), vec![d.0]);
|
||||
let step = s.doc().unwrap().history.undo.last().unwrap().clone();
|
||||
assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE)));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, Some(old.id));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(style(&s, "S").appearance, blue.appearance);
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// A style replaced by itself, or by a copy with the same look, records nothing.
|
||||
run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"}));
|
||||
let before = steps(&s);
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"}));
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"}));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
|
||||
// A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors.
|
||||
for p in [
|
||||
json!({"name": "S", "from": "nope"}),
|
||||
json!({"name": "nope", "from": "Blue"}),
|
||||
json!({"name": "S", "from": 3}),
|
||||
json!({"name": "S", "from": "Blue", "id": a.0}),
|
||||
json!({"from": "Blue"}),
|
||||
] {
|
||||
assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!((steps(&s), style(&s, "S")), (before, old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_style_unlinks_and_renaming_keeps_links() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -253,6 +253,28 @@ fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_ste
|
||||
assert!(st.doc.symbol_edit.is_some());
|
||||
}
|
||||
|
||||
/// Redefining the symbol being edited with `keepArt: true` also leaves symbol editing mode in the
|
||||
/// same step; the art outside the editing layer stays ordinary art and stays selected, and the
|
||||
/// art on the editing layer still can't redefine it.
|
||||
#[test]
|
||||
fn redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode() {
|
||||
let (mut s, first, second) = two_instances();
|
||||
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30})));
|
||||
let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap());
|
||||
let e = s.execute("symbol.update", &json!({"name": "Box", "keepArt": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't hold an instance of itself"), "{e}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0], "keepArt": true}));
|
||||
assert!(r["id"].is_null(), "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none());
|
||||
assert_eq!(st.history.undo.len(), steps + 1);
|
||||
assert!(matches!(st.doc.node(other).map(|n| &n.kind), Some(NodeKind::Path { .. })), "the art stays ordinary art");
|
||||
assert_eq!(st.selection.objects, vec![other], "the art stays selected");
|
||||
assert!(is_instance(&s, first), "the instance editing was entered from is still an instance");
|
||||
assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() {
|
||||
let (mut s, first, _) = two_instances();
|
||||
|
||||
@@ -453,6 +453,92 @@ fn colour_table_lock_web_shift_snap_and_sort() {
|
||||
assert!(lossy < plain, "{lossy} vs {plain}");
|
||||
}
|
||||
|
||||
/// Delete Color: the deleted colors leave the table and the file, their pixels take the nearest
|
||||
/// color left, and the edit stays with the settings until another reduction is chosen.
|
||||
#[test]
|
||||
fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
|
||||
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
|
||||
let mut s = session(40.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
|
||||
let sources = |v: &Value| -> Vec<String> {
|
||||
let mut out: Vec<String> =
|
||||
v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| c["source"].as_str().unwrap().to_string()).collect();
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
let base = preview(&mut s, json!({"dither": "none"}));
|
||||
assert_eq!(base["colors"].as_array().unwrap().len(), 4, "{base}");
|
||||
for format in ["gif", "png8"] {
|
||||
let p = json!({"format": format, "dither": "none", "colorTable": {"deleted": ["#EE1100"]}});
|
||||
let v = preview(&mut s, p.clone());
|
||||
assert_eq!(v["colors"].as_array().unwrap().len(), 3, "{format}: {v}");
|
||||
assert!(v["colors"].as_array().unwrap().iter().any(|c| c["transparent"] == true), "{format}: the transparent entry stays");
|
||||
assert_eq!(sources(&v), ["#0000ff", "#ff0000"], "{format}");
|
||||
let file = one(&mut s, p);
|
||||
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
|
||||
let img = pixels(&file);
|
||||
assert_eq!(img.get_pixel(15, 5).0, [255, 0, 0, 255], "{format}: the nearest color left");
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0));
|
||||
assert_eq!(distinct(&img), 3, "{format}");
|
||||
}
|
||||
// A color the table does not hold is no edit; sorting does not bring a deleted one back.
|
||||
assert_eq!(sources(&preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#123456"]}}))).len(), 3);
|
||||
let sorted = preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#ee1100"], "sort": "luminance"}}));
|
||||
assert_eq!(sources(&sorted), ["#0000ff", "#ff0000"]);
|
||||
// A fixed palette: colors it lacks are not made again, and deletions come out of it.
|
||||
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
|
||||
assert_eq!(sources(&fixed), ["#0000ff", "#ff0000"]);
|
||||
let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"], "deleted": ["#ff0000"]}}));
|
||||
assert_eq!(sources(&fixed), ["#0000ff"]);
|
||||
// At most `colors` entries of a fixed palette, the transparent one included.
|
||||
let two = preview(&mut s, json!({"dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}}));
|
||||
assert_eq!(sources(&two), ["#0000ff"]);
|
||||
// Deleting every opaque color is refused: the pixels need a color.
|
||||
// Colors mapped to transparent do not count as left.
|
||||
for table in [
|
||||
json!({"deleted": ["#ff0000", "#ee1100", "#0000ff"]}),
|
||||
json!({"customPalette": ["#ff0000"], "deleted": ["#ff0000"]}),
|
||||
json!({"deleted": ["#0000ff", "#ee1100"], "transparent": ["#ff0000"]}),
|
||||
json!({"customPalette": ["#ff0000", "#0000ff"], "deleted": ["#0000ff"], "transparent": ["#ff0000"]}),
|
||||
] {
|
||||
let p = json!({"colorTable": table});
|
||||
let e = s.execute("document.exportForWeb.preview", &p).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(e.contains(cmd::webexport::KEEP_ONE), "{p}: {e}");
|
||||
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
|
||||
}
|
||||
for bad in [
|
||||
json!({"colorTable": {"deleted": ["nope"]}}),
|
||||
json!({"colorTable": {"customPalette": ["#ff000080"]}}),
|
||||
json!({"colorTable": {"deleted": vec!["#ff0000"; 257]}}),
|
||||
] {
|
||||
assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// A deleted color leaves the other lists; JPEG and PNG-24 have no table to edit.
|
||||
let table = json!({
|
||||
"deleted": ["#ee1100"], "customPalette": ["#ff0000", "#ee1100", "#0000ff"], "locked": ["#EE1100", "#0000ff"],
|
||||
"transparent": ["#ee1100"], "webShift": ["#ee1100"],
|
||||
});
|
||||
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
|
||||
let t = r["settings"]["colorTable"].clone();
|
||||
assert_eq!((&t["locked"], &t["transparent"], &t["webShift"]), (&json!(["#0000ff"]), &json!([]), &json!([])));
|
||||
assert_eq!(t["deleted"], json!(["#ee1100"]));
|
||||
for format in ["jpg", "png24"] {
|
||||
assert!(preview(&mut s, json!({"format": format, "colorTable": t.clone()})).get("colors").is_none(), "{format}");
|
||||
}
|
||||
// The remembered edit survives other keys and a format change, and goes with another reduction.
|
||||
let r = run(&mut s, "webExport.settings", json!({"colors": 64, "format": "png8"}));
|
||||
assert_eq!(r["settings"]["colorTable"]["deleted"], json!(["#ee1100"]));
|
||||
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
|
||||
assert_eq!((&r["settings"]["colorTable"]["deleted"], &r["settings"]["colorTable"]["customPalette"]), (&json!([]), &json!([])));
|
||||
// A saved preset keeps the edit.
|
||||
run(&mut s, "webExport.presets.save", json!({"name": "No near red", "dither": "none", "colorTable": {"deleted": ["#ee1100"]}}));
|
||||
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_and_remembered_settings() {
|
||||
let mut s = two_colours();
|
||||
|
||||
@@ -480,8 +480,8 @@ fn reflect_and_shear_tools() {
|
||||
assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// Reflect and Shear return an error for an `axis` they don't take (Reflect's names it and also
|
||||
/// takes an angle): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
|
||||
/// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an
|
||||
/// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect
|
||||
/// then reflects across the vertical axis and Shear shears along the horizontal one.
|
||||
#[test]
|
||||
fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
|
||||
@@ -489,13 +489,17 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let n = undo_len(&s);
|
||||
let reflect = "axis must be \"vertical\", \"horizontal\" or an angle in degrees";
|
||||
let shear = "`axis` must be one of horizontal, vertical";
|
||||
let shear = "axis must be \"horizontal\", \"vertical\" or an angle in degrees from -359 to 359";
|
||||
for (cmd, p, msg) in [
|
||||
("object.reflect", json!({"axis": "diagonal", "origin": [0, 0]}), format!("{reflect}, not `diagonal`")),
|
||||
("object.reflect", json!({"axis": "45", "origin": [0, 0]}), format!("{reflect}, not `45`")),
|
||||
("object.reflect", json!({"axis": true, "origin": [0, 0]}), format!("{reflect}, not `true`")),
|
||||
("object.shear", json!({"angle": 30, "axis": "diagonal"}), shear.to_string()),
|
||||
("object.shear", json!({"angle": 30, "axis": 90}), shear.to_string()),
|
||||
("object.shear", json!({"angle": 30, "axis": "diagonal"}), format!("{shear}, not `diagonal`")),
|
||||
("object.shear", json!({"angle": 30, "axis": "90"}), format!("{shear}, not `90`")),
|
||||
("object.shear", json!({"angle": 30, "axis": 360}), format!("{shear}, not `360`")),
|
||||
("object.shear", json!({"angle": 30, "axis": -359.5}), format!("{shear}, not `-359.5`")),
|
||||
("object.shear", json!({"angle": 30, "axis": [45]}), format!("{shear}, not `[45]`")),
|
||||
("object.shear", json!({"angle": 30, "axis": false}), format!("{shear}, not `false`")),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}"));
|
||||
assert_eq!(e.to_string(), format!("invalid parameters for `{cmd}`: {msg}"));
|
||||
@@ -511,6 +515,119 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
|
||||
assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}");
|
||||
}
|
||||
|
||||
/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant
|
||||
/// opposite ways, and 120 and 300 slant as -60 does.
|
||||
#[test]
|
||||
fn shear_angles_slant_by_their_tangent() {
|
||||
let run = 100.0 * 60f64.to_radians().tan();
|
||||
for (angle, want) in [
|
||||
(60.0, Rect::new(-run, 0.0, 100.0, 100.0)),
|
||||
(-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)),
|
||||
] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap();
|
||||
assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no
|
||||
/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_rejects_angles_with_no_shear_or_out_of_range() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let n = undo_len(&s);
|
||||
let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear");
|
||||
let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}");
|
||||
for (angle, msg) in [
|
||||
(90.0, none(90.0)),
|
||||
(-90.0, none(-90.0)),
|
||||
(270.0, none(270.0)),
|
||||
(-270.0, none(-270.0)),
|
||||
(90.0 + 1e-12, none(90.0 + 1e-12)),
|
||||
(360.0, range(360.0)),
|
||||
(-359.5, range(-359.5)),
|
||||
(1e300, range(1e300)),
|
||||
] {
|
||||
let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string());
|
||||
assert_eq!(e.to_string(), msg);
|
||||
}
|
||||
assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle");
|
||||
assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a));
|
||||
assert_eq!(undo_len(&s), n, "no undo step");
|
||||
}
|
||||
|
||||
/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact
|
||||
/// coordinates and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_by_0_and_180_changes_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let before = bounds(&s, a);
|
||||
let n = undo_len(&s);
|
||||
for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] {
|
||||
for axis in ["horizontal", "vertical"] {
|
||||
s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap();
|
||||
assert_eq!(bounds(&s, a), before, "{angle} {axis}");
|
||||
assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point
|
||||
/// slides along the axis by the tangent of the shear angle times its distance across the axis
|
||||
/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again
|
||||
/// repeats it; 0° and 90° shear as the named axes do, and a copy leaves the original in place.
|
||||
#[test]
|
||||
fn shear_along_an_axis_at_an_angle() {
|
||||
let anchors = |s: &Session, id: NodeId| -> Vec<Point> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect()
|
||||
};
|
||||
// The axis's direction and the direction a quarter turn counter-clockwise from it, with y down.
|
||||
let sheared = |p: Point, o: Point, axis: f64, angle: f64| {
|
||||
let (a, k) = (axis.to_radians(), angle.to_radians().tan());
|
||||
let (along, across) = (Vec2::new(a.cos(), -a.sin()), Vec2::new(-a.sin(), -a.cos()));
|
||||
p + along * (k * (p - o).dot(across))
|
||||
};
|
||||
let near = |a: &[Point], b: &[Point]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.distance(*q) < 1e-9);
|
||||
let o = Point::new(20.0, 30.0);
|
||||
for (axis, angle) in [(45.0, 30.0), (-120.5, 20.0), (359.0, 30.0), (-359.0, -30.0), (30.0, 30.0)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
|
||||
let before = anchors(&s, a);
|
||||
let n = undo_len(&s);
|
||||
s.execute("object.shear", &json!({"angle": angle, "axis": axis, "origin": [o.x, o.y]})).unwrap();
|
||||
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, axis, angle)).collect();
|
||||
assert!(near(&anchors(&s, a), &want), "{axis}° {angle}°: {:?}, not {want:?}", anchors(&s, a));
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
s.execute("object.transformAgain", &json!({})).unwrap();
|
||||
let again: Vec<Point> = want.iter().map(|p| sheared(*p, o, axis, angle)).collect();
|
||||
assert!(near(&anchors(&s, a), &again), "Transform Again at {axis}°: {:?}", anchors(&s, a));
|
||||
}
|
||||
for (named, axis) in [("horizontal", 0.0), ("vertical", 90.0), ("vertical", -270.0)] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
|
||||
s.execute("object.shear", &json!({"angle": 30, "axis": named, "origin": [o.x, o.y]})).unwrap();
|
||||
let by_name = anchors(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("object.shear", &json!({"angle": 30, "axis": axis, "origin": [o.x, o.y]})).unwrap();
|
||||
assert!(near(&anchors(&s, a), &by_name), "{axis}° shears as {named}: {:?}, not {by_name:?}", anchors(&s, a));
|
||||
}
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0);
|
||||
let before = anchors(&s, a);
|
||||
s.execute("object.shear", &json!({"angle": 30, "axis": 45, "origin": [o.x, o.y], "copy": true})).unwrap();
|
||||
assert!(near(&anchors(&s, a), &before), "the original stays: {:?}", anchors(&s, a));
|
||||
let copy = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_ne!(copy, a, "the copy is selected");
|
||||
let want: Vec<Point> = before.iter().map(|p| sheared(*p, o, 45.0, 30.0)).collect();
|
||||
assert!(near(&anchors(&s, copy), &want), "the copy is sheared: {:?}", anchors(&s, copy));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distort_command_maps_corners() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1009,6 +1009,9 @@ fn structured_junk() {
|
||||
("addon.pathtools.expandDashes", json!({})),
|
||||
("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})),
|
||||
("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})),
|
||||
("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})),
|
||||
("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})),
|
||||
// Refused before anything is written: no format of that name, a time that is no time.
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})),
|
||||
("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})),
|
||||
|
||||
@@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() {
|
||||
assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() {
|
||||
use vectorcraft_doc::Arrowhead;
|
||||
let mut s = session();
|
||||
for (style, head) in
|
||||
[("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)]
|
||||
{
|
||||
let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap();
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
|
||||
let heads: Vec<_> = n
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone())))
|
||||
.filter(|(a, b)| a.is_some() || b.is_some())
|
||||
.collect();
|
||||
match head {
|
||||
Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"),
|
||||
None => assert!(heads.is_empty(), "{style}: {heads:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_angles_circles_arcs_and_curves() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() {
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}");
|
||||
}
|
||||
|
||||
/// Every string in `v`, at any depth.
|
||||
fn strings_in(v: &Value, out: &mut Vec<String>) {
|
||||
match v {
|
||||
Value::String(s) => out.push(s.clone()),
|
||||
Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)),
|
||||
Value::Object(map) => map.values().for_each(|v| strings_in(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller: an exporter, given the native document's JSON, is not run for a document
|
||||
/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every
|
||||
/// command that writes its format refuses, before any file or folder is written, with an error
|
||||
/// that names no file or folder, and the document keeps its links. A data set's image inside the
|
||||
/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them,
|
||||
/// and the person's export gives it every path as stored.
|
||||
#[test]
|
||||
fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = tmp_dir("confined-away");
|
||||
let home = tmp_dir("confined-home");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input));
|
||||
let format = "plugin.test.confined";
|
||||
let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap();
|
||||
let out = path_of(&home.join("out"));
|
||||
let outputs = [
|
||||
("document.serialize", json!({"format": format})),
|
||||
("document.export", json!({"format": format})),
|
||||
("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})),
|
||||
("document.exportSelection", json!({"format": format})),
|
||||
("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
("assets.export", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
];
|
||||
let hidden = [path_of(&away), path_of(&home)];
|
||||
// `assets`: an asset's file is checked too (its document holds the asset's art and the
|
||||
// document's data sets, not other art).
|
||||
let refused = |s: &mut Session, why: &str, assets: bool| {
|
||||
for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}"));
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains(why), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written");
|
||||
};
|
||||
// The strings of the JSON the exporter is given.
|
||||
let given = |s: &mut Session, confined: bool| {
|
||||
let p = json!({"format": format});
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) };
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found);
|
||||
found
|
||||
};
|
||||
|
||||
let script = path_of(&away.join("menu.js"));
|
||||
s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap();
|
||||
refused(&mut s, "a linked JavaScript file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&script), "the person's export");
|
||||
s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap();
|
||||
|
||||
let set_image = |s: &mut Session, path: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect();
|
||||
doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }];
|
||||
};
|
||||
let photo = path_of(&away.join("photo.png"));
|
||||
set_image(&mut s, &photo);
|
||||
refused(&mut s, "a linked image file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&photo), "the person's export");
|
||||
let inside = path_of(&home.join("photo.png"));
|
||||
set_image(&mut s, &inside);
|
||||
assert!(given(&mut s, true).contains(&inside), "an image inside the read roots");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear();
|
||||
|
||||
let folder = path_of(&away.join("screens"));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap();
|
||||
assert!(!given(&mut s, true).contains(&folder), "the export folder is left out");
|
||||
assert!(given(&mut s, false).contains(&folder), "the person's export");
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it");
|
||||
|
||||
let mut part = Session::new();
|
||||
part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let placed = path_of(&away.join("part.vectorcraft"));
|
||||
part.execute("file.saveAs", &json!({"path": placed})).unwrap();
|
||||
s.execute("file.place", &json!({"path": placed, "link": true})).unwrap();
|
||||
refused(&mut s, "a linked image file is outside the read roots", false);
|
||||
// The asset's file holds the rectangle alone, without the placed file.
|
||||
let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap();
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found);
|
||||
assert!(!found.contains(&placed), "{found:?}");
|
||||
let _ = std::fs::remove_dir_all(&away);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
@@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() {
|
||||
assert_eq!(text, program(&doc));
|
||||
}
|
||||
|
||||
/// The program written from `doc`, with the gradient and pattern definitions found by comparing
|
||||
/// each in turn (`scanned`) or through their indexes.
|
||||
fn program_scanned(doc: &Document, scanned: bool) -> Vec<u8> {
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned));
|
||||
let out = export_ai_editing(doc, &opts());
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(false));
|
||||
out.unwrap().program
|
||||
}
|
||||
|
||||
/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with
|
||||
/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of
|
||||
/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one
|
||||
/// and another gradient for the rest; one with the gradient of an object whose style isn't written
|
||||
/// (an even-odd fill with a drop shadow), after that object; and two whose gradients
|
||||
/// differ only in the sign of a zero offset.
|
||||
fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document {
|
||||
let mut doc = gradients_and_patterns();
|
||||
let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
|
||||
let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1));
|
||||
let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0));
|
||||
let more = (0..swatches)
|
||||
.map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false })
|
||||
.collect();
|
||||
swatches_plus(&mut doc, more);
|
||||
let mut paints = vec![];
|
||||
for i in 0..distinct {
|
||||
paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None));
|
||||
}
|
||||
for i in 0..reused {
|
||||
paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None));
|
||||
}
|
||||
for i in 0..swatches {
|
||||
let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) };
|
||||
paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}"))));
|
||||
}
|
||||
// The reader wouldn't read an even-odd fill with the style, so the style isn't written.
|
||||
let unstyled = two(Color::WHITE, Color::BLACK);
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))],
|
||||
effects: vec![fx("stylize.dropShadow", serde_json::json!({}))],
|
||||
contents_index: None,
|
||||
};
|
||||
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap);
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
put(&mut doc, n);
|
||||
paints.push(gradient_paint(unstyled, None, None));
|
||||
let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]);
|
||||
paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]);
|
||||
for (i, p) in (0u16..).zip(paints) {
|
||||
let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0);
|
||||
let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]);
|
||||
put(&mut doc, n);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// Gradient and pattern definitions found through their indexes are those found by comparing each
|
||||
/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to
|
||||
/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its
|
||||
/// name free; gradients that differ only in the sign of a zero share a definition.
|
||||
#[test]
|
||||
fn indexed_definitions_write_the_same_program() {
|
||||
let doc = many_gradients(300, 300, 7, 6);
|
||||
let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true));
|
||||
let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b);
|
||||
assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len());
|
||||
let text = String::from_utf8(indexed).unwrap();
|
||||
let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect();
|
||||
// `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1
|
||||
// after the style + 1 for both signs of zero.
|
||||
assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}");
|
||||
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len(), "{names:?}");
|
||||
assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1);
|
||||
}
|
||||
|
||||
/// A gradient paint is matched with the definitions of the same gradient, not with each
|
||||
/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons
|
||||
/// each, where comparing each definition in turn takes hundreds of thousands.
|
||||
#[test]
|
||||
fn gradient_definitions_are_found_without_comparing_each() {
|
||||
let doc = many_gradients(1000, 1000, 10, 0);
|
||||
let comparisons = |scanned: bool| {
|
||||
writer::GRADIENT_COMPARISONS.with(|c| c.set(0));
|
||||
program_scanned(&doc, scanned);
|
||||
writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get)
|
||||
};
|
||||
let (indexed, scanned) = (comparisons(false), comparisons(true));
|
||||
assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index");
|
||||
assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index");
|
||||
}
|
||||
|
||||
/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20
|
||||
/// gradient swatches, with the definitions found by comparing each in turn and through their
|
||||
/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with
|
||||
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing"]
|
||||
fn gradient_definitions_timing() {
|
||||
let doc = many_gradients(5000, 5000, 50, 20);
|
||||
let mut times = [vec![], vec![]];
|
||||
let mut programs: [Option<Vec<u8>>; 2] = [None, None];
|
||||
let mut how = "";
|
||||
for _ in 0..7 {
|
||||
for (k, scanned) in [true, false].into_iter().enumerate() {
|
||||
let (start, h) = thread_time();
|
||||
let program = program_scanned(&doc, scanned);
|
||||
times[k].push(thread_time().0.saturating_sub(start));
|
||||
how = h;
|
||||
programs[k].get_or_insert(program);
|
||||
}
|
||||
}
|
||||
assert_eq!(programs[0], programs[1]);
|
||||
for t in &mut times {
|
||||
t.sort();
|
||||
}
|
||||
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
|
||||
println!("median of 7 runs ({how}):");
|
||||
println!("| definitions found | median (ms) | runs (ms) |");
|
||||
println!("|---|---:|---|");
|
||||
for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() {
|
||||
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
|
||||
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop,
|
||||
/// and reads back with each stop on its side.
|
||||
#[test]
|
||||
@@ -10077,6 +10204,7 @@ fn brush_library() -> Vec<vectorcraft_brush::Brush> {
|
||||
rotation: (-45.0, 30.0),
|
||||
rotation_relative_to_path: true,
|
||||
colorization: Colorization::Tints,
|
||||
hue_jitter: 0.0,
|
||||
modes: Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random]),
|
||||
}),
|
||||
},
|
||||
@@ -10183,6 +10311,22 @@ fn brushes_are_read_back_with_their_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The writer does not write a Scatter brush's hue jitter: the brush would open without it, so it
|
||||
/// is left out of the Brushes panel and reported.
|
||||
#[test]
|
||||
fn a_scatter_brush_with_hue_jitter_is_left_out() {
|
||||
use vectorcraft_brush::BrushKind;
|
||||
let mut lib = brush_library();
|
||||
let BrushKind::Scatter(s) = &mut lib[1].kind else { panic!("scatter") };
|
||||
s.hue_jitter = 60.0;
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
vectorcraft_brush::store(&mut doc, &lib);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings);
|
||||
let back = vectorcraft_brush::library(&read_back(&doc));
|
||||
assert_eq!(back.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Nib", "Ribbon", "Plain ribbon"]);
|
||||
}
|
||||
|
||||
/// An Art brush's options, without its art.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct ArtBrushOptions(serde_json::Value);
|
||||
@@ -10512,6 +10656,7 @@ fn more_brush_settings_are_read_back() {
|
||||
rotation: (15.0, 15.0),
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
modes: Some([Variation::Tilt, Variation::Bearing, Variation::Fixed, Variation::Rotation]),
|
||||
};
|
||||
let lib = vec![
|
||||
|
||||
@@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD;
|
||||
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
|
||||
#[cfg(test)]
|
||||
pub(super) use paints::{
|
||||
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
@@ -200,11 +201,11 @@ pub(super) struct Writer<'a> {
|
||||
/// pattern's definition, the pattern's space turned y up.
|
||||
canvas: Affine,
|
||||
/// The gradient definitions, in the order they are first used.
|
||||
gradients: Vec<paints::GradientDef>,
|
||||
gradients: paints::GradientDefs,
|
||||
/// The number the next new gradient definition's name tries first (1 is `Gradient`).
|
||||
next_gradient: u64,
|
||||
/// The pattern definitions written, each after those its art uses.
|
||||
patterns: Vec<paints::PatternOut>,
|
||||
patterns: paints::PatternDefs,
|
||||
/// The patterns whose definitions are being written.
|
||||
defining: Vec<String>,
|
||||
/// Writing the palette: the definitions it adds are for its swatches only.
|
||||
@@ -357,9 +358,9 @@ impl<'a> Writer<'a> {
|
||||
grad_space: to_art,
|
||||
tile_grad_space: Affine::translate((-origin.0, origin.1)),
|
||||
canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art,
|
||||
gradients: vec![],
|
||||
gradients: paints::GradientDefs::default(),
|
||||
next_gradient: 1,
|
||||
patterns: vec![],
|
||||
patterns: paints::PatternDefs::default(),
|
||||
defining: vec![],
|
||||
in_palette: false,
|
||||
canvas_origin: origin,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the
|
||||
//! pattern operators (see [`crate::ai_editing`] for the form).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -46,6 +48,134 @@ pub(super) struct PatternOut {
|
||||
used: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing
|
||||
/// the gradient or name with each definition in turn.
|
||||
pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// How many times [`GradientDefs::find`] has compared two gradients on this thread.
|
||||
pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Are gradients `a` and `b` the same?
|
||||
fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
|
||||
#[cfg(test)]
|
||||
GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1));
|
||||
a == b
|
||||
}
|
||||
|
||||
/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its
|
||||
/// bits, with -0 as 0); different gradients may share one.
|
||||
fn gradient_key(g: &Gradient) -> u64 {
|
||||
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
std::mem::discriminant(&g.kind).hash(&mut h);
|
||||
std::mem::discriminant(&g.method).hash(&mut h);
|
||||
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
|
||||
for s in &g.stops {
|
||||
let (model, c) = match s.color {
|
||||
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
|
||||
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
|
||||
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
|
||||
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
|
||||
};
|
||||
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
|
||||
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The gradient definitions, in the order they are first used, found by name and by gradient
|
||||
/// without comparing each one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct GradientDefs {
|
||||
list: Vec<GradientDef>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
/// The places in `list` of the definitions no swatch names, in order, by their gradient's key
|
||||
/// ([`gradient_key`]).
|
||||
ramps: HashMap<u64, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl GradientDefs {
|
||||
/// Is `name` a definition's name?
|
||||
fn has_name(&self, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().any(|d| d.name == name);
|
||||
}
|
||||
self.names.contains_key(name)
|
||||
}
|
||||
|
||||
/// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch
|
||||
/// of the same gradient, else the first definition of the same gradient that no swatch names.
|
||||
fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return swatch
|
||||
.and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g)))
|
||||
.or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g)));
|
||||
}
|
||||
let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g));
|
||||
swatch
|
||||
.and_then(|s| self.names.get(s).copied().filter(|i| held(i, true)))
|
||||
.or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false)))
|
||||
}
|
||||
|
||||
/// Add `d`, whose name no definition has.
|
||||
fn push(&mut self, d: GradientDef) {
|
||||
let i = self.list.len();
|
||||
if !d.swatch {
|
||||
self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i);
|
||||
}
|
||||
self.names.insert(d.name.clone(), i);
|
||||
self.list.push(d);
|
||||
}
|
||||
|
||||
/// Keep the first `len` definitions; the names of those removed are free again.
|
||||
fn truncate(&mut self, len: usize) {
|
||||
while self.list.len() > len {
|
||||
let Some(d) = self.list.pop() else { break };
|
||||
self.names.remove(&d.name);
|
||||
if !d.swatch {
|
||||
// Places are added in order, so the removed definition's is the last of its key's.
|
||||
let key = gradient_key(&d.gradient);
|
||||
if let Some(places) = self.ramps.get_mut(&key) {
|
||||
places.pop();
|
||||
if places.is_empty() {
|
||||
self.ramps.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern definitions written, each after those its art uses, found by name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PatternDefs {
|
||||
list: Vec<PatternOut>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PatternDefs {
|
||||
/// The place of pattern `name`'s definition.
|
||||
fn find(&self, name: &str) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().position(|p| p.name == name);
|
||||
}
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// Add `p`, whose name no definition has.
|
||||
fn push(&mut self, p: PatternOut) {
|
||||
self.names.insert(p.name.clone(), self.list.len());
|
||||
self.list.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::ai_editing) const DIAMOND: &str =
|
||||
"diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps";
|
||||
@@ -118,7 +248,7 @@ impl Writer<'_> {
|
||||
&& let stops = curve_as_stops(&g.gradient)
|
||||
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
&& !self.gradients.has_name(&sw.name)
|
||||
{
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false });
|
||||
}
|
||||
@@ -131,17 +261,14 @@ impl Writer<'_> {
|
||||
/// swatch or a pattern).
|
||||
fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
|
||||
let used = !self.in_palette;
|
||||
let found = swatch
|
||||
.and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g))
|
||||
.or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g));
|
||||
if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) {
|
||||
let found = self.gradients.find(g, swatch);
|
||||
if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) {
|
||||
d.used |= used;
|
||||
return d.name.clone();
|
||||
}
|
||||
let (doc, gradients) = (self.doc, &self.gradients);
|
||||
let name = free_gradient_name(&mut self.next_gradient, |name| {
|
||||
gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()
|
||||
});
|
||||
let name =
|
||||
free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some());
|
||||
self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used });
|
||||
name
|
||||
}
|
||||
@@ -149,14 +276,14 @@ impl Writer<'_> {
|
||||
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
|
||||
/// art uses, and the next name's number.
|
||||
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
|
||||
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
(self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
}
|
||||
|
||||
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
|
||||
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
|
||||
let (len, used, next) = mark;
|
||||
self.gradients.truncate(len);
|
||||
for (d, u) in self.gradients.iter_mut().zip(used) {
|
||||
for (d, u) in self.gradients.list.iter_mut().zip(used) {
|
||||
d.used = u;
|
||||
}
|
||||
self.next_gradient = next;
|
||||
@@ -476,7 +603,7 @@ impl Writer<'_> {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.iter().any(|p| p.name == name) {
|
||||
if self.patterns.find(name).is_some() {
|
||||
return true;
|
||||
}
|
||||
self.doc.pattern(name).is_some_and(tile_holds_art)
|
||||
@@ -492,7 +619,7 @@ impl Writer<'_> {
|
||||
return false;
|
||||
}
|
||||
let used = !self.in_palette;
|
||||
if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) {
|
||||
if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) {
|
||||
p.used |= used;
|
||||
return true;
|
||||
}
|
||||
@@ -582,7 +709,7 @@ impl Writer<'_> {
|
||||
/// uses).
|
||||
pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) {
|
||||
let defs = std::mem::take(&mut self.gradients);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used);
|
||||
let _ = writeln!(s, "{} Bn", used.len());
|
||||
for d in &used {
|
||||
self.gradient_def(s, d);
|
||||
@@ -595,12 +722,12 @@ impl Writer<'_> {
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
}
|
||||
self.gradients = defs;
|
||||
for p in self.patterns.iter().filter(|p| p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
if self.patterns.iter().any(|p| !p.used) {
|
||||
if self.patterns.list.iter().any(|p| !p.used) {
|
||||
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
|
||||
for p in self.patterns.iter().filter(|p| !p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| !p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
@@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool {
|
||||
b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn two(a: f32, b: Color) -> Gradient {
|
||||
Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)])
|
||||
}
|
||||
|
||||
fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef {
|
||||
GradientDef { name: name.into(), gradient, swatch, used: true }
|
||||
}
|
||||
|
||||
/// The same gradients have the same key, a zero of either sign included.
|
||||
#[test]
|
||||
fn a_zero_of_either_sign_gives_the_same_key() {
|
||||
assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK)));
|
||||
assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK));
|
||||
assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE)));
|
||||
}
|
||||
|
||||
/// Definitions whose gradients share a key are told apart by their gradients, the first of the
|
||||
/// same gradient found; a gradient that isn't equal to itself is found in none.
|
||||
#[test]
|
||||
fn definitions_that_share_a_key_are_told_apart() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Gradient", white.clone(), false));
|
||||
defs.push(def("Gradient 2", black.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
// Every definition under the black gradient's key, as if the keys of both were the same.
|
||||
defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]);
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]);
|
||||
assert_eq!(defs.find(&white, None), Some(0));
|
||||
let nan = two(f32::NAN, Color::BLACK);
|
||||
defs.push(def("Gradient 4", nan.clone(), false));
|
||||
assert_eq!(defs.find(&nan, None), None);
|
||||
}
|
||||
|
||||
/// A swatch's definition is found by the swatch's name and gradient; a definition that no
|
||||
/// swatch names, for the same gradient without the name or with another.
|
||||
#[test]
|
||||
fn a_swatch_definition_is_found_by_its_name_and_gradient() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", black.clone(), true));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), None);
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), None);
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), Some(2));
|
||||
assert_eq!(defs.find(&black, Some("Other")), Some(1));
|
||||
}
|
||||
|
||||
/// Definitions removed leave their names free and are no longer found; those kept still are.
|
||||
#[test]
|
||||
fn removed_definitions_free_their_names() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", white.clone(), true));
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
defs.truncate(2);
|
||||
assert!(defs.has_name("Ramp") && defs.has_name("Gradient"));
|
||||
assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3"));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
assert_eq!(defs.ramps.values().map(Vec::len).sum::<usize>(), 1);
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&white, None), Some(2));
|
||||
defs.truncate(0);
|
||||
assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty());
|
||||
}
|
||||
|
||||
/// A pattern's definition is found by its name.
|
||||
#[test]
|
||||
fn pattern_definitions_are_found_by_name() {
|
||||
let mut defs = PatternDefs::default();
|
||||
assert_eq!(defs.find("Dots"), None);
|
||||
for name in ["Dots", "Checks"] {
|
||||
defs.push(PatternOut { name: name.into(), text: String::new(), used: false });
|
||||
}
|
||||
assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None));
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,8 @@ mod tests_native;
|
||||
#[cfg(test)]
|
||||
mod tests_reads;
|
||||
#[cfg(test)]
|
||||
mod tests_strings;
|
||||
#[cfg(test)]
|
||||
mod tests_type1;
|
||||
#[cfg(test)]
|
||||
mod tests_type42;
|
||||
|
||||
@@ -146,13 +146,21 @@ impl Interp<'_> {
|
||||
fn token(&mut self) -> Res {
|
||||
match self.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, lex.immediate)?;
|
||||
// The whitespace after the token is read with it.
|
||||
let used = bytes.len() - lex.data().len();
|
||||
self.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
// The scanner reads the string in place. The borrow ends before `scanned`, which
|
||||
// can fail or charge the budget, and before the results are pushed.
|
||||
let read = {
|
||||
let bytes = s.borrow();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
// The whitespace after the token is read with it.
|
||||
lex.next()?.map(|o| {
|
||||
let immediate = lex.immediate;
|
||||
let rest = lex.data().len();
|
||||
(o, immediate, bytes.len() - rest, rest)
|
||||
})
|
||||
};
|
||||
let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, immediate)?;
|
||||
self.push_interval(Obj::Str(s), used, rest)?;
|
||||
self.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
|
||||
@@ -753,21 +753,25 @@ impl<'a> Interp<'a> {
|
||||
}
|
||||
|
||||
fn search_string(&mut self, op: Op) -> Res {
|
||||
let seek = self.pop_str()?.to_vec();
|
||||
let seek = self.pop_str()?;
|
||||
let s = self.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
// Both strings are read in place, and the borrows end before the results are pushed.
|
||||
let (len, n, at) = {
|
||||
let (text, seek) = (s.borrow(), seek.borrow());
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
(text.len(), seek.len(), at)
|
||||
};
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
self.push_interval(o.clone(), i, seek.len())?;
|
||||
self.push_interval(o.clone(), i + n, len - i - n)?;
|
||||
self.push_interval(o.clone(), i, n)?;
|
||||
self.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
self.push_interval(o, 0, seek.len())?;
|
||||
self.push_interval(o.clone(), n, len - n)?;
|
||||
self.push_interval(o, 0, n)?;
|
||||
}
|
||||
self.push(Obj::Bool(true))?;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ thread_local! {
|
||||
/// Tests: the arrays of the list last released on this thread that were still alive after it
|
||||
/// (the ones the interpreter itself still held).
|
||||
pub(crate) static ARRAYS_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many values [`Shared::to_vec`] has copied on this thread.
|
||||
pub(crate) static VALUES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -340,7 +342,10 @@ impl<T: Clone + Held> Shared<T> {
|
||||
}
|
||||
|
||||
pub fn to_vec(&self) -> Vec<T> {
|
||||
self.borrow().to_vec()
|
||||
let v = self.borrow().to_vec();
|
||||
#[cfg(test)]
|
||||
VALUES_COPIED.with(|n| n.set(n.get() + v.len()));
|
||||
v
|
||||
}
|
||||
|
||||
/// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end.
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read
|
||||
//! their strings in place. The tests run them next to reference readers that copy the strings
|
||||
//! first, on the same operands in the same interpreter state: the operand stack, the error and the
|
||||
//! operations spent must agree.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::graphics::{GState, Out};
|
||||
use super::interp::Interp;
|
||||
use super::lex::Lexer;
|
||||
use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED};
|
||||
|
||||
/// An interpreter that has run `src`, with the operands it left.
|
||||
fn after(src: &[u8]) -> Interp<'_> {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.layers.clear();
|
||||
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
|
||||
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
|
||||
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
|
||||
it
|
||||
}
|
||||
|
||||
/// The reference `token`: the string copied before it is scanned.
|
||||
fn token_by_copy(it: &mut Interp) -> Res {
|
||||
match it.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, lex.immediate)?;
|
||||
let used = bytes.len() - lex.data().len();
|
||||
it.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
let (o, immediate) = it.next_in(&f)?;
|
||||
let Some(o) = o else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, immediate)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
_ => return Err(PsError::Ps("typecheck", "token".into())),
|
||||
}
|
||||
it.push(Obj::Bool(true))
|
||||
}
|
||||
|
||||
/// The reference `search` and `anchorsearch`: both strings copied before they are compared.
|
||||
fn search_by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
let seek = it.pop_str()?.to_vec();
|
||||
let s = it.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
it.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
it.push_interval(o.clone(), i, seek.len())?;
|
||||
it.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
it.push_interval(o, 0, seek.len())?;
|
||||
}
|
||||
it.push(Obj::Bool(true))?;
|
||||
}
|
||||
None => {
|
||||
it.push(Obj::Str(s))?;
|
||||
it.push(Obj::Bool(false))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) }
|
||||
}
|
||||
|
||||
/// The error's name, or the limit reached.
|
||||
fn outcome(r: Res) -> Result<(), String> {
|
||||
r.map_err(|e| match e {
|
||||
PsError::Ps(name, _) => name.to_string(),
|
||||
e => format!("{e:?}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Everything the operator left: the operand stack with each string's storage, offset and length,
|
||||
/// and the operations spent.
|
||||
fn state(it: &Interp) -> (String, u64) {
|
||||
(format!("{:?}", it.stack), it.ops_left())
|
||||
}
|
||||
|
||||
/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds
|
||||
/// each call the string the last one left), and check that the two agree after every call.
|
||||
fn agree(src: &str, op: Op, steps: usize) {
|
||||
let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes()));
|
||||
// `search` and `anchorsearch` look for the same string on each call.
|
||||
let seeks = [new.stack.last().cloned(), old.stack.last().cloned()];
|
||||
for step in 0..steps {
|
||||
let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op)));
|
||||
assert_eq!(a, b, "{src} {op:?}, call {step}");
|
||||
assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}");
|
||||
// Keep walking while the operator answered true, with the string it left.
|
||||
let more = matches!(new.stack.last(), Some(Obj::Bool(true)));
|
||||
if a.is_err() || !more {
|
||||
break;
|
||||
}
|
||||
for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) {
|
||||
it.stack.pop();
|
||||
// `token` leaves the rest under the object; `search` leaves it under match and pre
|
||||
// (and `anchorsearch` under the match).
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.truncate(keep);
|
||||
// The string to look for again, or the file `token` reads on from.
|
||||
if op != Op::Token || matches!(seek, Some(Obj::File { .. })) {
|
||||
it.stack.extend(seek.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_and_search_agree_with_copying_readers() {
|
||||
let tokens = [
|
||||
"()",
|
||||
"( )",
|
||||
"(\r\n\t )",
|
||||
"(12)",
|
||||
"(12 34)",
|
||||
"(12 34)",
|
||||
"(12\r\n34)",
|
||||
"(/x {a b} (s) <41> 1.5 x)",
|
||||
"(1 {)",
|
||||
"( [ 1 ] )",
|
||||
"/x 7 def (//x {//x} y)",
|
||||
"(xx12 34 56) 2 7 getinterval",
|
||||
"(%comment only)",
|
||||
"5",
|
||||
"(12 /x {a}) /ReusableStreamDecode filter",
|
||||
"currentfile",
|
||||
];
|
||||
for src in tokens {
|
||||
agree(src, Op::Token, 16);
|
||||
}
|
||||
let searches = [
|
||||
"(abcabc) (bc)",
|
||||
"(abc) (x)",
|
||||
"(abc) ()",
|
||||
"() ()",
|
||||
"() (a)",
|
||||
"(ab) (abc)",
|
||||
"(a\nb\nc\n) (\n)",
|
||||
"/s (aa) def s s",
|
||||
"(xxab cd ef) 2 8 getinterval ( )",
|
||||
"(abc) 5",
|
||||
"5 (abc)",
|
||||
];
|
||||
for src in searches {
|
||||
agree(src, Op::Search, 8);
|
||||
agree(src, Op::AnchorSearch, 8);
|
||||
}
|
||||
// Over the operation budget: the same error, with the same operands popped.
|
||||
let big = "/h 65536 string def h (\\001)";
|
||||
let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes()));
|
||||
for it in [&mut new, &mut old] {
|
||||
let left = it.ops_left();
|
||||
assert_eq!(it.spend(left.saturating_sub(10)), Ok(()));
|
||||
}
|
||||
let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search)));
|
||||
assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}");
|
||||
assert_eq!((a, state(&new)), (b, state(&old)));
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
/// The results share the string's storage: a write to the string after `token` or `search` shows
|
||||
/// in what they left.
|
||||
#[test]
|
||||
fn token_and_search_results_see_later_writes() {
|
||||
let check = super::tests::check;
|
||||
check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq");
|
||||
check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and");
|
||||
check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq");
|
||||
check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq");
|
||||
}
|
||||
|
||||
/// `token` on a string, `search` and `anchorsearch` copy neither string.
|
||||
#[test]
|
||||
fn token_and_search_copy_no_string() {
|
||||
for (src, op) in [
|
||||
("(12 34 56 78)", Op::Token),
|
||||
("(abc def ghi) ( )", Op::Search),
|
||||
("(abc def ghi) (xyz)", Op::Search),
|
||||
("(abc def ghi) (abc)", Op::AnchorSearch),
|
||||
("(abc def ghi) (def)", Op::AnchorSearch),
|
||||
] {
|
||||
let mut it = after(src.as_bytes());
|
||||
VALUES_COPIED.with(|n| n.set(0));
|
||||
assert_eq!(it.op(op), Ok(()), "{src} {op:?}");
|
||||
assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}");
|
||||
it.release();
|
||||
}
|
||||
}
|
||||
|
||||
/// The median of `runs`.
|
||||
fn median(runs: &[Duration]) -> Duration {
|
||||
let mut sorted = runs.to_vec();
|
||||
sorted.sort();
|
||||
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a walk records of each result: a string's length and first bytes, any other object whole.
|
||||
fn mark(o: &Obj, h: &mut impl Hasher) {
|
||||
match o {
|
||||
Obj::Str(s) => {
|
||||
s.len().hash(h);
|
||||
s.borrow().iter().take(16).for_each(|b| b.hash(h));
|
||||
}
|
||||
o => format!("{o:?}").hash(h),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy
|
||||
/// or in place: how long it took, the calls made, and a hash of every result and of the operations
|
||||
/// spent. The interpreter is made before the clock starts.
|
||||
fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) {
|
||||
let mut it = after(b"");
|
||||
it.stack.push(Obj::Str(Shared::new(data.to_vec())));
|
||||
let mut calls = 0;
|
||||
let mut h = DefaultHasher::new();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if let Some(seek) = seek {
|
||||
it.stack.push(Obj::Str(Shared::new(seek.to_vec())));
|
||||
}
|
||||
let r = if copy { by_copy(&mut it, op) } else { it.op(op) };
|
||||
assert_eq!(r, Ok(()));
|
||||
calls += 1;
|
||||
if !matches!(it.stack.pop(), Some(Obj::Bool(true))) {
|
||||
break;
|
||||
}
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.stack.truncate(keep);
|
||||
}
|
||||
let took = start.elapsed();
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.ops_left().hash(&mut h);
|
||||
it.release();
|
||||
(took, calls, h.finish())
|
||||
}
|
||||
|
||||
/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the
|
||||
/// same, and print every run and the medians.
|
||||
fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) {
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let mut calls = 0;
|
||||
for run in 0..7 {
|
||||
let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] };
|
||||
let mut got = vec![];
|
||||
for copy in order {
|
||||
let (took, n, last) = walk(data, op, seek, copy);
|
||||
if copy {
|
||||
old.push(took)
|
||||
} else {
|
||||
new.push(took)
|
||||
}
|
||||
calls = n;
|
||||
got.push((n, last));
|
||||
}
|
||||
assert!(got.first() == got.get(1), "{what}: the readers differ");
|
||||
}
|
||||
let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0);
|
||||
println!("{what}: {} bytes, {calls} calls", data.len());
|
||||
println!(" by copy, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
println!(" in place, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
let (o, w) = (median(&old), median(&new));
|
||||
println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
|
||||
}
|
||||
|
||||
/// Times `token` and `search` walking a string by what each call leaves, against the copying
|
||||
/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names
|
||||
/// for `token` and of 128-byte lines for `search`. Run it in release:
|
||||
/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn string_walks_timed() {
|
||||
for kib in [4, 64, 512] {
|
||||
let size = kib * 1024;
|
||||
let mut words = Vec::with_capacity(size + 16);
|
||||
let mut i = 0u32;
|
||||
while words.len() < size {
|
||||
let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") };
|
||||
words.extend_from_slice(w.as_bytes());
|
||||
i += 1;
|
||||
}
|
||||
compare(&format!("token, {kib} KiB"), &words, Op::Token, None);
|
||||
let lines: Vec<u8> = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect();
|
||||
compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n"));
|
||||
}
|
||||
}
|
||||
@@ -1636,6 +1636,33 @@ fn doc_json(s: &mut Server) -> Value {
|
||||
serde_json::from_str(&text_of(&r)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_refused_by_a_later_operation_changes_nothing() {
|
||||
let mut s = server();
|
||||
let count = |s: &mut Server| -> u64 {
|
||||
let r = call(s, 90, "inspect_document", json!({}));
|
||||
serde_json::from_str::<Value>(&text_of(&r)).unwrap()["objects"].as_u64().unwrap()
|
||||
};
|
||||
let base = count(&mut s);
|
||||
let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50})));
|
||||
let before = doc_json(&mut s);
|
||||
for (id, args, says) in [
|
||||
(2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"),
|
||||
(3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"),
|
||||
(4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"),
|
||||
(5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"),
|
||||
(6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"),
|
||||
] {
|
||||
let t = call(&mut s, id, "transform", args.clone());
|
||||
assert_eq!(t["isError"], true, "{args}: {t}");
|
||||
assert!(text_of(&t).contains(says), "{args}: {t}");
|
||||
assert_eq!(doc_json(&mut s), before, "{args}");
|
||||
}
|
||||
// No undo step was recorded: one undo removes the rectangle.
|
||||
assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false);
|
||||
assert_eq!(count(&mut s), base, "one undo removes the rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_text_rejects_invalid_path_effects_before_editing() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"transform",
|
||||
"Transform",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": {"type": "array", "items": {"type": "integer"}},
|
||||
|
||||
@@ -302,6 +302,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
// Each operation is its own command: check the params the later ones refuse before the first
|
||||
// runs, so a refused request changes nothing.
|
||||
fn bad(cmd: &'static str) -> impl Fn(String) -> String {
|
||||
move |e| format!("invalid parameters for `{cmd}`: {e}")
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?;
|
||||
}
|
||||
let reflect = a.get("reflect").and_then(Value::as_str);
|
||||
if let Some(axis) = reflect {
|
||||
vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?;
|
||||
}
|
||||
let shear = a.get("shear").and_then(Value::as_f64);
|
||||
if let Some(sh) = shear {
|
||||
vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?;
|
||||
}
|
||||
select_ids(b, a)?;
|
||||
// With `copy`, the first operation duplicates and the rest transform the copy (the new selection).
|
||||
let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false));
|
||||
@@ -322,17 +340,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String>
|
||||
exec(b, "object.rotate", with(json!({"angle": r})))?;
|
||||
done.push("rotate");
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?;
|
||||
done.push("scale");
|
||||
}
|
||||
if let Some(axis) = a.get("reflect").and_then(Value::as_str) {
|
||||
if let Some(axis) = reflect {
|
||||
exec(b, "object.reflect", with(json!({"axis": axis})))?;
|
||||
done.push("reflect");
|
||||
}
|
||||
if let Some(sh) = a.get("shear").and_then(Value::as_f64) {
|
||||
if let Some(sh) = shear {
|
||||
exec(b, "object.shear", with(json!({"angle": sh})))?;
|
||||
done.push("shear");
|
||||
}
|
||||
|
||||
@@ -166,6 +166,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"),
|
||||
("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"),
|
||||
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
|
||||
(
|
||||
"view.refreshMonitorProfile",
|
||||
"Refresh Monitor Profile",
|
||||
"",
|
||||
"{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)",
|
||||
),
|
||||
(
|
||||
"edit.autoSpellCheck",
|
||||
"Auto Spell Check",
|
||||
@@ -894,6 +900,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
("help.about", "About VectorCraft", "", "{}"),
|
||||
("help.checkForUpdates", "Check for Updates…", "", "{}"),
|
||||
("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"),
|
||||
(
|
||||
"help.discover",
|
||||
"VectorCraft Help…",
|
||||
"F1",
|
||||
"{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}",
|
||||
),
|
||||
(
|
||||
"help.discover.search",
|
||||
"Search",
|
||||
"",
|
||||
"{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result",
|
||||
),
|
||||
(
|
||||
"help.discover.choose",
|
||||
"Select",
|
||||
"",
|
||||
"{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}",
|
||||
),
|
||||
("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"),
|
||||
(
|
||||
"help.safeMode",
|
||||
"Safe Mode…",
|
||||
@@ -947,7 +972,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.brushOptions",
|
||||
"Brush Options…",
|
||||
"",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
|
||||
),
|
||||
(
|
||||
"ui.brushObjectOptions",
|
||||
@@ -1001,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.symbolOptions",
|
||||
"Symbol Options…",
|
||||
"F8",
|
||||
"{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}",
|
||||
"{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error",
|
||||
),
|
||||
(
|
||||
"tool.options",
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
|
||||
//! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along
|
||||
//! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes
|
||||
//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]), the
|
||||
//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common
|
||||
//! tangents of two convex outlines ([`common_tangents`]), the
|
||||
//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes
|
||||
//! ([`tangent_circles`]).
|
||||
|
||||
mod bridge;
|
||||
mod crossings;
|
||||
mod dashes;
|
||||
mod extend;
|
||||
@@ -25,6 +27,7 @@ use std::collections::BTreeSet;
|
||||
use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
|
||||
|
||||
pub use bridge::{BridgeError, circle_of, smooth_bridge};
|
||||
pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at};
|
||||
pub use dashes::{DashSpec, Piece, divide_dashes};
|
||||
pub use extend::{ExtendMode, extend_length_to, extend_open};
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both
|
||||
//! circles from outside, so the outline runs on smoothly from each circle into the bridge.
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU};
|
||||
|
||||
use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
|
||||
|
||||
use super::Circle;
|
||||
|
||||
/// How far (as a share of the radius) a path's outline may stray from a circle and still be read
|
||||
/// as that circle.
|
||||
const ROUND: f64 = 1e-3;
|
||||
/// Points [`circle_of`] checks on each segment, its ends included.
|
||||
const SAMPLES: usize = 9;
|
||||
|
||||
/// Why [`smooth_bridge`] makes no outline.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BridgeError {
|
||||
/// One circle is inside the other (or they share a center).
|
||||
Inside,
|
||||
/// The circles are too far apart for the radius: the two arcs would not reach both circles,
|
||||
/// or would cross before they do.
|
||||
TooFar,
|
||||
/// A radius or circle that is not a finite size above 0, or an outline too large for `f64`.
|
||||
Bad,
|
||||
}
|
||||
|
||||
/// The circle `path` draws: one closed subpath whose outline stays within 0.1% of its radius of
|
||||
/// a circle all the way around, once. `None` for any other path.
|
||||
pub fn circle_of(path: &PathData) -> Option<Circle> {
|
||||
let [sp] = path.subpaths.as_slice() else { return None };
|
||||
if !sp.closed || sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let b = path.bounds()?;
|
||||
let (w, h) = (b.width(), b.height());
|
||||
if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) || (w - h).abs() > ROUND * w.max(h) {
|
||||
return None;
|
||||
}
|
||||
let (center, radius) = (b.center(), (w + h) / 4.0);
|
||||
let off = |q: Point| (q.distance(center) - radius).abs() > ROUND * radius;
|
||||
for k in 0..sp.segment_count() {
|
||||
let seg = sp.segment(k);
|
||||
if (0..SAMPLES).any(|i| off(seg.eval(i as f64 / (SAMPLES - 1) as f64))) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// Around once: a path going around twice, or back on itself, encloses a different area.
|
||||
let area = path.to_bezpath().area().abs();
|
||||
((area - PI * radius * radius).abs() <= 4.0 * ROUND * area).then_some(Circle { center, radius })
|
||||
}
|
||||
|
||||
/// The outline of circles `a` and `b` joined by two arcs of radius `radius` (pt), one on each
|
||||
/// side of the line through their centers, each touching both circles from outside. The outline
|
||||
/// runs around `a` on its side away from `b`, along one arc, around `b` on its side away from `a`
|
||||
/// and back along the other arc; every anchor is smooth, as each arc and the circle it meets share
|
||||
/// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider,
|
||||
/// gentler bridge; farther apart circles make a narrower one, until the arcs would cross.
|
||||
pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result<SubPath, BridgeError> {
|
||||
let finite = |x: f64| x.is_finite() && x > 0.0;
|
||||
let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite());
|
||||
if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points {
|
||||
return Err(BridgeError::Bad);
|
||||
}
|
||||
let axis = b.center - a.center;
|
||||
// `f64::hypot`: `Vec2::hypot` squares the length, which overflows above about 1e154 pt.
|
||||
let d = axis.x.hypot(axis.y);
|
||||
if d + a.radius.min(b.radius) <= a.radius.max(b.radius) * (1.0 + 1e-9) {
|
||||
return Err(BridgeError::Inside);
|
||||
}
|
||||
// The arcs' centers are `radius` outside both circles: where circles about the two centers,
|
||||
// `radius` larger than each, cross.
|
||||
let (ra, rb) = (radius + a.radius, radius + b.radius);
|
||||
if !ra.is_finite() || !rb.is_finite() {
|
||||
return Err(BridgeError::Bad);
|
||||
}
|
||||
// Halves and no squares, so no step overflows while the lengths fit in `f64`.
|
||||
let half = ra / 2.0 + rb / 2.0;
|
||||
if d / 2.0 > half {
|
||||
return Err(BridgeError::TooFar);
|
||||
}
|
||||
let along = d / 2.0 + (ra - rb) / d * half;
|
||||
let across = (ra - along).max(0.0).sqrt() * (ra / 2.0 + along / 2.0).max(0.0).sqrt() * SQRT_2;
|
||||
if !along.is_finite() || !across.is_finite() {
|
||||
return Err(BridgeError::Bad);
|
||||
}
|
||||
// Each arc runs between its points on `a` and `b`, which lie towards the two centers from the
|
||||
// arc's center. Its point nearest the axis is the foot of its center on the axis when that foot
|
||||
// is between the two centers, else one of its ends, which are off the axis. So the two arcs
|
||||
// cross, leaving no neck, only when that foot is between the centers and nearer to the arc's
|
||||
// center than its radius.
|
||||
if along > 0.0 && along < d && across <= radius * (1.0 + 1e-9) {
|
||||
return Err(BridgeError::TooFar);
|
||||
}
|
||||
let u = axis / d;
|
||||
let n = Vec2::new(-u.y, u.x);
|
||||
let mut segs = vec![];
|
||||
// Each side's arc center and where its arc touches `a` and `b`.
|
||||
let side = |s: f64| {
|
||||
let p = a.center + u * along + n * (s * across);
|
||||
(p, a.center + (p - a.center) * (a.radius / ra), b.center + (p - b.center) * (b.radius / rb))
|
||||
};
|
||||
let ((p1, a1, b1), (p2, a2, b2)) = (side(1.0), side(-1.0));
|
||||
arc(&mut segs, a.center, a.radius, a1, a2, Some(-u));
|
||||
arc(&mut segs, p2, radius, a2, b2, None);
|
||||
arc(&mut segs, b.center, b.radius, b2, b1, Some(u));
|
||||
arc(&mut segs, p1, radius, b1, a1, None);
|
||||
let count = segs.len();
|
||||
let anchors: Vec<Anchor> = (0..count)
|
||||
.map(|i| {
|
||||
let (prev, seg) = (segs[(i + count - 1) % count], segs[i]);
|
||||
Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth }
|
||||
})
|
||||
.collect();
|
||||
let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) {
|
||||
return Err(BridgeError::Bad);
|
||||
}
|
||||
Ok(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both
|
||||
/// on it): through the direction `through` from the center when given, else the shorter way. In
|
||||
/// cubics of at most a quarter turn each, `from` exactly at the start and `to` at the end.
|
||||
fn arc(out: &mut Vec<CubicBez>, center: Point, r: f64, from: Point, to: Point, through: Option<Vec2>) {
|
||||
let angle = |q: Vec2| q.y.atan2(q.x);
|
||||
let start = angle(from - center);
|
||||
// The turn from `from` to `to` counter-clockwise (in the y-up sense), 0 to 2π.
|
||||
let ccw = (angle(to - center) - start).rem_euclid(TAU);
|
||||
let sweep = match through {
|
||||
Some(dir) if (angle(dir) - start).rem_euclid(TAU) <= ccw => ccw,
|
||||
Some(_) => ccw - TAU,
|
||||
None if ccw > PI => ccw - TAU,
|
||||
None => ccw,
|
||||
};
|
||||
let pieces = (sweep.abs() / FRAC_PI_2).ceil().max(1.0) as usize;
|
||||
let step = sweep / pieces as f64;
|
||||
// Handle length that makes a cubic follow the arc of `step`, signed with its direction.
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan() * r;
|
||||
let on = |t: f64| center + Vec2::new(t.cos(), t.sin()) * r;
|
||||
let tangent = |t: f64| Vec2::new(-t.sin(), t.cos());
|
||||
for i in 0..pieces {
|
||||
let (t0, t1) = (start + step * i as f64, start + step * (i + 1) as f64);
|
||||
let p0 = if i == 0 { from } else { on(t0) };
|
||||
let p3 = if i + 1 == pieces { to } else { on(t1) };
|
||||
out.push(CubicBez::new(p0, p0 + tangent(t0) * k, p3 - tangent(t1) * k, p3));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn circle(x: f64, y: f64, r: f64) -> Circle {
|
||||
Circle { center: Point::new(x, y), radius: r }
|
||||
}
|
||||
|
||||
/// Every point the outline passes through, 32 to a segment.
|
||||
fn outline(sp: &SubPath) -> Vec<Point> {
|
||||
(0..sp.segment_count()).flat_map(|k| (0..32).map(move |i| sp.segment(k).eval(i as f64 / 32.0))).collect()
|
||||
}
|
||||
|
||||
/// The outline crosses the vertical line at `x` at these y values, top to bottom.
|
||||
fn crossings_at(sp: &SubPath, x: f64) -> Vec<f64> {
|
||||
let pts = outline(sp);
|
||||
let mut ys: Vec<f64> = (0..pts.len())
|
||||
.filter_map(|i| {
|
||||
let (p, q) = (pts[i], pts[(i + 1) % pts.len()]);
|
||||
((p.x - x) * (q.x - x) <= 0.0 && p.x != q.x).then(|| p.y + (q.y - p.y) * (x - p.x) / (q.x - p.x))
|
||||
})
|
||||
.collect();
|
||||
ys.sort_by(f64::total_cmp);
|
||||
ys
|
||||
}
|
||||
|
||||
/// The bridge's width at `x`, from the outline's crossings there.
|
||||
fn width_at(sp: &SubPath, x: f64) -> f64 {
|
||||
let ys = crossings_at(sp, x);
|
||||
ys.last().unwrap() - ys.first().unwrap()
|
||||
}
|
||||
|
||||
fn assert_smooth(sp: &SubPath) {
|
||||
for a in sp.anchors.iter() {
|
||||
let (i, o) = (a.p - a.h_in, a.h_out - a.p);
|
||||
assert!(i.hypot() > 1e-6 && o.hypot() > 1e-6, "both handles at {a:?}");
|
||||
assert!(i.cross(o).abs() <= 1e-9 * i.hypot() * o.hypot() && i.dot(o) > 0.0, "the outline turns at {a:?}");
|
||||
assert_eq!(a.kind, AnchorKind::Smooth);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each point of the outline is on circle `c` or outside it.
|
||||
fn outside(sp: &SubPath, c: Circle) -> bool {
|
||||
outline(sp).iter().all(|p| p.distance(c.center) >= c.radius - 1e-3)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_equal_circles_join_with_a_neck_narrower_than_the_circles() {
|
||||
let (a, b) = (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0));
|
||||
let sp = smooth_bridge(a, b, 20.0).unwrap();
|
||||
assert!(sp.closed);
|
||||
assert_smooth(&sp);
|
||||
// The arcs' centers are 40 from each circle's center: (30, ±√700), so the neck at x = 30 is
|
||||
// 2 × (√700 − 20) wide.
|
||||
let neck = 2.0 * (700f64.sqrt() - 20.0);
|
||||
assert!((width_at(&sp, 30.0) - neck).abs() < 1e-2, "{}", width_at(&sp, 30.0));
|
||||
assert!(width_at(&sp, 30.0) < width_at(&sp, 10.0));
|
||||
// Around each circle on its far side, and symmetric.
|
||||
let ys = crossings_at(&sp, -10.0);
|
||||
assert!((ys[0] + 300f64.sqrt()).abs() < 1e-2 && (ys[1] - 300f64.sqrt()).abs() < 1e-2, "{ys:?}");
|
||||
assert!((width_at(&sp, 50.0) - width_at(&sp, 10.0)).abs() < 1e-2);
|
||||
let b = PathData::single(sp).bounds().unwrap();
|
||||
// Within the cubics' own error from a true circle (about 0.03% of the radius).
|
||||
assert!((b.x0 + 20.0).abs() < 1e-2 && (b.x1 - 80.0).abs() < 1e-2 && (b.y1 - 20.0).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arcs_touch_both_circles_and_run_on_from_them() {
|
||||
for (a, b, r) in [
|
||||
(circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0), 20.0),
|
||||
(circle(10.0, 5.0, 30.0), circle(70.0, 40.0, 8.0), 40.0),
|
||||
(circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 15.0), 10.0),
|
||||
] {
|
||||
let sp = smooth_bridge(a, b, r).unwrap();
|
||||
assert_smooth(&sp);
|
||||
// The outline goes around the outside of both circles, never into either.
|
||||
assert!(outside(&sp, a) && outside(&sp, b));
|
||||
// On each circle the outline leaves along the circle's tangent, where an arc takes over
|
||||
// as well: two anchors on each circle are where an arc meets it.
|
||||
for c in [a, b] {
|
||||
let on: Vec<_> = sp.anchors.iter().filter(|q| (q.p.distance(c.center) - c.radius).abs() < 1e-6).collect();
|
||||
assert!(on.len() >= 2, "{}", on.len());
|
||||
for q in on {
|
||||
let radial = q.p - c.center;
|
||||
assert!(radial.dot(q.h_out - q.p).abs() <= 1e-6 * radial.hypot() * (q.h_out - q.p).hypot(), "{q:?}");
|
||||
}
|
||||
}
|
||||
assert!(sp.anchors.len() <= 12, "{}", sp.anchors.len());
|
||||
// Every segment off the two circles is part of an arc of radius `r` that touches both
|
||||
// circles from outside: its center is `r` farther than each circle's radius from it.
|
||||
let on = |q: Point, c: Circle| (q.distance(c.center) - c.radius).abs() < 1e-3;
|
||||
let mut arcs = 0;
|
||||
for k in 0..sp.segment_count() {
|
||||
let seg = sp.segment(k);
|
||||
let (p0, pm, p1) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0));
|
||||
if on(pm, a) || on(pm, b) {
|
||||
continue;
|
||||
}
|
||||
arcs += 1;
|
||||
let (center, radius) = circumcircle(p0, pm, p1);
|
||||
assert!((radius - r).abs() < 1e-2 * r, "radius {radius} for {r}");
|
||||
assert!((center.distance(a.center) - (r + a.radius)).abs() < 1e-2 * r, "touches {a:?}");
|
||||
assert!((center.distance(b.center) - (r + b.radius)).abs() < 1e-2 * r, "touches {b:?}");
|
||||
}
|
||||
assert!((2..=4).contains(&arcs), "{arcs}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The circle through three points: its center and radius.
|
||||
fn circumcircle(p: Point, q: Point, s: Point) -> (Point, f64) {
|
||||
let d = 2.0 * (p.x * (q.y - s.y) + q.x * (s.y - p.y) + s.x * (p.y - q.y));
|
||||
let sq = |v: Point| v.x * v.x + v.y * v.y;
|
||||
let x = (sq(p) * (q.y - s.y) + sq(q) * (s.y - p.y) + sq(s) * (p.y - q.y)) / d;
|
||||
let y = (sq(p) * (s.x - q.x) + sq(q) * (p.x - s.x) + sq(s) * (q.x - p.x)) / d;
|
||||
let c = Point::new(x, y);
|
||||
(c, c.distance(p))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_circles_join_round_both() {
|
||||
let (a, b) = (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0));
|
||||
let sp = smooth_bridge(a, b, 40.0).unwrap();
|
||||
assert_smooth(&sp);
|
||||
let bounds = PathData::single(sp.clone()).bounds().unwrap();
|
||||
assert!((bounds.x0 + 30.0).abs() < 1e-2 && (bounds.x1 - 80.0).abs() < 1e-2 && (bounds.y0 + 30.0).abs() < 1e-2, "{bounds:?}");
|
||||
// The neck narrows from the big circle towards the small one.
|
||||
assert!(width_at(&sp, 35.0) > width_at(&sp, 50.0));
|
||||
assert!(width_at(&sp, 50.0) < 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_circles_join_at_large_radii_overlapping_or_not() {
|
||||
// With a large radius the arcs' centers lie beyond the smaller circle, so the arcs never
|
||||
// reach the axis even though their centers are nearer to it than their radius.
|
||||
for (a, b, r) in [
|
||||
(circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 100.0),
|
||||
(circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 30.0),
|
||||
(circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 50.0),
|
||||
(circle(0.0, 0.0, 30.0), circle(60.0, 0.0, 8.0), 300.0),
|
||||
] {
|
||||
let sp = smooth_bridge(a, b, r).unwrap_or_else(|e| panic!("{a:?} {b:?} {r}: {e:?}"));
|
||||
assert_smooth(&sp);
|
||||
assert!(outside(&sp, a) && outside(&sp, b));
|
||||
// The outline crosses the axis only at the two far ends: it does not cross itself.
|
||||
let pts = outline(&sp);
|
||||
let crossings = (0..pts.len()).filter(|&i| (pts[i].y > 0.0) != (pts[(i + 1) % pts.len()].y > 0.0)).count();
|
||||
assert_eq!(crossings, 2, "{a:?} {b:?} {r}");
|
||||
// It encloses more than the larger circle.
|
||||
let area = PathData::single(sp).to_bezpath().area().abs();
|
||||
assert!(area > PI * a.radius.max(b.radius).powi(2), "{area}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_touching_circles_are_joined() {
|
||||
let (a, b) = (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0));
|
||||
let sp = smooth_bridge(a, b, 10.0).unwrap();
|
||||
assert_smooth(&sp);
|
||||
// The circles cross at x = 15, y = ±√175; the bridge fills in the notch there.
|
||||
assert!(width_at(&sp, 15.0) > 2.0 * 175f64.sqrt());
|
||||
assert!(width_at(&sp, 15.0) < 40.0);
|
||||
let touching = smooth_bridge(circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 10.0).unwrap();
|
||||
assert_smooth(&touching);
|
||||
assert!(width_at(&touching, 20.0) > 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_apart_circles_and_nested_ones_make_no_bridge() {
|
||||
let (a, b) = (circle(0.0, 0.0, 10.0), circle(100.0, 0.0, 10.0));
|
||||
assert_eq!(smooth_bridge(a, b, 5.0), Err(BridgeError::TooFar), "arcs don't reach");
|
||||
// The arcs reach both circles (gap 80 < 2 × 45) but cross before they do.
|
||||
assert_eq!(smooth_bridge(a, b, 45.0), Err(BridgeError::TooFar), "no neck left");
|
||||
// A large enough radius bridges them: the neck stays open above (d/2)² − r² over 2r = 120.
|
||||
assert!(smooth_bridge(a, b, 130.0).is_ok());
|
||||
assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), 10.0), Err(BridgeError::Inside));
|
||||
assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(0.0, 0.0, 30.0), 10.0), Err(BridgeError::Inside));
|
||||
assert_eq!(smooth_bridge(a, b, 0.0), Err(BridgeError::Bad));
|
||||
assert_eq!(smooth_bridge(a, b, f64::NAN), Err(BridgeError::Bad));
|
||||
assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_circles_bridge_with_finite_anchors_or_are_refused() {
|
||||
// Squaring these lengths overflows f64.
|
||||
let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153));
|
||||
let sp = smooth_bridge(a, b, 5e153).unwrap();
|
||||
assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite())));
|
||||
assert_smooth(&sp);
|
||||
// The two radius sums fit in f64, but not their total.
|
||||
let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307));
|
||||
let sp = smooth_bridge(a, b, 1.5e308).unwrap();
|
||||
assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite())));
|
||||
// The arcs' centers would lie beyond the largest f64.
|
||||
let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308));
|
||||
assert_eq!(smooth_bridge(a, b, 1e308), Err(BridgeError::Bad));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_are_told_from_other_paths() {
|
||||
let round = shapes::ellipse(kurbo::Rect::new(10.0, 20.0, 50.0, 60.0));
|
||||
let c = circle_of(&round).unwrap();
|
||||
assert!(c.center.distance(Point::new(30.0, 40.0)) < 1e-9 && (c.radius - 20.0).abs() < 1e-9);
|
||||
let oval = shapes::ellipse(kurbo::Rect::new(0.0, 0.0, 50.0, 40.0));
|
||||
assert_eq!(circle_of(&oval), None);
|
||||
let square = PathData::single(SubPath::polyline(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true));
|
||||
assert_eq!(circle_of(&square), None);
|
||||
let mut open = round.clone();
|
||||
open.subpaths[0].closed = false;
|
||||
assert_eq!(circle_of(&open), None);
|
||||
let two = PathData::new(vec![round.subpaths[0].clone(), round.subpaths[0].clone()]);
|
||||
assert_eq!(circle_of(&two), None);
|
||||
}
|
||||
}
|
||||
+104
-27
@@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash ";
|
||||
/// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it
|
||||
/// keeps every offset.
|
||||
const PLACEHOLDER: &str = "0000000000000000";
|
||||
/// Deepest name tree searched for the editing file.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most name tree nodes searched for the editing file.
|
||||
const MAX_NODES: usize = 1 << 16;
|
||||
|
||||
/// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option<Editing> {
|
||||
editing_in(&crate::pages::open(bytes, password).ok()?)
|
||||
}
|
||||
|
||||
/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]).
|
||||
struct Search<'a> {
|
||||
/// The editing file's file specification, if one was found.
|
||||
spec: Option<Dict<'a>>,
|
||||
/// A name tree key searched names the editing file (set also when its file specification
|
||||
/// can't be read).
|
||||
keyed: bool,
|
||||
/// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched.
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// The search of a parsed PDF's attachments for the editing file.
|
||||
fn editing_file_spec(pdf: &Pdf) -> Search<'_> {
|
||||
let xref = pdf.xref();
|
||||
let Some(tree) = xref
|
||||
.get::<Dict<'_>>(xref.root_id())
|
||||
.and_then(|catalog| catalog.get::<Dict<'_>>(b"Names"))
|
||||
.and_then(|names| names.get::<Dict<'_>>(b"EmbeddedFiles"))
|
||||
else {
|
||||
return Search { spec: None, keyed: false, cut: false };
|
||||
};
|
||||
let (mut keyed, mut cut) = (false, false);
|
||||
let spec = editing_spec(tree, &mut keyed, &mut cut, xref);
|
||||
Search { spec, keyed, cut }
|
||||
}
|
||||
|
||||
/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't
|
||||
/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be
|
||||
/// resolved)? Also true when the name tree is too large to search to its end.
|
||||
pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool {
|
||||
let search = editing_file_spec(pdf);
|
||||
search.spec.is_some() || search.keyed || search.cut
|
||||
}
|
||||
|
||||
/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`]
|
||||
/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it
|
||||
/// reads.
|
||||
pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool {
|
||||
editing_file_spec(pdf).cut
|
||||
}
|
||||
|
||||
/// [`editing`] of a parsed PDF.
|
||||
pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
let xref = pdf.xref();
|
||||
let catalog = xref.get::<Dict<'_>>(xref.root_id())?;
|
||||
let tree = catalog.get::<Dict<'_>>(b"Names")?.get::<Dict<'_>>(b"EmbeddedFiles")?;
|
||||
let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?;
|
||||
let spec = editing_file_spec(pdf).spec?;
|
||||
let files = spec.get::<Dict<'_>>(b"EF")?;
|
||||
let stream = files.get::<Stream<'_>>(b"F").or_else(|| files.get::<Stream<'_>>(b"UF"))?;
|
||||
let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default();
|
||||
@@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
Some(Editing { data, intact })
|
||||
}
|
||||
|
||||
/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect
|
||||
/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path.
|
||||
fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIdentifier>, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
/// The first file specification of the editing file in the name tree `tree`, searched in order at
|
||||
/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the
|
||||
/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is
|
||||
/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is
|
||||
/// set when a key searched names the editing file, and `cut` when nodes are left unsearched.
|
||||
fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
let mut seen = HashSet::<ObjectIdentifier>::new();
|
||||
let mut nodes = vec![tree];
|
||||
let mut found = None;
|
||||
// Nodes still to be searched, counting the ones waiting in `nodes`.
|
||||
let mut left = MAX_NODES - 1;
|
||||
while let Some(node) = nodes.pop() {
|
||||
// Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut.
|
||||
if found.is_none() {
|
||||
found = node_spec(&node, keyed, xref);
|
||||
}
|
||||
let Some(kids) = node.get::<Array<'a>>(b"Kids") else { continue };
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
let mut kids: Vec<Dict<'a>> = items(&kids)
|
||||
.filter_map(|raw| match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into()),
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => Some(kid),
|
||||
_ => None,
|
||||
})
|
||||
.take(left.saturating_add(1))
|
||||
.collect();
|
||||
if kids.len() > left {
|
||||
*cut = true;
|
||||
kids.truncate(left);
|
||||
}
|
||||
left -= kids.len();
|
||||
nodes.extend(kids.into_iter().rev());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The file specification of the editing file among the name tree node `node`'s own `Names`.
|
||||
/// `keyed` is set when a key names the editing file.
|
||||
fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
if let Some(names) = node.get::<Array<'a>>(b"Names") {
|
||||
// The keys read as written, so a value that can't be resolved doesn't shift the pairs.
|
||||
let mut raw = items(&names);
|
||||
while let (Some(key), Some(_)) = (raw.next(), raw.next()) {
|
||||
let key = match key {
|
||||
MaybeRef::NotRef(Object::String(key)) => Some(key),
|
||||
MaybeRef::Ref(r) => xref.get::<PdfString<'a>>(r.into()),
|
||||
MaybeRef::NotRef(_) => None,
|
||||
};
|
||||
if key.is_some_and(|key| is_editing_name(&key)) {
|
||||
*keyed = true;
|
||||
}
|
||||
}
|
||||
let mut items = names.iter::<Object<'a>>();
|
||||
while let (Some(_), Some(spec)) = (items.next(), items.next()) {
|
||||
if let Object::Dict(spec) = spec
|
||||
@@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIden
|
||||
}
|
||||
}
|
||||
}
|
||||
if depth >= MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let kids = node.get::<Array<'a>>(b"Kids")?;
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
items(&kids).find_map(|raw| {
|
||||
let kid = match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into())?,
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => kid,
|
||||
_ => return None,
|
||||
};
|
||||
editing_spec(&kid, depth + 1, seen, xref)
|
||||
})
|
||||
None
|
||||
}
|
||||
|
||||
/// A file specification naming the editing file (current or legacy name), in any text string
|
||||
/// encoding.
|
||||
fn is_editing_file(spec: &Dict<'_>) -> bool {
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
})
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| is_editing_name(&name))
|
||||
}
|
||||
|
||||
/// A text string that is the editing file's name (current or legacy), in any encoding.
|
||||
fn is_editing_name(name: &PdfString<'_>) -> bool {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
}
|
||||
|
||||
/// The most decoded page content [`page_hash`] reads in all (bytes).
|
||||
|
||||
@@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> {
|
||||
|
||||
impl Writer {
|
||||
/// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata
|
||||
/// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in
|
||||
/// CMYK (unless the colours are converted to RGB).
|
||||
/// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency
|
||||
/// blends in CMYK (unless the colours are converted to RGB).
|
||||
pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option<i64>, cmyk: bool) -> Result<Self, PdfError> {
|
||||
let out = ColorOut::new(doc, set)?;
|
||||
let mut warnings = out.profile_notes.clone();
|
||||
@@ -111,7 +111,11 @@ impl Writer {
|
||||
created: created.map(date_time),
|
||||
modified: None,
|
||||
};
|
||||
let pdf = write::Writer::new(settings, metadata);
|
||||
// The document language (Document Setup) as the catalog's `Lang` and the XMP packet's
|
||||
// `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes
|
||||
// none rather than a guess.
|
||||
let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string);
|
||||
let pdf = write::Writer::new_with_language(settings, metadata, language);
|
||||
Ok(Self {
|
||||
pdf,
|
||||
cmyk: out.blends_cmyk(cmyk),
|
||||
|
||||
@@ -261,6 +261,18 @@ impl Opened {
|
||||
crate::editing::editing_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Does the PDF list the editing file among its attachments, also when
|
||||
/// [`editing`](Self::editing) can't read it?
|
||||
pub fn has_editing_file(&self) -> bool {
|
||||
crate::editing::has_editing_file_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Is the PDF's attachment name tree too large to search to its end? It may then list an
|
||||
/// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads.
|
||||
pub fn editing_search_cut(&self) -> bool {
|
||||
crate::editing::editing_search_cut_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it.
|
||||
pub fn illustrator_data(&self) -> Option<Vec<u8>> {
|
||||
private_data(&self.pdf)
|
||||
|
||||
@@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() {
|
||||
assert!(s.contains("/ViewerPreferences<</DisplayDocTitle true>>"), "viewers should show the document title (#3646)");
|
||||
}
|
||||
|
||||
/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any.
|
||||
fn catalog_lang(pdf: &[u8]) -> Option<String> {
|
||||
let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table");
|
||||
let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog");
|
||||
let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary");
|
||||
let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned();
|
||||
let at = catalog.find("/Lang")? + "/Lang".len();
|
||||
let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string");
|
||||
Some(rest[..rest.find(')').expect("a closed string")].to_string())
|
||||
}
|
||||
|
||||
/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in
|
||||
/// exported and printed PDFs, and the XMP packet says it too (#3644).
|
||||
#[test]
|
||||
fn the_catalog_gives_the_document_language() {
|
||||
let mut d = doc(100.0, 100.0);
|
||||
for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] {
|
||||
if let Some(language) = language {
|
||||
d.setup.language = language.into();
|
||||
}
|
||||
for opts in [PdfOptions::uncompressed(), PdfOptions::default()] {
|
||||
let bytes = export(&d, &opts).unwrap();
|
||||
assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}");
|
||||
}
|
||||
// Print to PDF writes its file with the same writer.
|
||||
let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap();
|
||||
assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed");
|
||||
let s = uncompressed(&d);
|
||||
assert!(s.contains(&format!("<dc:language><rdf:Bag><rdf:li>{tag}</rdf:li></rdf:Bag></dc:language>")), "{language:?}: {s}");
|
||||
}
|
||||
// A language without a tag (from a file) writes none rather than a guess.
|
||||
d.setup.language = "Klingon".into();
|
||||
assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None);
|
||||
}
|
||||
|
||||
/// A function or colour space built on itself is refused before the interpreter builds it (by
|
||||
/// recursion, with no cap: a stack overflow), and those of real files are read.
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user