mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 03:12:57 +01:00
Merge main into feat/3d-classic-map-art
This commit is contained in:
commit
ac6a625d52
492 files changed
+37932
-2422
No files matched your search
Generated
+1
@@ -6775,6 +6775,7 @@ dependencies = [
|
||||
"craft-stream-codecs",
|
||||
"craft-xml",
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
"heic-rs",
|
||||
|
||||
@@ -128,14 +128,17 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
|
||||
@@ -238,10 +238,12 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_script_data(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
|
||||
@@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) {
|
||||
pub(crate) async fn sleep(ms: i32) {
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most
|
||||
//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after
|
||||
//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures.
|
||||
|
||||
/// The wait after a face's first failed fetch before it is fetched again (ms).
|
||||
const RETRY_MS: i32 = 30_000;
|
||||
/// Failed fetches of a face after which it is not fetched again this session.
|
||||
pub(crate) const MAX_TRIES: u32 = 5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum State {
|
||||
Idle,
|
||||
/// Being fetched, after `tries` failed fetches.
|
||||
Loading {
|
||||
tries: u32,
|
||||
},
|
||||
Loaded,
|
||||
/// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or
|
||||
/// at once when the clock reads earlier than `failed_at`.
|
||||
Failed {
|
||||
tries: u32,
|
||||
failed_at: f64,
|
||||
retry_at: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// The fetch state of each face of a web font list, by index.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Demand {
|
||||
states: Vec<State>,
|
||||
}
|
||||
|
||||
impl Demand {
|
||||
/// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not
|
||||
/// loaded, not being fetched, and not waiting to be fetched again. They are marked as being
|
||||
/// fetched.
|
||||
pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
for &i in wanted {
|
||||
if self.states.len() <= i {
|
||||
self.states.resize(i + 1, State::Idle);
|
||||
}
|
||||
let Some(state) = self.states.get_mut(i) else { continue };
|
||||
let tries = match *state {
|
||||
State::Idle => Some(0),
|
||||
State::Loading { .. } | State::Loaded => None,
|
||||
State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries),
|
||||
};
|
||||
if let Some(tries) = tries {
|
||||
*state = State::Loading { tries };
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`.
|
||||
/// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it
|
||||
/// loaded or has failed [`MAX_TRIES`] times.
|
||||
pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option<i32> {
|
||||
let state = self.states.get_mut(i)?;
|
||||
let State::Loading { tries } = *state else { return None };
|
||||
if ok {
|
||||
*state = State::Loaded;
|
||||
return None;
|
||||
}
|
||||
let tries = tries + 1;
|
||||
let wait = RETRY_MS << (tries - 1).min(4);
|
||||
*state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) };
|
||||
(tries < MAX_TRIES).then_some(wait)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_face_is_fetched_once_and_kept() {
|
||||
let mut d = Demand::default();
|
||||
assert_eq!(d.start(&[2], 0.0), [2]);
|
||||
assert!(d.start(&[2], 1.0).is_empty(), "already being fetched");
|
||||
assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry");
|
||||
assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again");
|
||||
assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own");
|
||||
assert_eq!(d.finished(7, false, 4.0), None, "a face never started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_face_waits_longer_after_each_failure_and_then_stops() {
|
||||
let mut d = Demand::default();
|
||||
let mut now = 0.0;
|
||||
// The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first.
|
||||
for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) {
|
||||
assert_eq!(d.start(&[0], now), [0], "at {now}");
|
||||
assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}");
|
||||
assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}");
|
||||
now += f64::from(wait);
|
||||
}
|
||||
// The fifth fetch, and after it fails, none.
|
||||
assert_eq!(d.start(&[0], now), [0]);
|
||||
assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures");
|
||||
assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures");
|
||||
// A later success after failures keeps the face.
|
||||
let mut d = Demand::default();
|
||||
d.start(&[1], 0.0);
|
||||
assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS));
|
||||
assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]);
|
||||
assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None);
|
||||
assert!(d.start(&[1], 1e12).is_empty());
|
||||
}
|
||||
|
||||
/// While a face is fetched again after a failure, neither the interface asking for its script
|
||||
/// again nor the retry timer starts a second fetch of it.
|
||||
#[test]
|
||||
fn a_face_being_fetched_again_is_not_fetched_twice_at_once() {
|
||||
let mut d = Demand::default();
|
||||
d.start(&[0], 0.0);
|
||||
assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS));
|
||||
let retry = f64::from(RETRY_MS);
|
||||
assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice");
|
||||
assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again");
|
||||
assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer");
|
||||
assert_eq!(d.finished(0, true, retry + 2_000.0), None);
|
||||
assert!(d.start(&[0], 1e12).is_empty(), "loaded");
|
||||
}
|
||||
|
||||
/// A clock that reads earlier than the failure (one set back meanwhile) does not hold the
|
||||
/// retry back: the timer that asks for it has waited already.
|
||||
#[test]
|
||||
fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() {
|
||||
let mut d = Demand::default();
|
||||
let failed_at = 1e12;
|
||||
d.start(&[0], failed_at);
|
||||
assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS));
|
||||
assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting");
|
||||
assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
//! Craft-fonts faces served beside the wasm (`fonts/<sha16>/…`, copied by
|
||||
//! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup`
|
||||
//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks
|
||||
//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped:
|
||||
//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing.
|
||||
//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and
|
||||
//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the
|
||||
//! interface's own text needs its script. The browser checks each file against its SHA-256
|
||||
//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With
|
||||
//! `WEB_FONTS` empty (built without craft-fonts) these do nothing.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_text::craft_fonts::demand_fonts;
|
||||
use vectorcraft_text::{FontDb, WEB_FONTS, WebFont};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::demand::Demand;
|
||||
|
||||
/// Per startup face: the page shows its loading text meanwhile.
|
||||
const STARTUP_TIMEOUT_MS: i32 = 20_000;
|
||||
/// Per background face.
|
||||
@@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4;
|
||||
thread_local! {
|
||||
/// The background fetch runs once per page, though a graphics restart creates the app again.
|
||||
static BACKGROUND_STARTED: Cell<bool> = const { Cell::new(false) };
|
||||
/// The `demand` faces' fetches.
|
||||
static DEMAND: RefCell<Demand> = RefCell::new(Demand::default());
|
||||
/// The running app's context, asked for a frame when a `demand` face arrives (none before the
|
||||
/// app starts: its first frame looks through the faces loaded by then).
|
||||
static REPAINT: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or
|
||||
/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those
|
||||
/// characters with it from then on. Set as the interface's missing-glyph handler
|
||||
/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name
|
||||
/// before the app starts.
|
||||
pub fn want_chars(chars: &[char]) {
|
||||
let wanted = demand_fonts(WEB_FONTS, chars.iter().copied());
|
||||
if !wanted.is_empty() {
|
||||
fetch_demand(&wanted);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start.
|
||||
/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives.
|
||||
fn fetch_demand(wanted: &[usize]) {
|
||||
for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) {
|
||||
let Some(f) = WEB_FONTS.get(i) else { continue };
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let ok = load(f, BACKGROUND_TIMEOUT_MS).await;
|
||||
let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms()));
|
||||
if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if let Some(wait) = retry {
|
||||
// A second longer, so a clock the browser coarsens still reads the wait as over.
|
||||
crate::api::sleep(wait.saturating_add(1_000)).await;
|
||||
fetch_demand(&[i]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch and register the `startup` faces (one after the other). Returns how many loaded.
|
||||
pub async fn load_startup_fonts() -> usize {
|
||||
let mut loaded = 0;
|
||||
for f in WEB_FONTS.iter().filter(|f| f.startup) {
|
||||
for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) {
|
||||
if load(f, STARTUP_TIMEOUT_MS).await {
|
||||
loaded += 1;
|
||||
}
|
||||
@@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize {
|
||||
}
|
||||
|
||||
/// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for
|
||||
/// a frame after each so the font menus and the canvas pick it up. Only the first call does
|
||||
/// anything.
|
||||
/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches
|
||||
/// anything; each call makes `ctx` the context a `demand` face asks for a frame.
|
||||
pub fn spawn_background_fonts(ctx: egui::Context) {
|
||||
REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone()));
|
||||
if BACKGROUND_STARTED.with(|s| s.replace(true)) {
|
||||
return;
|
||||
}
|
||||
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect());
|
||||
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect());
|
||||
let next = Rc::new(Cell::new(0usize));
|
||||
for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) {
|
||||
let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone());
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod demand;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -81,6 +81,11 @@ pub fn start() {
|
||||
return;
|
||||
};
|
||||
detect_language();
|
||||
// The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the
|
||||
// startup fonts, without holding up the start. Text in those scripts painted later (a saved
|
||||
// interface language, another one chosen, a layer or file name) has its face fetched then.
|
||||
vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars);
|
||||
crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::<Vec<_>>());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Before the first frame, which looks for copies a crash left behind.
|
||||
let locks = WebLocks::start(RECOVERY_PREFIX).await;
|
||||
|
||||
@@ -43,6 +43,16 @@ impl eframe::App for App {
|
||||
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
|
||||
/// app's raw-input hook while the keyboard user is unconfined.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// Without vsync, a main-window frame starts no sooner than the minimum interval after the
|
||||
// last one. eframe runs this hook once per frame, shown or not, before egui reads the input.
|
||||
// The frame's time moves on by the wait, and the hang report's frame time starts after it.
|
||||
if raw.viewport_id == egui::ViewportId::ROOT {
|
||||
if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) {
|
||||
std::thread::sleep(wait);
|
||||
raw.time = raw.time.map(|time| time + wait.as_secs_f64());
|
||||
}
|
||||
self.last_frame_began = Some(std::time::Instant::now());
|
||||
}
|
||||
let _timed = BEACON.enter_timed(Stage::Input);
|
||||
self.frame_start = Some(std::time::Instant::now());
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
|
||||
@@ -73,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(
|
||||
@@ -83,8 +83,9 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
PickRequest::FolderAt(folder) => return d.folder(folder),
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
@@ -98,6 +99,37 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_folder_picker_asked_for_a_folder_starts_there() {
|
||||
/// The settings a dialog was given, by name.
|
||||
#[derive(Default)]
|
||||
struct Recorded(Vec<String>);
|
||||
impl DialogSettings for Recorded {
|
||||
fn parent(self, _: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(mut self, title: &str) -> Self {
|
||||
self.0.push(format!("title {title}"));
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, _: &[impl ToString]) -> Self {
|
||||
self.0.push(format!("filter {name}"));
|
||||
self
|
||||
}
|
||||
fn folder(mut self, folder: &str) -> Self {
|
||||
self.0.push(format!("folder {folder}"));
|
||||
self
|
||||
}
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.0.push(format!("name {name}"));
|
||||
self
|
||||
}
|
||||
}
|
||||
assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]);
|
||||
assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty());
|
||||
}
|
||||
|
||||
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
|
||||
/// window and keeps it in front).
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -130,9 +162,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
|
||||
}
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
@@ -315,7 +347,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
let picked = dialog.pick_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
PickRequest::OpenMany => {
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
|
||||
}
|
||||
@@ -334,7 +366,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
// on that nil; treat the pick as cancelled instead (#5980).
|
||||
Err(()) => Box::pin(async move { Vec::new() }),
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => {
|
||||
let picked = dialog.pick_folder();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
@@ -355,7 +387,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.and_then(|w| w.window_handle().ok())
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -363,6 +395,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
|
||||
// dialogs run the window's events while they are open.
|
||||
@@ -410,6 +443,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
|
||||
@@ -142,6 +142,11 @@ struct App {
|
||||
display_profile: display_profile::Reader,
|
||||
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
|
||||
frame_start: Option<std::time::Instant>,
|
||||
/// The shortest time between the starts of two frames, while the window presents without vsync
|
||||
/// ([`presentation::min_frame_interval`]).
|
||||
min_frame: Option<std::time::Duration>,
|
||||
/// When the last frame started, after its wait for [`Self::min_frame`].
|
||||
last_frame_began: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
|
||||
@@ -365,6 +370,10 @@ fn main() -> std::process::ExitCode {
|
||||
let saved_window = saved.as_ref().and_then(|ui| ui.window);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str);
|
||||
// Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off.
|
||||
#[cfg(feature = "wgpu")]
|
||||
let low_latency_drawing =
|
||||
saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let power_env = eframe::wgpu::PowerPreference::from_env();
|
||||
#[cfg(feature = "wgpu")]
|
||||
@@ -458,10 +467,11 @@ fn main() -> std::process::ExitCode {
|
||||
let mut options = options;
|
||||
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
|
||||
// composites it, so the window answers the pointer a frame sooner (#444).
|
||||
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
|
||||
// `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing
|
||||
// asks for no vsync when neither sets the mode (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing);
|
||||
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
|
||||
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
|
||||
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing));
|
||||
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
|
||||
@@ -508,6 +518,11 @@ fn main() -> std::process::ExitCode {
|
||||
// For the hang report (`hang_watch`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
let requested_surface = options.wgpu_options.surface;
|
||||
// Without vsync, frames start at most 240 times a second (`presentation`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
let min_frame = presentation::min_frame_interval(&requested_surface);
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let min_frame = None;
|
||||
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
|
||||
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -539,6 +554,7 @@ fn main() -> std::process::ExitCode {
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
@@ -694,6 +710,8 @@ fn main() -> std::process::ExitCode {
|
||||
monitors_listed: None,
|
||||
display_profile: Default::default(),
|
||||
frame_start: None,
|
||||
min_frame,
|
||||
last_frame_began: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people
|
||||
/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first
|
||||
/// needs them.
|
||||
pub fn attach_script_data(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Script Data") {
|
||||
session.attach_script_data(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -6,9 +6,17 @@
|
||||
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
|
||||
//! overrides its variable; a value that isn't one of these stops the app with a message, as
|
||||
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
|
||||
//! The surface the app asks for is logged at start-up.
|
||||
//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at
|
||||
//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the
|
||||
//! surface presents without vsync, frames start at most 240 times a second. The surface the app
|
||||
//! asks for is logged at start-up, with where its present mode came from.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The most frames a second the window draws while it presents without vsync.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub const UNSYNCED_FRAME_CAP: u32 = 240;
|
||||
|
||||
/// A present mode the command line or the environment can ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -96,25 +104,44 @@ impl Overrides {
|
||||
Ok(Self { mode, latency })
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied.
|
||||
/// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and
|
||||
/// no present mode override, the mode is `novsync`.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let present_mode = match self.mode {
|
||||
Some(Mode::Fifo) => PresentMode::Fifo,
|
||||
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
|
||||
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
|
||||
None if low_latency_drawing => PresentMode::AutoNoVsync,
|
||||
None => surface.present_mode,
|
||||
};
|
||||
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The present mode and frame latency `surface` asks for, for the start-up log:
|
||||
/// "autovsync, frame latency 1", with "(override)"
|
||||
/// after a value a flag or variable set.
|
||||
/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the
|
||||
/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
|
||||
pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option<Duration> {
|
||||
use eframe::wgpu::PresentMode;
|
||||
match surface.present_mode {
|
||||
PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP),
|
||||
PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a frame waits before it starts, `since_last` after the previous frame started, so that
|
||||
/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed).
|
||||
pub fn frame_wait(min: Option<Duration>, since_last: Option<Duration>) -> Option<Duration> {
|
||||
min?.checked_sub(since_last?).filter(|wait| !wait.is_zero())
|
||||
}
|
||||
|
||||
/// The present mode and frame latency `surface` asks for, for the start-up log:
|
||||
/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and
|
||||
/// "(preference)" after a present mode Low-Latency Drawing set.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let mode = match surface.present_mode {
|
||||
PresentMode::AutoVsync => "autovsync",
|
||||
@@ -126,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override
|
||||
};
|
||||
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
let tag = |set: bool| if set { " (override)" } else { "" };
|
||||
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
|
||||
let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) };
|
||||
format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -224,20 +252,99 @@ mod tests {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
// No override: the surface the app asks for is unchanged.
|
||||
assert_eq!(Overrides::default().apply(app), app);
|
||||
assert_eq!(Overrides::default().apply(app, false), app);
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app);
|
||||
let s = latency.apply(app, false);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
|
||||
assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)");
|
||||
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
|
||||
let s = fifo.apply(app);
|
||||
let s = fifo.apply(app, false);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
|
||||
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
|
||||
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
let s = novsync.apply(app);
|
||||
let s = novsync.apply(app, false);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
|
||||
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
|
||||
assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)");
|
||||
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
|
||||
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
|
||||
assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default");
|
||||
}
|
||||
|
||||
/// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an
|
||||
/// explicit Immediate or Mailbox; off, the app's surface is exactly its own.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let none = Overrides::default();
|
||||
assert_eq!(none.apply(app, false), app);
|
||||
let s = none.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::AutoNoVsync);
|
||||
assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency);
|
||||
let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}"));
|
||||
// A latency override still applies with the preference's mode.
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app, true);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)");
|
||||
}
|
||||
|
||||
/// The flag and the variable each set the present mode over Low-Latency Drawing.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_flag_and_the_variable_win_over_low_latency_drawing() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let flag = parse(&["--present-mode", "fifo"]).unwrap();
|
||||
let s = flag.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::Fifo);
|
||||
assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true));
|
||||
let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap();
|
||||
let s = var.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::AutoVsync);
|
||||
assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true));
|
||||
// The flag wins over the variable, and both over the preference.
|
||||
let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap();
|
||||
assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo);
|
||||
}
|
||||
|
||||
/// Frames start at most 240 times a second without vsync, from the preference or an override,
|
||||
/// and the display paces them with vsync.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let cap = Duration::from_secs(1) / 240;
|
||||
assert_eq!(cap.as_nanos(), 4_166_666);
|
||||
assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap));
|
||||
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap));
|
||||
assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None);
|
||||
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None);
|
||||
for (mode, capped) in [
|
||||
(PresentMode::Immediate, true),
|
||||
(PresentMode::Mailbox, true),
|
||||
(PresentMode::AutoNoVsync, true),
|
||||
(PresentMode::Fifo, false),
|
||||
(PresentMode::FifoRelaxed, false),
|
||||
(PresentMode::AutoVsync, false),
|
||||
] {
|
||||
let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) };
|
||||
assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_waits_out_the_rest_of_the_minimum_interval() {
|
||||
let min = Some(Duration::from_millis(4));
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3)));
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None);
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None);
|
||||
assert_eq!(frame_wait(min, None), None, "the first frame starts at once");
|
||||
assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync");
|
||||
}
|
||||
}
|
||||
+238
-1
@@ -753,6 +753,229 @@ impl Brush {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- stroke options ----------
|
||||
|
||||
/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]).
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ScatterOptions {
|
||||
size: (f64, f64),
|
||||
spacing: (f64, f64),
|
||||
scatter: (f64, f64),
|
||||
rotation: (f64, f64),
|
||||
modes: Option<[Variation; 4]>,
|
||||
rotation_relative_to_path: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
/// The Art brush fields a stroke can set for itself.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ArtOptions {
|
||||
width: f64,
|
||||
width_mode: Option<Variation>,
|
||||
width_max: Option<f64>,
|
||||
flip_along: bool,
|
||||
flip_across: bool,
|
||||
overlap: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
/// The Pattern brush fields a stroke can set for itself.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PatternOptions {
|
||||
scale: f64,
|
||||
spacing: f64,
|
||||
fit: PatternFit,
|
||||
flip_along: bool,
|
||||
flip_across: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
impl BrushKind {
|
||||
/// The definition fields, by their `brush.options` names, that one stroke can set for itself
|
||||
/// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle
|
||||
/// brush has none.
|
||||
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
|
||||
match self {
|
||||
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
|
||||
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
|
||||
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Bristle(_) => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the
|
||||
/// values are a `null` `modes`, so a stroke that sets them so keeps that setting.
|
||||
fn option_values(&self) -> serde_json::Value {
|
||||
let v = match self {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| {
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.entry("modes").or_insert(serde_json::Value::Null);
|
||||
}
|
||||
v
|
||||
}),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions {
|
||||
size: s.size,
|
||||
spacing: s.spacing,
|
||||
scatter: s.scatter,
|
||||
rotation: s.rotation,
|
||||
modes: s.modes,
|
||||
rotation_relative_to_path: s.rotation_relative_to_path,
|
||||
colorization: s.colorization,
|
||||
}),
|
||||
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
|
||||
width: a.width,
|
||||
width_mode: a.width_mode,
|
||||
width_max: a.width_max,
|
||||
flip_along: a.flip_along,
|
||||
flip_across: a.flip_across,
|
||||
overlap: a.overlap,
|
||||
colorization: a.colorization,
|
||||
}),
|
||||
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
|
||||
scale: p.scale,
|
||||
spacing: p.spacing,
|
||||
fit: p.fit,
|
||||
flip_along: p.flip_along,
|
||||
flip_across: p.flip_across,
|
||||
colorization: p.colorization,
|
||||
}),
|
||||
BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())),
|
||||
};
|
||||
v.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives
|
||||
/// them). An error when a value is of the wrong kind.
|
||||
fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> {
|
||||
match self {
|
||||
BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?,
|
||||
BrushKind::Scatter(s) => {
|
||||
let o: ScatterOptions = serde_json::from_value(v)?;
|
||||
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
|
||||
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
let o: ArtOptions = serde_json::from_value(v)?;
|
||||
(a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across);
|
||||
(a.overlap, a.colorization) = (o.overlap, o.colorization);
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
let o: PatternOptions = serde_json::from_value(v)?;
|
||||
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
|
||||
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
}
|
||||
BrushKind::Bristle(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Stroke option value `new` with each `null` item of an array taken from the same place in
|
||||
/// `current`, an array of the same length: a stroke option that changes some items of a range or a
|
||||
/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as
|
||||
/// it is.
|
||||
pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value {
|
||||
match (new, current) {
|
||||
(serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => {
|
||||
serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect())
|
||||
}
|
||||
_ => new.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Brush {
|
||||
/// The brush as a stroke whose own settings are `options` draws it: each field of
|
||||
/// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization`
|
||||
/// object changes only the fields it gives), and the values are kept within their ranges
|
||||
/// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there
|
||||
/// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of
|
||||
/// the wrong kind.
|
||||
pub fn with_stroke_options(&self, options: &serde_json::Map<String, serde_json::Value>) -> Result<Brush, String> {
|
||||
let keys = self.kind.stroke_option_keys();
|
||||
let mut values = self.kind.option_values();
|
||||
let Some(o) = values.as_object_mut() else { return Ok(self.clone()) };
|
||||
for (k, v) in options {
|
||||
if !keys.contains(&k.as_str()) {
|
||||
continue;
|
||||
}
|
||||
match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) {
|
||||
(Some(inner), Some(fields)) if k == "colorization" => {
|
||||
for (f, fv) in fields {
|
||||
inner.insert(f.clone(), fv.clone());
|
||||
}
|
||||
}
|
||||
// Set below, once the values the modes may follow are in.
|
||||
_ if k == "modes" => {}
|
||||
_ => {
|
||||
let current = o.get(k).cloned().unwrap_or_default();
|
||||
o.insert(k.clone(), keep_items(v, ¤t));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it.
|
||||
if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut)
|
||||
&& c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift")
|
||||
&& c.get("key").is_none_or(serde_json::Value::is_null)
|
||||
{
|
||||
let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK);
|
||||
c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?);
|
||||
}
|
||||
let mut b = self.clone();
|
||||
b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?;
|
||||
if let Some(m) = options.get("modes")
|
||||
&& keys.contains(&"modes")
|
||||
{
|
||||
// A null item keeps the mode the brush with the other settings has: modes it leaves to
|
||||
// its values follow the stroke's values, as they are kept within their ranges. Modes
|
||||
// equal to those are left as the brush has them, so they keep following the values.
|
||||
b.sanitize();
|
||||
let current = match &b.kind {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(),
|
||||
_ => serde_json::Value::Null,
|
||||
};
|
||||
let modes = keep_items(m, ¤t);
|
||||
if modes != current {
|
||||
if let Some(o) = values.as_object_mut() {
|
||||
o.insert("modes".into(), modes);
|
||||
}
|
||||
b = self.clone();
|
||||
b.kind.set_option_values(values).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
b.sanitize();
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// The stroke options of `options` that make the brush draw differently: each field of
|
||||
/// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs
|
||||
/// from the brush's own, with that value (kept within its range). An error for a field the
|
||||
/// type does not take and for a value of the wrong kind.
|
||||
pub fn stroke_options_that_differ(
|
||||
&self,
|
||||
options: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
|
||||
let keys = self.kind.stroke_option_keys();
|
||||
if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
return Err(if keys.is_empty() {
|
||||
format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase())
|
||||
} else {
|
||||
format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", "))
|
||||
});
|
||||
}
|
||||
let edited = self.with_stroke_options(options)?.kind.option_values();
|
||||
let own = self.kind.option_values();
|
||||
Ok(keys
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
let v = edited.get(*k)?;
|
||||
(own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone()))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- library ----------
|
||||
|
||||
/// The brush library of `doc`: its stored brushes, or the defaults when it has none.
|
||||
@@ -842,8 +1065,22 @@ fn tolerance(scale: f64) -> f64 {
|
||||
/// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id
|
||||
/// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush,
|
||||
/// and what they draw by name that would draw one is left out ([`leave_out_brushed`]).
|
||||
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`).
|
||||
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own
|
||||
/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values
|
||||
/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is.
|
||||
pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let edited;
|
||||
let brush = if stroke.brush_options.is_empty() {
|
||||
brush
|
||||
} else {
|
||||
match brush.with_stroke_options(&stroke.brush_options) {
|
||||
Ok(b) => {
|
||||
edited = b;
|
||||
&edited
|
||||
}
|
||||
Err(_) => brush,
|
||||
}
|
||||
};
|
||||
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
|
||||
@@ -2037,3 +2038,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `options` as a stroke's own brush settings.
|
||||
fn with_options(options: serde_json::Value) -> StrokeLayer {
|
||||
StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strokes_own_options_change_its_art_and_leave_the_brush() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
let path = line(20.0, 50.0, 220.0, 50.0);
|
||||
let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0})));
|
||||
assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half));
|
||||
assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush");
|
||||
let BrushKind::Art(a) = &brush.kind else { panic!("art brush") };
|
||||
assert_eq!(a.width, 100.0, "the brush keeps its width");
|
||||
// A calligraphic stroke's own size and angle.
|
||||
let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0})));
|
||||
assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib));
|
||||
// A pattern stroke's own scale doubles the tiles across it.
|
||||
let pattern = pattern_brush(PatternFit::Stretch, false);
|
||||
let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height();
|
||||
let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height();
|
||||
assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_options_are_checked_and_kept_within_their_ranges() {
|
||||
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// Out of range: clamped; equal to the brush's own value: left out.
|
||||
let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap();
|
||||
assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0}));
|
||||
// A field the type does not take, and a value of the wrong kind, are errors.
|
||||
assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle"));
|
||||
assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err());
|
||||
let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
|
||||
assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err());
|
||||
assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty());
|
||||
// A colorization object changes only the fields it gives: Hue Shift keeps the key it has.
|
||||
let key = Color::rgb(0.0, 0.0, 1.0);
|
||||
let hue = Brush {
|
||||
name: "h".into(),
|
||||
kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }),
|
||||
};
|
||||
let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap();
|
||||
assert_eq!(tints.kind.colorization(), Colorization::Tints);
|
||||
let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
|
||||
assert!(back.is_empty(), "the brush's own colorization: {back:?}");
|
||||
// Hue Shift without a key takes the art's main color, as brush.options gives it.
|
||||
let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
|
||||
let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK);
|
||||
assert_eq!(keyless["colorization"]["method"], json!("hueShift"));
|
||||
assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap());
|
||||
// Settings that do not read draw the brush as it is.
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(20.0, 50.0, 220.0, 50.0);
|
||||
let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]})));
|
||||
assert!(near(bounds(&odd).height(), 4.0, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_stroke_option_items_keep_the_items_the_stroke_has() {
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// A scatter brush at fixed sizes, with no modes of its own: they follow its values.
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) };
|
||||
let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") };
|
||||
assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's");
|
||||
// A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode.
|
||||
let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap();
|
||||
let BrushKind::Scatter(s) = e.kind else { panic!("scatter") };
|
||||
assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]);
|
||||
// The kept modes follow the values as they are kept within their ranges.
|
||||
let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap();
|
||||
let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") };
|
||||
assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]);
|
||||
// Modes that change nothing are no setting of the stroke's: they keep following its values.
|
||||
let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap();
|
||||
assert!(same.is_empty(), "{same:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() {
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// A brush whose modes are its own, and a stroke whose modes follow its values instead.
|
||||
let mut b = calli(0.0, 100.0, 3.0);
|
||||
if let BrushKind::Calligraphic(c) = &mut b.kind {
|
||||
c.modes = Some([Variation::Pressure; 3]);
|
||||
}
|
||||
let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap();
|
||||
assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0}));
|
||||
let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") };
|
||||
assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give");
|
||||
// A brush whose modes follow its values: a null `modes` is the brush's own and is left out.
|
||||
let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap();
|
||||
assert!(plain.is_empty(), "{plain:?}");
|
||||
}
|
||||
+33
-6
@@ -7,6 +7,8 @@
|
||||
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
|
||||
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
|
||||
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
|
||||
//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
|
||||
//! effects once for all of them.
|
||||
//!
|
||||
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
|
||||
//! clipping) is approximated or left out, and each such loss comes back as a warning.
|
||||
@@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6;
|
||||
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
|
||||
/// layers, guides and hidden objects are left out.
|
||||
pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
|
||||
Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as
|
||||
/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied
|
||||
/// once for all the drawings.
|
||||
pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result<Vec<DxfOutput>, String> {
|
||||
export_drawings_with(doc, opts, drawings, bake_for_drawings)
|
||||
}
|
||||
|
||||
/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when
|
||||
/// nothing changes.
|
||||
fn bake_for_drawings(doc: &Document) -> Option<Document> {
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, false, layers)
|
||||
}
|
||||
|
||||
/// [`export_drawings`] with `bake` applying the live effects.
|
||||
fn export_drawings_with(
|
||||
doc: &Document,
|
||||
opts: &DxfOptions,
|
||||
drawings: &[(Rect, bool)],
|
||||
bake: impl Fn(&Document) -> Option<Document>,
|
||||
) -> Result<Vec<DxfOutput>, String> {
|
||||
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
|
||||
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
|
||||
}
|
||||
let r = opts.region;
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
|
||||
return Err("the export region is not finite".into());
|
||||
}
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
|
||||
if drawings.is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let baked = bake(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
Ok(scene::Scene::new(doc, opts).run())
|
||||
Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() {
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// One drawing written by applying the live effects for it alone and walking the result, as each
|
||||
/// drawing of a multi-drawing export was written before [`export_drawings`].
|
||||
fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput {
|
||||
let baked = crate::bake_for_drawings(doc);
|
||||
crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run()
|
||||
}
|
||||
|
||||
/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes.
|
||||
type Written = (Vec<u8>, Vec<(String, Vec<u8>)>, Vec<String>, Vec<String>);
|
||||
|
||||
/// Every field of a written drawing, for comparing two.
|
||||
fn written(out: &DxfOutput) -> Written {
|
||||
let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect();
|
||||
(out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone())
|
||||
}
|
||||
|
||||
/// A Transform effect that moves its object `x` pt right.
|
||||
fn moved_by(mut n: Node, x: f64) -> Node {
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true });
|
||||
n
|
||||
}
|
||||
|
||||
/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect
|
||||
/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image.
|
||||
fn drawings_doc() -> Document {
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
2,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 128, 255, 255].repeat(4),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
|
||||
instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
|
||||
let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
faint.opacity = 0.5;
|
||||
faint.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 2,
|
||||
height: 2,
|
||||
xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
|
||||
});
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() {
|
||||
let d = drawings_doc();
|
||||
assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply");
|
||||
// The left and right halves cropped, the whole page uncropped, and a region off the page.
|
||||
let drawings = [
|
||||
(Rect::new(0.0, 0.0, 100.0, 100.0), true),
|
||||
(Rect::new(100.0, 0.0, 200.0, 100.0), true),
|
||||
(Rect::new(0.0, 0.0, 200.0, 100.0), false),
|
||||
(Rect::new(300.0, 0.0, 400.0, 100.0), true),
|
||||
];
|
||||
// With every option, and with images and hatches left out (which adds setting notes).
|
||||
let all_in = opts(&d);
|
||||
for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] {
|
||||
let bakes = std::cell::Cell::new(0);
|
||||
let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| {
|
||||
bakes.set(bakes.get() + 1);
|
||||
crate::bake_for_drawings(doc)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing");
|
||||
assert_eq!(outs.len(), drawings.len());
|
||||
for ((region, crop), out) in drawings.iter().zip(&outs) {
|
||||
let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() });
|
||||
assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}");
|
||||
let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap();
|
||||
assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}");
|
||||
}
|
||||
let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect();
|
||||
assert_eq!(public, outs.iter().map(written).collect::<Vec<_>>());
|
||||
// The halves hold different art, the left half a line with losses, and the region off the
|
||||
// page nothing.
|
||||
assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty());
|
||||
assert_ne!(outs[0].bytes, outs[1].bytes);
|
||||
assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty());
|
||||
if o.include_images {
|
||||
assert_eq!(outs[2].images.len(), 1);
|
||||
} else {
|
||||
assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_are_checked_before_the_live_effects_are_applied() {
|
||||
let d = drawings_doc();
|
||||
let o = opts(&d);
|
||||
let bakes = std::cell::Cell::new(0);
|
||||
let count = |doc: &Document| {
|
||||
bakes.set(bakes.get() + 1);
|
||||
crate::bake_for_drawings(doc)
|
||||
};
|
||||
let page = (d.artboards[0].rect, false);
|
||||
let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false);
|
||||
assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite");
|
||||
let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err();
|
||||
assert!(e.starts_with("scale must be a number"), "{e}");
|
||||
assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty());
|
||||
assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none");
|
||||
}
|
||||
|
||||
/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`.
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by
|
||||
/// drawing with the effects applied for each (as before [`export_drawings`]) and with
|
||||
/// [`export_drawings`], alternating, seven times each, and check that both write the same
|
||||
/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of
|
||||
/// wall-clock time.
|
||||
/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn dxf_artboards_bake_perf() {
|
||||
const BOARDS: usize = 8;
|
||||
let mut d = Document::new(200.0 * BOARDS as f64, 200.0);
|
||||
let layer = d.layers[0].id;
|
||||
let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
|
||||
let mut art = vec![];
|
||||
for i in 0..50 {
|
||||
let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0);
|
||||
art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5)));
|
||||
}
|
||||
let mut cell = Node::group(d.alloc_id(), art);
|
||||
cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"})));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) });
|
||||
for b in 0..BOARDS {
|
||||
let x0 = 200.0 * b as f64;
|
||||
for i in 0..250 {
|
||||
let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0);
|
||||
let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5);
|
||||
let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i});
|
||||
n.appearance.effects.push(effect("distort.roughen", params));
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
for i in 0..20 {
|
||||
let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0));
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf });
|
||||
d.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
}
|
||||
}
|
||||
let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() };
|
||||
let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect();
|
||||
let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::<Vec<_>>();
|
||||
let after = || export_drawings(&d, &o, &drawings).unwrap();
|
||||
let time = |f: &dyn Fn() -> Vec<DxfOutput>| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
let outs = f();
|
||||
let wall = wall.elapsed().as_secs_f64() * 1000.0;
|
||||
let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6);
|
||||
(outs, cpu, wall)
|
||||
};
|
||||
let (mut runs_before, mut runs_after) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
let (a, cpu_a, wall_a) = time(&before);
|
||||
let (b, cpu_b, wall_b) = time(&after);
|
||||
assert_eq!(a.len(), BOARDS);
|
||||
assert_eq!(a.iter().map(written).collect::<Vec<_>>(), b.iter().map(written).collect::<Vec<_>>(), "both write the same drawings");
|
||||
runs_before.push((cpu_a, wall_a));
|
||||
runs_after.push((cpu_b, wall_b));
|
||||
}
|
||||
let median = |runs: &[(Option<f64>, f64)], cpu: bool| {
|
||||
let mut v: Vec<f64> = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(v.len() / 2).copied()
|
||||
};
|
||||
for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] {
|
||||
println!(
|
||||
"{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}",
|
||||
median(runs, true),
|
||||
median(runs, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
-3
@@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 {
|
||||
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
|
||||
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
|
||||
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
|
||||
/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
|
||||
/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper
|
||||
/// as the media white point; the colorimetric Lab → CMYK table without black-point
|
||||
/// compensation, the perceptual and saturation ones with it); a profile the user
|
||||
/// loaded is the file it came from. Cached.
|
||||
pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
|
||||
static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new());
|
||||
@@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
|
||||
let bytes: Arc<[u8]> = if name == GRAY {
|
||||
icc::encode(&icc::gray_profile(name))?
|
||||
} else if BUILTIN_CMYK.contains(&name) {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
|
||||
icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
// The perceptual and saturation tables map the shadows with black-point compensation; the
|
||||
// colorimetric table is the inverse of the CMYK → Lab table, without it.
|
||||
let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?;
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?;
|
||||
let paper = match &cms.cmyk {
|
||||
CmykSpace::Generic(g) => g.paper_xyz(),
|
||||
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
|
||||
};
|
||||
let to_lab = |c| cms.cmyk_to_lab(c);
|
||||
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
|
||||
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
} else {
|
||||
icc::builtin_rgb_bytes(name)?
|
||||
}
|
||||
|
||||
@@ -133,6 +133,11 @@ pub struct GenericCmyk {
|
||||
}
|
||||
|
||||
impl GenericCmyk {
|
||||
/// Absolute XYZ (D50) of the paper.
|
||||
pub fn paper_xyz(&self) -> [f32; 3] {
|
||||
self.paper_xyz
|
||||
}
|
||||
|
||||
pub fn new(params: GenericCmykParams) -> Self {
|
||||
let paper_xyz = lab_to_xyz(params.paper);
|
||||
let mut prim = [D50; 16];
|
||||
|
||||
+26
-12
@@ -446,11 +446,20 @@ const B2A_GRID: usize = 17;
|
||||
const GAMUT_GRID: usize = 9;
|
||||
|
||||
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
|
||||
/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
|
||||
/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped,
|
||||
/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the
|
||||
/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag.
|
||||
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
|
||||
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
|
||||
/// TIFF that embedded one, #2707).
|
||||
pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
|
||||
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
|
||||
/// the ICC-absolute colorimetric intent reproduces.
|
||||
pub(super) fn cmyk_profile(
|
||||
name: &str,
|
||||
paper: [f32; 3],
|
||||
to_lab: impl Fn([f32; 4]) -> lab::Lab,
|
||||
mapped: impl Fn(lab::Lab) -> [f32; 4],
|
||||
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
|
||||
) -> ColorProfile {
|
||||
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
|
||||
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
|
||||
@@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
let l = to_lab(cmyk);
|
||||
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
|
||||
}
|
||||
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
|
||||
for i in 0..B2A_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
|
||||
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
|
||||
}
|
||||
let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| {
|
||||
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
|
||||
for i in 0..B2A_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
|
||||
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
|
||||
}
|
||||
b2a
|
||||
};
|
||||
let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric));
|
||||
// Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut.
|
||||
let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3));
|
||||
for i in 0..GAMUT_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID));
|
||||
let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0);
|
||||
gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX });
|
||||
gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX });
|
||||
}
|
||||
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
|
||||
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| {
|
||||
@@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
})
|
||||
};
|
||||
let a2b = table(4, 3, A2B_GRID, a2b);
|
||||
let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped);
|
||||
let b2a = table(3, 4, B2A_GRID, b2a);
|
||||
let gamut = table(3, 1, GAMUT_GRID, gamut);
|
||||
let mut p = ColorProfile::default();
|
||||
@@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
p.pcs = DataColorSpace::Lab;
|
||||
p.rendering_intent = RenderingIntent::RelativeColorimetric;
|
||||
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
|
||||
p.media_white_point = Some(p.white_point);
|
||||
p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])));
|
||||
p.lut_a_to_b_perceptual = Some(a2b.clone());
|
||||
p.lut_a_to_b_saturation = Some(a2b.clone());
|
||||
p.lut_a_to_b_colorimetric = Some(a2b);
|
||||
p.lut_b_to_a_perceptual = Some(b2a.clone());
|
||||
p.lut_b_to_a_saturation = Some(b2a.clone());
|
||||
p.lut_b_to_a_perceptual = Some(b2a_mapped.clone());
|
||||
p.lut_b_to_a_saturation = Some(b2a_mapped);
|
||||
p.lut_b_to_a_colorimetric = Some(b2a);
|
||||
p.gamut = Some(gamut);
|
||||
labelled(p, name)
|
||||
|
||||
@@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() {
|
||||
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
|
||||
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
|
||||
}
|
||||
// And back: an in-gamut colour separates to about the same inks.
|
||||
let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
|
||||
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
|
||||
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
|
||||
assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
|
||||
// And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is
|
||||
// the colorimetric inverse of the CMYK → Lab table, with no black-point compensation.
|
||||
for inks in [
|
||||
[0.1, 0.6, 0.8, 0.0],
|
||||
[0.5, 0.1, 0.3, 0.1],
|
||||
[0.3, 0.3, 0.3, 0.2],
|
||||
[0.05, 0.05, 0.4, 0.0],
|
||||
[0.4, 0.3, 0.3, 0.6],
|
||||
[0.6, 0.5, 0.5, 0.4],
|
||||
[0.2, 0.2, 0.2, 0.8],
|
||||
[0.0, 0.0, 0.0, 0.5],
|
||||
] {
|
||||
let srgb = cms.cmyk_to_srgb(inks, false);
|
||||
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
|
||||
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
|
||||
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again));
|
||||
assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})");
|
||||
}
|
||||
// The perceptual table keeps black-point compensation: source black separates to inks
|
||||
// that print the press's black point, as the CMS separates it with compensation.
|
||||
let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap();
|
||||
let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap();
|
||||
let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]);
|
||||
let de = delta_e2000(printed(&want), printed(&got));
|
||||
assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() {
|
||||
// CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto
|
||||
// RGB, which holds every color these profiles print, so no display gamut clips the inks.
|
||||
// Inks that print outside sRGB come back to inks that print the same color.
|
||||
for name in BUILTIN_CMYK {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap();
|
||||
for inks in
|
||||
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]]
|
||||
{
|
||||
let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]]));
|
||||
// Within the ΔE of 3 that the gamut tag counts as reproduced.
|
||||
assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_profiles_carry_their_paper_as_the_media_white() {
|
||||
let generic = generic::swop_like();
|
||||
let p = parse(&icc_bytes(GENERIC_CMYK).unwrap());
|
||||
let white = p.media_white_point.unwrap();
|
||||
let paper = lab::lab_to_xyz(generic.paper);
|
||||
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
|
||||
assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
|
||||
let rich = [0.75, 0.68, 0.67, 0.9];
|
||||
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
|
||||
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
|
||||
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
|
||||
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the
|
||||
// profile's Lab → CMYK table carries no compensation of its own).
|
||||
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
|
||||
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
|
||||
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}");
|
||||
// The screen shows what an sRGB conversion writes, compensated alike.
|
||||
let srgb = |bpc| {
|
||||
let c = icc_cmyk(bpc);
|
||||
|
||||
@@ -143,6 +143,11 @@ impl Appearance {
|
||||
pub fn fill_paint(&self) -> Paint {
|
||||
self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None)
|
||||
}
|
||||
/// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this
|
||||
/// includes lower fills in the stack; zero opacity still counts for selecting its geometry.
|
||||
pub fn has_visible_fill(&self) -> bool {
|
||||
self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none()))
|
||||
}
|
||||
pub fn stroke_paint(&self) -> Paint {
|
||||
self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,11 @@ pub struct StrokeLayer {
|
||||
/// Brush applied to the stroke (by brush name).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub brush: Option<String>,
|
||||
/// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush
|
||||
/// definition fields, by their `brush.options` names, that replace the brush's values on this
|
||||
/// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them.
|
||||
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
|
||||
pub brush_options: serde_json::Map<String, serde_json::Value>,
|
||||
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -170,6 +175,7 @@ impl StrokeLayer {
|
||||
arrow_scale: (100.0, 100.0),
|
||||
profile: None,
|
||||
brush: None,
|
||||
brush_options: serde_json::Map::new(),
|
||||
opacity: 1.0,
|
||||
blend: BlendMode::Normal,
|
||||
visible: true,
|
||||
|
||||
+14
-11
@@ -607,9 +607,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<
|
||||
|
||||
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
|
||||
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
// Each round leaves out the objects found so far (and everything inside them).
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if tops.contains(&top) {
|
||||
// Each round leaves out the objects found so far (and everything inside them). `found` holds
|
||||
// the same ids as `tops`, which keeps their order.
|
||||
let mut found: HashSet<NodeId> = tops.iter().copied().collect();
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if !found.insert(top) {
|
||||
break;
|
||||
}
|
||||
tops.push(top);
|
||||
@@ -1290,8 +1292,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
|
||||
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
|
||||
}
|
||||
|
||||
/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a
|
||||
/// miter or square cap, so the caller falls back to the full stroke check there.
|
||||
/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the
|
||||
/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit,
|
||||
/// while Miter and Square can extend beyond it.
|
||||
fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> {
|
||||
if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 {
|
||||
return None;
|
||||
@@ -1349,6 +1352,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1361,7 +1365,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
let mut strokes = n.appearance.painted_strokes();
|
||||
if !opt.outline
|
||||
&& n.appearance.fill().is_none_or(|f| f.paint.is_none())
|
||||
&& !has_fill
|
||||
&& let Some(s) = strokes.next()
|
||||
&& strokes.next().is_none()
|
||||
&& s.align == StrokeAlign::Center
|
||||
@@ -1376,10 +1380,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
path,
|
||||
p,
|
||||
s.width / 2.0 + opt.tol,
|
||||
if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 },
|
||||
if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 },
|
||||
)
|
||||
{
|
||||
if hit {
|
||||
if hit && !near_decoration {
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
@@ -1390,8 +1394,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
|
||||
return Some(k);
|
||||
}
|
||||
let filled = !n.appearance.fill_paint().is_none();
|
||||
if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) {
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
@@ -1412,7 +1415,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
|
||||
@@ -1823,6 +1823,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
|
||||
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
|
||||
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if tops.contains(&top) {
|
||||
break;
|
||||
}
|
||||
tops.push(top);
|
||||
}
|
||||
tops
|
||||
}
|
||||
|
||||
/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod
|
||||
/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the
|
||||
/// document, the group and its members, topmost first.
|
||||
fn isolated_stack(count: u32) -> (Document, NodeId, Vec<NodeId>) {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
|
||||
let below = square(&mut d, 0.0);
|
||||
d.insert(Some(l), usize::MAX, below).unwrap();
|
||||
let members: Vec<Node> = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect();
|
||||
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
|
||||
for x in [0.0, 100.0] {
|
||||
let above = square(&mut d, x);
|
||||
d.insert(Some(l), usize::MAX, above).unwrap();
|
||||
}
|
||||
ids.reverse();
|
||||
(d, g, ids)
|
||||
}
|
||||
|
||||
/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above
|
||||
/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where
|
||||
/// only the art around the group lies.
|
||||
#[test]
|
||||
fn select_behind_in_isolation_lists_a_large_stack_once() {
|
||||
let (d, g, ids) = isolated_stack(40);
|
||||
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
|
||||
assert_eq!(at(47.5, Some(g)), ids);
|
||||
assert_eq!(at(47.5, Some(g)).iter().collect::<HashSet<_>>().len(), 40, "no object twice");
|
||||
assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below");
|
||||
// At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within
|
||||
// the tolerance): `ids[k]` is member 39 - k.
|
||||
let left: Vec<NodeId> = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect();
|
||||
assert_eq!(left.len(), 20);
|
||||
assert_eq!(at(17.5, Some(g)), left);
|
||||
assert!(at(125.0, Some(g)).is_empty(), "only the square around the group");
|
||||
assert_eq!(at(125.0, None).len(), 1);
|
||||
let isolated = HitOptions { scope: Some(g), ..HitOptions::default() };
|
||||
let p = Point::new(47.5, 25.0);
|
||||
assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first");
|
||||
let (d, g, clip, art) = masked_square(false);
|
||||
let isolated = HitOptions { scope: Some(g), ..SELECTING };
|
||||
for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] {
|
||||
let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]);
|
||||
assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}");
|
||||
}
|
||||
assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides");
|
||||
assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline");
|
||||
}
|
||||
|
||||
/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden
|
||||
/// and locked objects), each object in turn isolated, and each list started with some of the
|
||||
/// objects already found: the set lookup returns what the ordered-list lookup returns, field for
|
||||
/// field.
|
||||
#[test]
|
||||
fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() {
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut next = move |n: u32| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
seed % n
|
||||
};
|
||||
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
|
||||
for _ in 0..2 + next(5) {
|
||||
let id = d.alloc_id();
|
||||
let rect = |next: &mut dyn FnMut(u32) -> u32| {
|
||||
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
|
||||
Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)))
|
||||
};
|
||||
let mut n = match next(if depth < 3 { 9 } else { 4 }) {
|
||||
4 | 5 => Node::group(id, Vec::new()),
|
||||
6 => {
|
||||
let mut g = Node::group(id, Vec::new());
|
||||
g.set_clips(true);
|
||||
g
|
||||
}
|
||||
7 => {
|
||||
let content =
|
||||
(0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect();
|
||||
Node::new(
|
||||
id,
|
||||
NodeKind::Envelope {
|
||||
content,
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp {
|
||||
style: "arc".to_string(),
|
||||
bend: 0.0,
|
||||
h: 0.0,
|
||||
v: 0.0,
|
||||
horizontal: true,
|
||||
version: 0,
|
||||
}),
|
||||
fidelity: 100.0,
|
||||
editing: next(2) == 0,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }),
|
||||
};
|
||||
n.visible = next(8) != 0;
|
||||
n.locked = next(8) == 0;
|
||||
let group = matches!(n.kind, NodeKind::Group { .. });
|
||||
d.insert(Some(parent), usize::MAX, n).unwrap();
|
||||
if group {
|
||||
fill(d, id, depth + 1, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut compared = 0;
|
||||
for round in 0..60 {
|
||||
let mut d = Document::new(120.0, 120.0);
|
||||
let layer = d.layers[0].id;
|
||||
fill(&mut d, layer, 0, &mut next);
|
||||
let mut scopes = vec![None];
|
||||
d.walk(|n| {
|
||||
if n.id != layer {
|
||||
scopes.push(Some(n.id));
|
||||
}
|
||||
});
|
||||
for _ in 0..6 {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
for &scope in &scopes {
|
||||
let opt = HitOptions { scope, ..opt };
|
||||
let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]);
|
||||
let context = format!("round {round}, {p:?}, {opt:?}");
|
||||
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}");
|
||||
if scope.is_some() {
|
||||
assert_eq!(objects_at(&d, p, opt, scope), want, "{context}");
|
||||
}
|
||||
for found in 1..want.len() {
|
||||
let start = want[..found].to_vec();
|
||||
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found");
|
||||
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found");
|
||||
}
|
||||
compared += usize::from(!want.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(compared > 500, "only {compared} non-empty lists compared");
|
||||
}
|
||||
|
||||
/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup
|
||||
/// against the ordered-list lookup, alternating the two in one process:
|
||||
/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`.
|
||||
#[test]
|
||||
#[ignore = "a timing, not a check"]
|
||||
fn select_behind_isolation_timing() {
|
||||
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
|
||||
fn clock(start: std::time::Instant) -> u128 {
|
||||
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
|
||||
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
|
||||
}
|
||||
type Lookup = fn(&Document, Point, HitOptions, Option<NodeId>, Vec<NodeId>) -> Vec<NodeId>;
|
||||
let start = std::time::Instant::now();
|
||||
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
|
||||
let p = Point::new(47.5, 25.0);
|
||||
for count in [200, 1_000] {
|
||||
let (d, g, ids) = isolated_stack(count);
|
||||
let opt = HitOptions { scope: Some(g), ..HitOptions::default() };
|
||||
assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids);
|
||||
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids);
|
||||
// The time per call of `f`: batches of calls double until one takes at least 100 ms.
|
||||
let per_call = |f: Lookup| {
|
||||
let mut calls = 1u32;
|
||||
loop {
|
||||
let t = clock(start);
|
||||
for _ in 0..calls {
|
||||
std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![]));
|
||||
}
|
||||
let spent = clock(start) - t;
|
||||
if spent >= 100_000_000 || calls >= 1 << 20 {
|
||||
return (spent as f64 / f64::from(calls), calls);
|
||||
}
|
||||
calls *= 2;
|
||||
}
|
||||
};
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
old.push(per_call(objects_at_repeated_after_by_list));
|
||||
new.push(per_call(objects_at_repeated_after));
|
||||
}
|
||||
old.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
new.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let (o, n) = (old[3], new[3]);
|
||||
println!(
|
||||
"{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs",
|
||||
o.0 / 1e6,
|
||||
o.1,
|
||||
n.0 / 1e6,
|
||||
n.1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
|
||||
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
|
||||
/// one instance and 100 pt lower by an instance in a group.
|
||||
|
||||
+218
-10
@@ -117,6 +117,29 @@ impl Document {
|
||||
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
|
||||
/// Returns the ids of the texts in the layers that changed.
|
||||
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
|
||||
self.resolve_inline_art_since(None, layout).changed
|
||||
}
|
||||
|
||||
/// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved,
|
||||
/// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the
|
||||
/// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the
|
||||
/// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then
|
||||
/// still measures the same, the type in the layer trees that are the same nodes as `last`'s
|
||||
/// already has these bounds: only the other layer trees are checked, in the same order, and
|
||||
/// the document and the ids returned are those of the full pass. Otherwise, or without `last`,
|
||||
/// the full pass runs.
|
||||
pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass {
|
||||
if let Some((last, kept)) = last
|
||||
&& self.same_inline_inputs(last, kept)
|
||||
{
|
||||
let measured = Measured(RefCell::new(kept.0.clone()));
|
||||
let mut changed = vec![];
|
||||
let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed);
|
||||
for (i, layer) in layers {
|
||||
self.layers[i] = layer;
|
||||
}
|
||||
return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true };
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut unused = vec![];
|
||||
let graph = InlineGraph::of(self);
|
||||
@@ -147,10 +170,44 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false }
|
||||
}
|
||||
|
||||
/// Whether the type in this document's layer trees that are the same nodes as `last`'s already
|
||||
/// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]).
|
||||
fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool {
|
||||
self.symbols.len() == last.symbols.len()
|
||||
&& self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& self.graph_designs.len() == last.graph_designs.len()
|
||||
&& self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& self.patterns.len() == last.patterns.len()
|
||||
&& self
|
||||
.patterns
|
||||
.iter()
|
||||
.zip(&last.patterns)
|
||||
.all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y)))
|
||||
&& crate::Shared::ptr_eq(&self.unknown, &last.unknown)
|
||||
&& kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass of [`Document::resolve_inline_art_since`] did.
|
||||
#[derive(Debug)]
|
||||
pub struct InlinePass {
|
||||
/// The ids of the texts in the layers that changed, in the order the full pass finds them.
|
||||
pub changed: Vec<NodeId>,
|
||||
/// The bounds the pass gave the inline graphics of each symbol name, for the next pass.
|
||||
pub measured: InlineMeasured,
|
||||
/// Whether only the layer trees that differ from the last resolved document's were checked.
|
||||
pub partial: bool,
|
||||
}
|
||||
|
||||
/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each
|
||||
/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the
|
||||
/// pass before it measured, so the names of all the type in the document stay listed.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct InlineMeasured(HashMap<String, Option<Rect>>);
|
||||
|
||||
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
|
||||
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
|
||||
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
|
||||
@@ -185,6 +242,22 @@ fn resolve_tree(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> bool {
|
||||
resolve_since(None, n, bounds, layout, changed)
|
||||
}
|
||||
|
||||
/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was
|
||||
/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same
|
||||
/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node
|
||||
/// of the tree is visited.
|
||||
fn resolve_since(
|
||||
old: Option<&Node>,
|
||||
n: &mut Arc<Node>,
|
||||
bounds: &dyn Fn(&str) -> Option<Rect>,
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> bool {
|
||||
#[cfg(test)]
|
||||
tests::VISITS.with(|v| v.set(v.get() + 1));
|
||||
let mut copied = false;
|
||||
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
|
||||
let node = Arc::make_mut(n);
|
||||
@@ -196,17 +269,17 @@ fn resolve_tree(
|
||||
}
|
||||
copied = true;
|
||||
}
|
||||
let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art);
|
||||
let mask = n.extras().mask.as_deref().and_then(|m| {
|
||||
let mut art = m.art.clone();
|
||||
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
|
||||
});
|
||||
let mut kids = vec![];
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let mut c = c.clone();
|
||||
if resolve_tree(&mut c, bounds, layout, changed) {
|
||||
kids.push((i, c));
|
||||
if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut art = m.art.clone();
|
||||
let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o);
|
||||
resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art)
|
||||
});
|
||||
let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice));
|
||||
let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed);
|
||||
if mask.is_none() && kids.is_empty() {
|
||||
return copied;
|
||||
}
|
||||
@@ -224,6 +297,35 @@ fn resolve_tree(
|
||||
true
|
||||
}
|
||||
|
||||
/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list
|
||||
/// before an edit) that has its id, found at the same position or else by id, and skips those that
|
||||
/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new
|
||||
/// node of each tree that changed.
|
||||
fn resolve_kids(
|
||||
old: Option<&[Arc<Node>]>,
|
||||
kids: &[Arc<Node>],
|
||||
bounds: &dyn Fn(&str) -> Option<Rect>,
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
|
||||
/// A symbol is first asked for after its own type is resolved (the pass goes in
|
||||
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
|
||||
@@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
/// How many nodes [`resolve_since`] has visited on this thread.
|
||||
pub(super) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes visited since the last call.
|
||||
fn visits() -> usize {
|
||||
VISITS.with(|v| v.replace(0))
|
||||
}
|
||||
|
||||
/// A copy of `d` resolved by the full pass, and the ids that pass returns.
|
||||
fn fully_resolved(d: &Document) -> (Document, Vec<NodeId>) {
|
||||
let mut full = d.clone();
|
||||
let ids = full.resolve_inline_art_with(&mut |_| {});
|
||||
(full, ids)
|
||||
}
|
||||
|
||||
/// The children of the layer at `i`, for an edit.
|
||||
fn layer_kids(d: &mut Document, i: usize) -> &mut Vec<Arc<Node>> {
|
||||
match Arc::make_mut(&mut d.layers[i]).children_mut() {
|
||||
Some(kids) => kids,
|
||||
None => panic!("layer {i} is a group"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing
|
||||
/// `S` in the opacity mask of the second.
|
||||
fn many_groups() -> Document {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
symbol(&mut d, "S", vec![square]);
|
||||
for _ in 0..50 {
|
||||
let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect();
|
||||
let group = Node::group(d.alloc_id(), kids);
|
||||
d.layers.push(Arc::new(group));
|
||||
}
|
||||
let t = showing(&mut d, "S");
|
||||
layer_kids(&mut d, 0).push(t);
|
||||
let masked = showing(&mut d, "S");
|
||||
Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true)));
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() {
|
||||
let mut d = many_groups();
|
||||
let first = d.resolve_inline_art_since(None, &mut |_| {});
|
||||
assert!(!first.partial);
|
||||
assert_eq!(first.changed.len(), 2);
|
||||
let last = d.clone();
|
||||
visits();
|
||||
let _ = fully_resolved(&d);
|
||||
let full_visits = visits();
|
||||
// The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the
|
||||
// second group's opacity mask new type: its 20 squares stay the same nodes.
|
||||
let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0));
|
||||
layer_kids(&mut d, 30)[5] = moved;
|
||||
let added = showing(&mut d, "S");
|
||||
layer_kids(&mut d, 40).push(added.clone());
|
||||
let mask_type = showing(&mut d, "S");
|
||||
if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
m.art = mask_type.clone();
|
||||
}
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids, [mask_type.id, added.id]);
|
||||
visits();
|
||||
let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {});
|
||||
let partial_visits = visits();
|
||||
assert!(pass.partial);
|
||||
assert_eq!(pass.changed, ids);
|
||||
assert_eq!(d, want);
|
||||
// The three changed groups, the mask's new type, the moved square and the added type.
|
||||
assert_eq!(partial_visits, 6);
|
||||
assert!(full_visits > 1000, "{full_visits}");
|
||||
assert_eq!(pass.measured, first.measured);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_symbols_or_symbol_sizes_take_the_full_pass() {
|
||||
let mut d = many_groups();
|
||||
let mut pass = d.resolve_inline_art_since(None, &mut |_| {});
|
||||
// A natural size for S, its art unchanged.
|
||||
let last = d.clone();
|
||||
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] }));
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids.len(), 2);
|
||||
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert_eq!((&d, &pass.changed), (&want, &ids));
|
||||
// New art for S.
|
||||
let last = d.clone();
|
||||
let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0));
|
||||
d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger]));
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids.len(), 2);
|
||||
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert_eq!((&d, &pass.changed), (&want, &ids));
|
||||
// A measurement that no longer holds, with the same symbols and foreign data.
|
||||
let last = d.clone();
|
||||
let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))]));
|
||||
pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert!(pass.changed.is_empty());
|
||||
}
|
||||
|
||||
/// The position of each node in `order`.
|
||||
fn positions(order: &[usize]) -> Vec<usize> {
|
||||
let mut at = vec![0; order.len()];
|
||||
|
||||
@@ -31,7 +31,7 @@ mod symbol_nine_slice;
|
||||
pub mod symbol_overrides;
|
||||
mod symbol_pixel_aligned;
|
||||
mod symbol_registration;
|
||||
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use shared::Shared;
|
||||
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
|
||||
pub use symbol_nine_slice::{
|
||||
@@ -168,7 +168,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
|
||||
@@ -66,7 +66,8 @@ pub use expand::{
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net,
|
||||
warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position.
|
||||
pub fn map_handles_within(
|
||||
path: &PathData,
|
||||
max_piece: f64,
|
||||
max: usize,
|
||||
f: impl Fn(Point) -> Point,
|
||||
handle: impl Fn(Point, Point) -> Point,
|
||||
) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, handle)
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
@@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
// Evaluating an unchanged curve can overflow even when its control points are finite.
|
||||
let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) };
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
@@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod handle_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unsplit_curve_keeps_its_finite_control_points() {
|
||||
let start = Point::new(1e308, 0.0);
|
||||
let end = Point::new(1.03e308, 0.0);
|
||||
let path = PathData::new(vec![SubPath::new(
|
||||
vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)],
|
||||
false,
|
||||
)]);
|
||||
assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounded_samples_preserve_a_smooth_interior_join() {
|
||||
let center = Point::new(1e16, 0.0);
|
||||
let path = PathData::new(vec![SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)),
|
||||
Anchor::with_handles(
|
||||
center,
|
||||
center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0),
|
||||
center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0),
|
||||
),
|
||||
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
)]);
|
||||
let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1));
|
||||
let join = &mapped.subpaths[0].anchors[1];
|
||||
let incoming = join.p - join.h_in;
|
||||
let outgoing = join.h_out - join.p;
|
||||
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
|
||||
assert!(incoming.dot(outgoing) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() {
|
||||
for x in [1e16, 1e16 + 2.0, -1e16] {
|
||||
for offset in [-6.0, -2.0, 2.0, 6.0] {
|
||||
let p = Point::new(x, 0.0);
|
||||
let h = Point::new(x + offset, 0.0);
|
||||
assert_eq!(mapped_handle(&|point| point, p, h), h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,6 +179,48 @@ impl LiveShape {
|
||||
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
|
||||
}
|
||||
}
|
||||
/// A line's length in the document, from its first end to its second. None for other shapes.
|
||||
pub fn line_length(&self) -> Option<f64> {
|
||||
let LiveShape::Line { a, b } = self else { return None };
|
||||
Some((*b - *a).hypot())
|
||||
}
|
||||
/// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the
|
||||
/// direction from its first end to its second (the Rotate field's sense). 0 for a line whose
|
||||
/// ends meet. None for other shapes.
|
||||
pub fn line_angle(&self) -> Option<f64> {
|
||||
let LiveShape::Line { a, b } = self else { return None };
|
||||
if a == b {
|
||||
return Some(0.0);
|
||||
}
|
||||
// No −0° or 360° from rounding: a line drawn left to right reads 0°.
|
||||
let a = (-self.angle_deg()).rem_euclid(360.0);
|
||||
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
|
||||
}
|
||||
/// Make a line `len` long (0 or more), keeping its first end in place and its direction, or
|
||||
/// pointing it to the right when its ends meet.
|
||||
pub fn set_line_length(&mut self, len: f64) {
|
||||
let LiveShape::Line { a, b } = self else { return };
|
||||
if !len.is_finite() || len < 0.0 {
|
||||
return;
|
||||
}
|
||||
let now = (*b - *a).hypot();
|
||||
*b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) };
|
||||
}
|
||||
/// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line
|
||||
/// whose ends meet stays as it is.
|
||||
pub fn set_line_angle(&mut self, angle: f64) {
|
||||
let LiveShape::Line { a, b } = self else { return };
|
||||
let half = (*b - *a).hypot() / 2.0;
|
||||
if !angle.is_finite() || half <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mid = a.midpoint(*b);
|
||||
let t = angle.to_radians();
|
||||
// The page's y axis points down, so a counterclockwise angle goes up the page.
|
||||
let (dx, dy) = (half * t.cos(), -half * t.sin());
|
||||
*a = Point::new(mid.x - dx, mid.y - dy);
|
||||
*b = Point::new(mid.x + dx, mid.y + dy);
|
||||
}
|
||||
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
|
||||
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
|
||||
pub fn make_sides_equal(&mut self) {
|
||||
|
||||
@@ -187,8 +187,9 @@ impl Document {
|
||||
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
|
||||
/// visited once even when an id is inside another).
|
||||
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
|
||||
let listed: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let roots: Vec<NodeId> =
|
||||
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
|
||||
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
|
||||
let mut n = 0;
|
||||
let mut g = relink(f);
|
||||
for id in roots {
|
||||
@@ -844,6 +845,77 @@ mod tests {
|
||||
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
|
||||
}
|
||||
|
||||
/// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
|
||||
fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
|
||||
let roots: Vec<NodeId> =
|
||||
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
|
||||
let mut n = 0;
|
||||
let mut g = relink(f);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(id) else { continue };
|
||||
if let Some((new, count)) = map_node(node, &mut g)
|
||||
&& let Some(slot) = d.node_mut(id)
|
||||
{
|
||||
*slot = new;
|
||||
n += count;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_within_ids_matches_a_search_of_the_ids() {
|
||||
// Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
|
||||
// rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let first = d.layers[0].id;
|
||||
let second = d.alloc_id();
|
||||
d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
|
||||
let rect = |d: &mut Document, i: u8| {
|
||||
let id = d.alloc_id();
|
||||
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
|
||||
(id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
|
||||
};
|
||||
let (r1, n1) = rect(&mut d, 1);
|
||||
let (r2, n2) = rect(&mut d, 2);
|
||||
let (r3, n3) = rect(&mut d, 3);
|
||||
let (r4, n4) = rect(&mut d, 4);
|
||||
let (r5, n5) = rect(&mut d, 5);
|
||||
let (inner, outer) = (d.alloc_id(), d.alloc_id());
|
||||
let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
|
||||
d.insert(Some(first), usize::MAX, outer_node).unwrap();
|
||||
d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
|
||||
d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
|
||||
let missing = NodeId(u64::MAX);
|
||||
let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
|
||||
// Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
|
||||
let mut lists: Vec<Vec<NodeId>> = vec![vec![]];
|
||||
let mut shorter: Vec<Vec<NodeId>> = vec![vec![]];
|
||||
for _ in 0..3 {
|
||||
shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
|
||||
lists.extend(shorter.iter().cloned());
|
||||
}
|
||||
assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
|
||||
for ids in &lists {
|
||||
// A callback that changes every paint it visits, so a paint visited twice counts twice.
|
||||
let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
|
||||
let mut d = d.clone();
|
||||
let mut visits = vec![];
|
||||
let n = map(&mut d, ids, &mut |c, s, t| {
|
||||
visits.push((*c, s.clone(), *t));
|
||||
*s = Some(format!("{}", visits.len()));
|
||||
*t *= 0.5;
|
||||
true
|
||||
});
|
||||
(n, visits, d.layers)
|
||||
};
|
||||
let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
|
||||
let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
|
||||
assert_eq!(by_set, by_search, "{ids:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
|
||||
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
|
||||
n.walk(&mut |m| {
|
||||
|
||||
@@ -32,8 +32,8 @@ pub use para_style::{
|
||||
pub use runs::PATH_LEAD_MAX;
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
|
||||
pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
TabStop,
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
|
||||
|
||||
|
||||
@@ -304,17 +304,40 @@ impl TextObject {
|
||||
/// Update the paragraph styles for replacing bytes `start..end` of the current plain text by
|
||||
/// `insert` (call before changing the runs). The paragraph the range starts in keeps its
|
||||
/// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that
|
||||
/// style too (Return continues the paragraph it splits); later paragraphs keep theirs.
|
||||
/// style too (Return continues the paragraph it splits), without the number its list gives it
|
||||
/// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new
|
||||
/// paragraphs is made at the start of a paragraph and some of that paragraph's text stays
|
||||
/// after it, that number moves with the text to the last paragraph the insertion starts.
|
||||
pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) {
|
||||
if self.paras.is_empty() {
|
||||
let added = insert.bytes().filter(|&b| b == b'\n').count();
|
||||
let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some());
|
||||
// With one style for every paragraph, the new paragraphs take it as it is unless its list
|
||||
// gives the paragraph a number.
|
||||
if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) {
|
||||
return;
|
||||
}
|
||||
let r = self.paragraphs_in(start, end);
|
||||
let v = self.paragraph_styles();
|
||||
let Some(keep) = v.get(r.start).cloned() else { return };
|
||||
let added = insert.bytes().filter(|&b| b == b'\n').count();
|
||||
let Some(mut keep) = v.get(r.start).cloned() else { return };
|
||||
let given = keep.list.and_then(|l| l.start);
|
||||
if let Some(l) = keep.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
let mut out: Vec<ParaStyle> = v.iter().take(r.start + 1).cloned().collect();
|
||||
out.extend(std::iter::repeat_n(keep, added));
|
||||
let text = self.plain_text();
|
||||
let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len()));
|
||||
let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n'));
|
||||
// The paragraph's text after the replaced bytes, which the last new paragraph then holds.
|
||||
let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n');
|
||||
if given.is_some() && added > 0 && at_para_start && text_kept {
|
||||
if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) {
|
||||
l.start = None;
|
||||
}
|
||||
if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) {
|
||||
l.start = given;
|
||||
}
|
||||
}
|
||||
out.extend(v.iter().skip(r.end).cloned());
|
||||
self.paras = out;
|
||||
if let Some(first) = self.paras.first() {
|
||||
|
||||
@@ -631,6 +631,8 @@ pub enum FirstBaseline {
|
||||
XHeight,
|
||||
/// The first line's leading.
|
||||
Leading,
|
||||
/// The top of the first line's ideographic em box touches the frame top.
|
||||
EmBoxHeight,
|
||||
/// Exactly `first_baseline_min` below the top.
|
||||
Fixed,
|
||||
}
|
||||
@@ -206,15 +206,41 @@ pub struct ParaList {
|
||||
/// ([`Self::depth`]). The file saves it only when it is not 1.
|
||||
#[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")]
|
||||
pub level: u8,
|
||||
/// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs
|
||||
/// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the
|
||||
/// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made
|
||||
/// with Return in a paragraph that has one does not take it, and a paragraph style does not
|
||||
/// keep it. A saved number outside the range is read as the nearest one. The file saves it
|
||||
/// only when it is set.
|
||||
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")]
|
||||
pub start: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for ParaList {
|
||||
/// A bulleted list with a dot, its marker aligned left, at level 1.
|
||||
/// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the
|
||||
/// paragraph before.
|
||||
fn default() -> Self {
|
||||
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 }
|
||||
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest number a numbered paragraph can be given ([`ParaList::start`]).
|
||||
pub const MAX_LIST_START: u32 = 999_999_999;
|
||||
|
||||
/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`],
|
||||
/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else
|
||||
/// is an error.
|
||||
fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
|
||||
let start = match serde_json::Value::deserialize(d)? {
|
||||
serde_json::Value::Null => return Ok(None),
|
||||
serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
|
||||
n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START)))
|
||||
}
|
||||
_ => return Err(serde::de::Error::custom("a list start must be a whole number")),
|
||||
};
|
||||
Ok(u32::try_from(start).ok())
|
||||
}
|
||||
|
||||
/// Is `level` the first list level, which the file does not save?
|
||||
fn is_first_level(level: &u8) -> bool {
|
||||
*level == 1
|
||||
@@ -307,6 +333,12 @@ impl ParaList {
|
||||
Self { level, ..self }
|
||||
}
|
||||
|
||||
/// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the
|
||||
/// paragraph before).
|
||||
pub fn starting_at(self, start: Option<u32>) -> Self {
|
||||
Self { start, ..self }
|
||||
}
|
||||
|
||||
/// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken
|
||||
/// as the nearest level.
|
||||
pub fn depth(&self) -> usize {
|
||||
@@ -334,8 +366,9 @@ impl ParaList {
|
||||
/// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts
|
||||
/// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1
|
||||
/// again; a bulleted one has its bullet and leaves the count of its level as it is, and a
|
||||
/// numbered one adds one to the count of its level and is numbered with it. A paragraph back
|
||||
/// at a shallower level then goes on with that level's count.
|
||||
/// numbered one adds one to the count of its level and is numbered with it, or with the number
|
||||
/// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a
|
||||
/// shallower level then goes on with that level's count.
|
||||
pub fn next_marker(list: Option<ParaList>, empty: bool, counts: &mut ListCounts) -> Option<String> {
|
||||
let Some(list) = list else {
|
||||
*counts = ListCounts::default();
|
||||
@@ -350,7 +383,7 @@ impl ParaList {
|
||||
}
|
||||
let count = &mut counts.0[level];
|
||||
if list.number.is_some() {
|
||||
*count = count.saturating_add(1);
|
||||
*count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START));
|
||||
}
|
||||
Some(list.marker(*count))
|
||||
}
|
||||
|
||||
@@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() {
|
||||
assert_eq!(opened.list_level_counts, (1..=8).collect::<Vec<u32>>(), "a file keeps only the counts of levels 2 to 9");
|
||||
}
|
||||
|
||||
/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level
|
||||
/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does
|
||||
/// not use the number, and a paragraph in no list still starts the count again. The file saves the
|
||||
/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one.
|
||||
#[test]
|
||||
fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() {
|
||||
let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start));
|
||||
let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7)));
|
||||
let mut counts = ListCounts::default();
|
||||
let markers: Vec<Option<String>> = [
|
||||
(num(1, None), false),
|
||||
(num(1, Some(5)), false),
|
||||
(num(1, None), false),
|
||||
(num(2, None), false),
|
||||
(num(2, Some(1)), false),
|
||||
(num(2, None), false),
|
||||
(num(1, None), false),
|
||||
(num(1, Some(9)), true),
|
||||
(num(1, None), false),
|
||||
(dot, false),
|
||||
(num(1, Some(1)), false),
|
||||
(None, false),
|
||||
(num(1, None), false),
|
||||
]
|
||||
.iter()
|
||||
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts))
|
||||
.collect();
|
||||
let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."];
|
||||
assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::<Vec<_>>(), want);
|
||||
let mut counts = ListCounts::default();
|
||||
let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START)));
|
||||
assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999."));
|
||||
let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0)));
|
||||
assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1");
|
||||
assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"}));
|
||||
assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5}));
|
||||
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap().start;
|
||||
assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5));
|
||||
assert_eq!(read(serde_json::json!({"number": "arabic"})), None);
|
||||
assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None);
|
||||
let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)];
|
||||
assert_eq!(
|
||||
starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))),
|
||||
[Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)],
|
||||
"a saved number outside 1 to 999999999 reads as the nearest one"
|
||||
);
|
||||
for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] {
|
||||
assert!(serde_json::from_value::<ParaList>(serde_json::json!({ "start": bad })).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Return in a paragraph that its list gives a number makes paragraphs without it, also while
|
||||
/// every paragraph shares one style; Return at the start of its text moves the number with the
|
||||
/// text, and Return elsewhere leaves it where it was.
|
||||
#[test]
|
||||
fn return_does_not_copy_a_paragraphs_number() {
|
||||
let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() };
|
||||
let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
|
||||
// One style for the whole text: Return after "one" splits it.
|
||||
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
|
||||
t.set_all_paras(five);
|
||||
t.splice_paras(3, 3, "\n");
|
||||
t.runs[0].text.insert(3, '\n');
|
||||
t.normalize_paras();
|
||||
assert_eq!(starts(&t), [Some(5), None]);
|
||||
assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list");
|
||||
// Return at the start of "two" (a paragraph with a number of its own): the number moves on
|
||||
// with the text, and the empty paragraph left before it has none.
|
||||
t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8))));
|
||||
t.splice_paras(4, 4, "\n\n");
|
||||
t.runs[0].text.insert_str(4, "\n\n");
|
||||
t.normalize_paras();
|
||||
assert_eq!(t.plain_text(), "one\n\n\ntwo");
|
||||
assert_eq!(starts(&t), [Some(5), None, None, Some(8)]);
|
||||
// A whole paragraph pasted at the start of "two": the number stays with "two".
|
||||
t.splice_paras(6, 6, "Pasted\n");
|
||||
t.runs[0].text.insert_str(6, "Pasted\n");
|
||||
t.normalize_paras();
|
||||
assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo");
|
||||
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]);
|
||||
// "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it.
|
||||
t.splice_paras(13, 16, "A\nB");
|
||||
t.runs[0].text.replace_range(13..16, "A\nB");
|
||||
t.normalize_paras();
|
||||
assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB");
|
||||
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]);
|
||||
// Text without a number keeps one style for every paragraph.
|
||||
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
|
||||
t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() });
|
||||
t.splice_paras(3, 3, "\n");
|
||||
assert!(t.paras.is_empty());
|
||||
}
|
||||
|
||||
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
|
||||
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
|
||||
/// The paragraphs after it still start lists.
|
||||
@@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() {
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from
|
||||
/// before it read their own first baseline as they did, Ascent when they have none.
|
||||
#[test]
|
||||
fn em_box_height_first_baseline_is_saved_and_read_back() {
|
||||
let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() };
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0)));
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set);
|
||||
let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0});
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading);
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent);
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err());
|
||||
}
|
||||
|
||||
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
|
||||
fn area_type() -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
|
||||
|
||||
@@ -316,6 +316,37 @@ fn percent(s: &str) -> Option<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm`
|
||||
/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed
|
||||
/// after the value the field shows) is 100 mm (#5684). A number written with both separators has
|
||||
/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a
|
||||
/// number that reads as thousands ([`thousands`]).
|
||||
pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
|
||||
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
|
||||
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
|
||||
/// instead (`0,125` and `1,25` are decimals).
|
||||
fn thousands(text: &str) -> bool {
|
||||
let number = text.trim();
|
||||
let number = number.strip_prefix(['+', '-']).unwrap_or(number);
|
||||
let Some((whole, rest)) = number.split_once(',') else { return false };
|
||||
let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()));
|
||||
(1..=3).contains(&whole.len())
|
||||
&& whole.bytes().all(|b| b.is_ascii_digit())
|
||||
&& !whole.starts_with('0')
|
||||
&& part.len() == 3
|
||||
&& unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'')
|
||||
}
|
||||
|
||||
/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length
|
||||
/// near the largest number in points is too large in Q and Ha.
|
||||
pub fn finite_in_every_unit(pt: f64) -> bool {
|
||||
pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite())
|
||||
}
|
||||
|
||||
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
|
||||
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
|
||||
pub fn parse_number(s: &str) -> Option<f64> {
|
||||
|
||||
@@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
|
||||
use crate::distort::{transform_move, transform_offsets};
|
||||
use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{
|
||||
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
|
||||
as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text,
|
||||
paint_type_clip, reshape_leaves,
|
||||
};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
@@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (bp, rule) = crate::clip_outline(first)?;
|
||||
let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
|
||||
if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
|
||||
(*r, *clipping) = (rule, true);
|
||||
}
|
||||
clip.name = first.name.clone();
|
||||
clip.visible = first.visible;
|
||||
let clip = clip_region_path(first)?;
|
||||
let paint = first.clip_paint();
|
||||
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
|
||||
// then given ids of their own.
|
||||
@@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
return Some(m);
|
||||
};
|
||||
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
|
||||
let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
|
||||
let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
|
||||
knockout_inside(&mut m, &mut inner);
|
||||
match &mut m.kind {
|
||||
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
|
||||
*children = vec![Arc::new(inner), stroke];
|
||||
|
||||
@@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
|
||||
let mut shadowed = type_node(55);
|
||||
shadowed.opacity = 0.5;
|
||||
shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({})));
|
||||
// Type that clips a group is outlined as the plain outlines it clips by.
|
||||
// Type that clips a group is outlined as a plain path of the region it clips by.
|
||||
let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
|
||||
let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true });
|
||||
g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]);
|
||||
@@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
|
||||
let b = o.geometric_bounds().unwrap();
|
||||
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
|
||||
let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap();
|
||||
assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}");
|
||||
assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}");
|
||||
// The region is copied with the type.
|
||||
let b = clipped.geometric_bounds().unwrap();
|
||||
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}",
|
||||
json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}),
|
||||
),
|
||||
g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})),
|
||||
g(
|
||||
"distort.twist",
|
||||
"Twist…",
|
||||
DT,
|
||||
"{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.",
|
||||
json!({"angle": 10.0}),
|
||||
),
|
||||
g(
|
||||
"distort.zigZag",
|
||||
"Zig Zag…",
|
||||
|
||||
@@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat
|
||||
use vectorcraft_pathops::addons::pathtools::insert_at;
|
||||
|
||||
use crate::util::{
|
||||
catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
|
||||
catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
|
||||
};
|
||||
|
||||
fn diag(b: Rect) -> f64 {
|
||||
@@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
|
||||
/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
|
||||
/// the rotation's directional derivative, including each side of the outer circle.
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
|
||||
if ang == 0.0 {
|
||||
@@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
}
|
||||
let c = b.center();
|
||||
let r = diag(b) / 2.0;
|
||||
let half = Vec2::new(b.width() * 0.5, b.height() * 0.5);
|
||||
let boundary = move |p: Point, length: f64| {
|
||||
if length == r {
|
||||
return true;
|
||||
}
|
||||
if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r {
|
||||
return false;
|
||||
}
|
||||
// A bounds-relative distance identifies boundary points affected by center rounding.
|
||||
(Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r
|
||||
};
|
||||
let f = move |q: Point| {
|
||||
let d = q - c;
|
||||
let t = (1.0 - d.hypot() / r).max(0.0);
|
||||
let length = d.hypot();
|
||||
let t = (1.0 - length / r).max(0.0);
|
||||
// y runs down, so a positive turn is clockwise on the page.
|
||||
let a = ang * t;
|
||||
if a == 0.0 {
|
||||
return q;
|
||||
}
|
||||
let (s, co) = a.sin_cos();
|
||||
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
|
||||
};
|
||||
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
|
||||
map_smooth_within(path, piece, max, f)
|
||||
map_handles_within(path, piece, max, f, |p, h| {
|
||||
let v = h - p;
|
||||
if !v.hypot().is_finite() {
|
||||
return f(p);
|
||||
}
|
||||
let d = p - c;
|
||||
let length = d.hypot();
|
||||
let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 };
|
||||
// The clamped rotation has different inward and outward derivatives at the circle.
|
||||
let inside = if boundary(p, length) { radial < 0.0 } else { length < r };
|
||||
let gradient = if inside { -ang / r * radial } else { 0.0 };
|
||||
let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient };
|
||||
let a = ang * (1.0 - length / r).max(0.0);
|
||||
let (s, co) = a.sin_cos();
|
||||
f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co)
|
||||
})
|
||||
}
|
||||
|
||||
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
|
||||
|
||||
@@ -703,6 +703,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
|
||||
}
|
||||
}
|
||||
fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
|
||||
// A clip group whose clipping type's strokes paint around it is outlined as that clip
|
||||
// group: the strokes outside the clip add nothing.
|
||||
if let Some(inner) = crate::reshape::painted_clip_inner(n) {
|
||||
return members(doc, inner, out);
|
||||
}
|
||||
// A clip group shows its members only inside its clipping path: its outline is that
|
||||
// region, not the clipped members' own shapes, which may reach far outside it (#7289).
|
||||
if n.clips() {
|
||||
@@ -884,14 +889,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
if paint {
|
||||
let shapes = member_shapes(doc, &m);
|
||||
let bounds = m.geometric_bounds();
|
||||
// A clip group whose clipping type paints strokes is now a group of a clip group and those
|
||||
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
|
||||
// that clip group. Such groups among the members are measured as their clip groups.
|
||||
let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some();
|
||||
let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m));
|
||||
let art =
|
||||
|items: &[AppearanceItem]| -> Vec<Arc<Node>> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() };
|
||||
let (below, above) = m.appearance.split_contents();
|
||||
let (below, above) = (art(below), art(above));
|
||||
let at = usize::from(m.clips());
|
||||
if let Some(ch) = m.children_mut() {
|
||||
let at = usize::from(wrapped || m.clips());
|
||||
let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) };
|
||||
if let Some(ch) = target.and_then(Node::children_mut) {
|
||||
let at = at.min(ch.len());
|
||||
ch.splice(at..at, below);
|
||||
ch.extend(above);
|
||||
|
||||
+103
-22
@@ -954,6 +954,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option<Node> {
|
||||
Some(Node { visible: t.visible, ..o })
|
||||
}
|
||||
|
||||
/// Clipping path `clip` of a clip group as a clipping path of the region it clips to
|
||||
/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry
|
||||
/// effects of its fills and strokes reshape what they paint and leave that region as it is.
|
||||
/// `None` when it has nothing to clip by.
|
||||
pub(crate) fn clip_region_path(clip: &Node) -> Option<Node> {
|
||||
let (bp, rule) = crate::clip_outline(clip)?;
|
||||
let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default());
|
||||
if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind {
|
||||
(*r, *clipping) = (rule, true);
|
||||
}
|
||||
p.name = clip.name.clone();
|
||||
p.visible = clip.visible;
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its
|
||||
/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks
|
||||
/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A
|
||||
/// neutral `m` stays neutral, so both take the setting of the groups around them.
|
||||
pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) {
|
||||
inner.knockout = m.knockout;
|
||||
if m.knockout != vectorcraft_doc::Knockout::Neutral {
|
||||
m.knockout = vectorcraft_doc::Knockout::Off;
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip
|
||||
/// group and its clipping type's strokes: a group that does not clip whose first member is a clip
|
||||
/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The
|
||||
/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes
|
||||
/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds
|
||||
/// ([`clip_bounds`]).
|
||||
pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> {
|
||||
if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
|
||||
return None;
|
||||
}
|
||||
let [inner, stroke, ..] = n.children()?.as_slice() else { return None };
|
||||
let clip = inner.children()?.first()?;
|
||||
(inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner)
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that
|
||||
/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type
|
||||
/// outside the clip do not widen them.
|
||||
pub(crate) fn clip_bounds(n: &Node) -> Option<Rect> {
|
||||
fn holds(n: &Node) -> bool {
|
||||
painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c))
|
||||
}
|
||||
fn unwrap(n: &mut Node) {
|
||||
if let Some(inner) = painted_clip_inner(n) {
|
||||
let mut inner = inner.clone();
|
||||
inner.visible = n.visible;
|
||||
*n = inner;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if holds(c) {
|
||||
unwrap(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !holds(n) {
|
||||
return n.geometric_bounds();
|
||||
}
|
||||
let mut probe = n.clone();
|
||||
unwrap(&mut probe);
|
||||
probe.geometric_bounds()
|
||||
}
|
||||
|
||||
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
|
||||
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
|
||||
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
|
||||
@@ -981,32 +1049,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
|
||||
}
|
||||
|
||||
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
|
||||
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
|
||||
/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
|
||||
/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
|
||||
/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
|
||||
/// they are. Hidden type paints nothing.
|
||||
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type
|
||||
/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped
|
||||
/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the
|
||||
/// type's art with only those fills or strokes, their own geometry effects applied. With strokes,
|
||||
/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group
|
||||
/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a
|
||||
/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both,
|
||||
/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden
|
||||
/// type paints nothing.
|
||||
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
|
||||
let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
|
||||
if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
|
||||
let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return };
|
||||
if !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
|
||||
return;
|
||||
}
|
||||
let paint = first.clip_paint();
|
||||
if paint.fill.is_none() && paint.stroke.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(clip) = clipping_text_outline(first) else { return };
|
||||
let Some(clip) = clip_region_path(first) else { return };
|
||||
let art = |part: Option<Node>| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
|
||||
let members: Vec<Arc<Node>> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
|
||||
let stroke = art(paint.stroke);
|
||||
let (fill, stroke) = (art(paint.fill), art(paint.stroke));
|
||||
let id = n.id;
|
||||
match (&mut n.kind, stroke) {
|
||||
(NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
|
||||
(NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
|
||||
*children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
|
||||
*clip = false;
|
||||
}
|
||||
_ => {}
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
let Some(slot) = ch.first_mut() else { return };
|
||||
*slot = Arc::new(clip);
|
||||
if let Some(fill) = fill {
|
||||
ch.insert(1, fill);
|
||||
}
|
||||
let Some(stroke) = stroke else { return };
|
||||
let guides = ch.split_off(Node::guide_run_start(ch));
|
||||
let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true });
|
||||
knockout_inside(n, &mut inner);
|
||||
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind {
|
||||
*children = [Arc::new(inner), stroke].into_iter().chain(guides).collect();
|
||||
*clip = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1822,7 +1899,7 @@ impl Step<'_> {
|
||||
if !groups.is_empty() {
|
||||
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
|
||||
}
|
||||
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
|
||||
let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art));
|
||||
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
|
||||
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
|
||||
}
|
||||
@@ -3247,6 +3324,9 @@ fn group_marks(
|
||||
NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false),
|
||||
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
// A clip group whose clipping type's strokes paint around it is measured as that clip
|
||||
// group: the strokes outside the clip do not widen it ([`clip_bounds`]).
|
||||
let clip = *clip || painted_clip_inner(n).is_some();
|
||||
let skip = children.len().saturating_sub(n.editing_children().len());
|
||||
let (mut bounds, mut held) = (None, false);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
@@ -3257,7 +3337,7 @@ fn group_marks(
|
||||
}
|
||||
at.pop();
|
||||
// Only members measured in the bounds hold the group's gradients in place.
|
||||
let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
|
||||
let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) };
|
||||
if counts {
|
||||
bounds = vectorcraft_geom::union_opt(bounds, b);
|
||||
held |= h;
|
||||
@@ -3473,16 +3553,17 @@ impl WarpedImages {
|
||||
|
||||
/// The geometric bounds of `art` as it draws after the effects so far: each image this table
|
||||
/// lists measured by the pieces the warps and moves it took would cut it into, when the art
|
||||
/// has room for them ([`cut_warped_images`]).
|
||||
/// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip
|
||||
/// are left out ([`clip_bounds`]).
|
||||
pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> {
|
||||
if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) {
|
||||
return art.geometric_bounds();
|
||||
return clip_bounds(art);
|
||||
}
|
||||
// The pieces the images would be cut into now: each group of pieces is shown or hidden as
|
||||
// its image is, and hidden objects are left out of a layer's bounds.
|
||||
let mut probe = art.clone();
|
||||
restore_warped_images(&mut probe, self, true);
|
||||
probe.geometric_bounds()
|
||||
clip_bounds(&probe)
|
||||
}
|
||||
|
||||
/// The geometric bounds of image `n`: when this table lists it, measured by the pieces the
|
||||
|
||||
@@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_boundary_handles_follow_the_inward_tangent() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
|
||||
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
|
||||
for angle in [90.0_f64, 400.0, -720.0] {
|
||||
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
|
||||
let anchors = &out.subpaths[0].anchors;
|
||||
let start = anchors.first().unwrap();
|
||||
let end = anchors.last().unwrap();
|
||||
assert_eq!(start.p, Point::new(40.0, 30.0));
|
||||
assert_eq!(end.p, Point::new(60.0, 30.0));
|
||||
for (actual, expected) in [
|
||||
(start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())),
|
||||
(end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())),
|
||||
] {
|
||||
assert!(actual.hypot() > 1e-9);
|
||||
let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs();
|
||||
assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_large_coordinate_joins_preserve_boundary_sides() {
|
||||
use vectorcraft_geom::Anchor;
|
||||
|
||||
let center = 1e16;
|
||||
for offset in [32.0, 64.0] {
|
||||
let p = Point::new(center + offset, 0.0);
|
||||
let line = PathData::single(SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(Point::new(p.x - 18.0, 0.0)),
|
||||
Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)),
|
||||
Anchor::corner(Point::new(p.x + 18.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3);
|
||||
let join = &out.subpaths[0].anchors[1];
|
||||
if offset == 64.0 {
|
||||
assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0));
|
||||
let actual = join.h_in - join.p;
|
||||
let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2);
|
||||
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
|
||||
assert!(error < 1e-9, "{actual:?}");
|
||||
} else {
|
||||
let incoming = join.p - join.h_in;
|
||||
let outgoing = join.h_out - join.p;
|
||||
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
|
||||
assert!(incoming.dot(outgoing) > 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fractional_boundary_handles_use_each_sides_derivative() {
|
||||
use vectorcraft_geom::Anchor;
|
||||
|
||||
for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] {
|
||||
for x in [bounds.x0, bounds.x1] {
|
||||
for angle in [90.0_f64, 400.0, -720.0] {
|
||||
let p = Point::new(x, 30.0);
|
||||
let line = PathData::single(SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(Point::new(x - 3.0 * step, 30.0)),
|
||||
Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)),
|
||||
Anchor::corner(Point::new(x + 3.0 * step, 30.0)),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = crate::distort::twist(&line, bounds, angle, 3);
|
||||
assert!(
|
||||
out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()),
|
||||
"x={x} angle={angle}: {:?}",
|
||||
out.subpaths[0].anchors
|
||||
);
|
||||
let join = &out.subpaths[0].anchors[1];
|
||||
assert!(join.p.distance(p) < 1e-10, "{:?}", join.p);
|
||||
let a = angle.to_radians();
|
||||
let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] };
|
||||
for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) {
|
||||
let expected = vectorcraft_geom::Vec2::new(dx, dy);
|
||||
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
|
||||
assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0);
|
||||
let center = bounds.center();
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false));
|
||||
let out = crate::distort::twist(&line, bounds, 90.0, 3);
|
||||
assert_eq!(out.subpaths[0].anchors[1].p, center);
|
||||
let bounds = Rect::new(0.0, 30.0, 2e16, 30.0);
|
||||
let p = Point::new(bounds.x1 - 8.0, 30.0);
|
||||
let line = PathData::single(SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(Point::new(p.x - 12.0, p.y)),
|
||||
Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)),
|
||||
Anchor::corner(Point::new(p.x + 12.0, p.y)),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = crate::distort::twist(&line, bounds, 90.0, 3);
|
||||
let join = &out.subpaths[0].anchors[1];
|
||||
assert!(join.p.y - p.y > 10.0, "{:?}", join.p);
|
||||
assert!(join.h_out.y - join.p.y < -4.0, "{join:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fixes_the_outer_circle_and_rotates_inside() {
|
||||
let out = run("distort.twist", json!({"angle": 0}), &square());
|
||||
|
||||
@@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() {
|
||||
assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn blue() -> Paint {
|
||||
Paint::solid(Color::rgb(0.0, 0.0, 1.0))
|
||||
}
|
||||
|
||||
fn green() -> Paint {
|
||||
Paint::solid(Color::rgb(0.0, 1.0, 0.0))
|
||||
}
|
||||
|
||||
/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3
|
||||
/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and
|
||||
/// stroked green 2 pt wide when `stroke`.
|
||||
fn painted_type(id: u64, fill: bool, stroke: bool) -> Node {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
|
||||
static FONT: std::sync::Once = std::sync::Once::new();
|
||||
FONT.call_once(|| {
|
||||
vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds"));
|
||||
});
|
||||
let style = CharStyle {
|
||||
font_family: HEIGHT_FAMILY.into(),
|
||||
size: 40.0,
|
||||
fill: if fill { blue() } else { Paint::None },
|
||||
stroke: if stroke { green() } else { Paint::None },
|
||||
stroke_width: 2.0,
|
||||
..Default::default()
|
||||
};
|
||||
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style))))
|
||||
}
|
||||
|
||||
/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke?
|
||||
fn paints(n: &Node, fill: bool) -> bool {
|
||||
use vectorcraft_doc::AppearanceItem;
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.paint == blue(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0,
|
||||
});
|
||||
own || n.children().into_iter().flatten().any(|c| paints(c, fill))
|
||||
}
|
||||
|
||||
/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of
|
||||
/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the
|
||||
/// green stroke art right after the clip group (over it, outside the clip), and whether a green
|
||||
/// stroke paints inside the clip group.
|
||||
type Painted = (Rect, Option<Rect>, Option<Rect>, bool);
|
||||
|
||||
fn painted_clip(n: &Node) -> Option<Painted> {
|
||||
let ch = n.children()?;
|
||||
for (i, c) in ch.iter().enumerate() {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind {
|
||||
let region = clip_outline(children.first()?)?.0.bounding_box();
|
||||
let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds());
|
||||
let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds());
|
||||
let inside = children.iter().skip(1).any(|m| paints(m, false));
|
||||
return Some((region, fill, stroke, inside));
|
||||
}
|
||||
if let Some(found) = painted_clip(c) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn near_rect(a: Rect, b: Rect) -> bool {
|
||||
(a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_clipping_type_survives_enclosing_geometry_effect() {
|
||||
// Type that paints a fill, a stroke, both or neither clips a red square, in a group whose
|
||||
// Transform (moving everything 10 pt down, beside other type that stays type in the export) or
|
||||
// Offset Path reshapes its members: the canvas and the export keep the type's fill as art
|
||||
// behind the square inside the clip and its stroke as art over the clip group, both reshaped
|
||||
// with the clip.
|
||||
let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box();
|
||||
assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}");
|
||||
let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))];
|
||||
for effect in effects {
|
||||
for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] {
|
||||
let clipped = clip_group(2, painted_type(3, fill, stroke));
|
||||
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]);
|
||||
outer.appearance.effects.push(effect.clone());
|
||||
let canvas = crate::evaluate_container(None, &outer).unwrap();
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let exported = baked.layers.iter().find_map(|l| painted_clip(l));
|
||||
for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] {
|
||||
let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id);
|
||||
let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group"));
|
||||
if effect.id == "distort.transform" {
|
||||
assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}");
|
||||
} else {
|
||||
let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0);
|
||||
assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt");
|
||||
}
|
||||
assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}");
|
||||
assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}");
|
||||
assert!(!inside, "{case}: the stroke paints outside the clip");
|
||||
for art in fills.into_iter().chain(strokes) {
|
||||
assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The group in `n` that holds a clip group and then the green stroke art of its clipping type,
|
||||
/// with that clip group.
|
||||
fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> {
|
||||
let ch = n.children()?;
|
||||
if let [inner, stroke, ..] = ch.as_slice()
|
||||
&& matches!(inner.kind, NodeKind::Group { clip: true, .. })
|
||||
&& !n.clips()
|
||||
&& paints(stroke, false)
|
||||
{
|
||||
return Some((n, inner));
|
||||
}
|
||||
ch.iter().find_map(|c| stroke_wrapper(c))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipping_type_strokes_paint_over_a_knockout_clip_group() {
|
||||
// A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its
|
||||
// clipped art knocks out as the clip group says, and the type's stroke paints over it without
|
||||
// knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's
|
||||
// Transform around it, or by its own Offset Path.
|
||||
use vectorcraft_doc::Knockout;
|
||||
for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] {
|
||||
for own in [false, true] {
|
||||
let mut ty = painted_type(3, true, true);
|
||||
if own {
|
||||
ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1})));
|
||||
}
|
||||
let mut clipped = clip_group(2, ty);
|
||||
clipped.knockout = knockout;
|
||||
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]);
|
||||
if !own {
|
||||
outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10})));
|
||||
}
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer.clone()).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let canvas = if own { None } else { crate::evaluate_container(None, &outer) };
|
||||
let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l));
|
||||
for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] {
|
||||
if own && what == "canvas" {
|
||||
continue;
|
||||
}
|
||||
let case = format!("{what}, own effect {own}, knockout {knockout:?}");
|
||||
let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip"));
|
||||
assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before");
|
||||
assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() {
|
||||
// A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that
|
||||
// strokes: the group's fill still paints inside the clip, and the type's stroke over it.
|
||||
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
|
||||
let mut group = clip_group(2, painted_type(3, false, true));
|
||||
group.appearance =
|
||||
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into();
|
||||
let canvas = crate::evaluate_container(None, &group).unwrap();
|
||||
let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap();
|
||||
assert!(strokes.is_some() && !inside, "{canvas:?}");
|
||||
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
|
||||
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
|
||||
let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow));
|
||||
assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}");
|
||||
assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() {
|
||||
// A clip group with an unplaced linear gradient fill of its own and an Offset Path effect,
|
||||
// clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient
|
||||
// spans the region the clipping path clips to.
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut ty = painted_type(3, false, false);
|
||||
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
|
||||
for item in &mut ty.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
|
||||
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
|
||||
}
|
||||
}
|
||||
let mut group = clip_group(2, ty);
|
||||
group.appearance =
|
||||
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into();
|
||||
let canvas = crate::evaluate_container(None, &group).unwrap();
|
||||
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
|
||||
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
|
||||
let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box();
|
||||
let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom,
|
||||
_ => None,
|
||||
});
|
||||
let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}"));
|
||||
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
|
||||
assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() {
|
||||
// A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect
|
||||
// (moving everything 10 pt down, or scaling it to half its width around its middle) holds a
|
||||
// clip group clipped by type whose stroke has a Transform effect moving it 60 pt right,
|
||||
// outside the clip. On the canvas and in the export, the clip region is the type's glyphs
|
||||
// reshaped by the group's effect, and the group's fill paints that region alone, its gradient
|
||||
// spanning it: the moved stroke adds nothing to the region, the fill or the box the group's
|
||||
// effect scales around.
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut ty = painted_type(3, false, false);
|
||||
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
|
||||
for item in &mut ty.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
|
||||
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
|
||||
}
|
||||
}
|
||||
let live = clip_outline(&ty).expect("the type clips").0.bounding_box();
|
||||
let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0);
|
||||
// Scaled to half its width around the middle of the clip, which the stroke does not move.
|
||||
let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0);
|
||||
let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1);
|
||||
// The group's own fill art: every object outside the clip groups whose own fill is `paint`.
|
||||
fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) {
|
||||
let mine = n.appearance.items.iter().any(|i| match (i, paint) {
|
||||
(vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)),
|
||||
(vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p,
|
||||
_ => false,
|
||||
});
|
||||
if mine {
|
||||
out.push(n);
|
||||
}
|
||||
for c in n.children().into_iter().flatten().filter(|c| !c.clips()) {
|
||||
own_fills(c, paint, out);
|
||||
}
|
||||
}
|
||||
let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)];
|
||||
for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) {
|
||||
let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]);
|
||||
outer.appearance =
|
||||
Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into();
|
||||
let canvas = crate::evaluate_container(None, &outer).unwrap();
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group");
|
||||
for (what, art) in [("canvas", &canvas), ("export", &*exported)] {
|
||||
let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" });
|
||||
let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}"));
|
||||
assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}");
|
||||
let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art"));
|
||||
assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}");
|
||||
let mut fills = vec![];
|
||||
own_fills(art, &paint, &mut fills);
|
||||
assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}");
|
||||
let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}");
|
||||
if let Paint::Gradient(_) = paint {
|
||||
for fill in fills {
|
||||
let geom = match fill.appearance.fill_paint() {
|
||||
Paint::Gradient(g) => g.geom,
|
||||
_ => None,
|
||||
};
|
||||
let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}"));
|
||||
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
|
||||
assert!(
|
||||
(left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5,
|
||||
"{case}: the gradient {geom:?} spans the clip {region:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() {
|
||||
// A clip group with a placed linear gradient fill of its own, in a group with Free Distort,
|
||||
// clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip:
|
||||
// the gradient moves and scales from the clip's bounds, as for the same clip group whose type
|
||||
// does not stroke. The moved stroke adds nothing to those bounds.
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
|
||||
let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None };
|
||||
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
|
||||
fn placed_geom(n: &Node) -> Option<vectorcraft_color::GradientGeom> {
|
||||
if let Paint::Gradient(g) = n.appearance.fill_paint()
|
||||
&& g.geom.is_some()
|
||||
{
|
||||
return g.geom;
|
||||
}
|
||||
n.children().into_iter().flatten().find_map(|c| placed_geom(c))
|
||||
}
|
||||
let ends = |stroke: bool| {
|
||||
let mut ty = painted_type(3, false, false);
|
||||
if stroke {
|
||||
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
|
||||
for item in &mut ty.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
|
||||
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut group = clip_group(2, ty);
|
||||
group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
|
||||
let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]);
|
||||
let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
|
||||
outer.appearance.effects.push(fx("distort.freeDistort", corners));
|
||||
let canvas = crate::evaluate_container(None, &outer).unwrap();
|
||||
if stroke {
|
||||
assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}");
|
||||
}
|
||||
placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}"))
|
||||
};
|
||||
let (plain, stroked) = (ends(false), ends(true));
|
||||
assert!(
|
||||
plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5,
|
||||
"the gradient {stroked:?} follows the clip as {plain:?} does"
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
|
||||
/// segments into pieces within an anchor budget.
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces};
|
||||
|
||||
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
|
||||
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
|
||||
|
||||
@@ -59,6 +59,9 @@ chrono = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in
|
||||
# Cargo.lock (vectorcraft-eps), so this adds no new crate.
|
||||
encoding_rs = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -70,8 +73,9 @@ log = { workspace = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`).
|
||||
# Already in Cargo.lock (walkdir), so this adds no new crate.
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
|
||||
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time
|
||||
//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used
|
||||
//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and
|
||||
//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and
|
||||
//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to.
|
||||
//! For each it times two ways of finding the selected objects that no other selected object holds: a
|
||||
//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids
|
||||
//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both
|
||||
//! give the same count, visit the same paints in the same order and leave the same document as
|
||||
//! `map_solid_paints_in` before it times them.
|
||||
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10
|
||||
//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs
|
||||
//! everything, in ms; elsewhere they are wall times.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hint::black_box;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
/// The colors the rectangles use, each with a swatch to link to.
|
||||
const COLORS: usize = 50;
|
||||
|
||||
/// The calls in each timed run; a row gives the time of one call.
|
||||
const REPS: usize = 10;
|
||||
|
||||
/// A way of finding the ids that no other listed id holds.
|
||||
type Roots = fn(&Document, &[NodeId]) -> Vec<NodeId>;
|
||||
|
||||
/// A way of applying a link function to the paints of the listed ids, returning the count changed.
|
||||
type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
|
||||
fn measure(f: impl FnOnce()) -> f64 {
|
||||
match thread_cpu_ns() {
|
||||
Some(start) => {
|
||||
f();
|
||||
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
|
||||
}
|
||||
None => {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Color `i` of [`COLORS`]: each has its own red value.
|
||||
fn color(i: usize) -> Color {
|
||||
Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25)
|
||||
}
|
||||
|
||||
/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models.
|
||||
fn red_bits(c: &Color) -> u32 {
|
||||
match c {
|
||||
Color::Rgb { r, .. } => r.to_bits(),
|
||||
_ => u32::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor.
|
||||
fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect()
|
||||
}
|
||||
|
||||
/// [`roots_by_search`] with each ancestor looked up in a set of the ids.
|
||||
fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let listed: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect()
|
||||
}
|
||||
|
||||
/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed
|
||||
/// paint put in place: the work of `map_solid_paints_in`.
|
||||
fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize {
|
||||
let mut n = 0;
|
||||
for id in roots(d, ids) {
|
||||
let Some(mut node) = d.node(id).cloned() else { continue };
|
||||
let count = map_node_solid_paints(&mut node, f);
|
||||
if count > 0
|
||||
&& let Some(slot) = d.node_mut(id)
|
||||
{
|
||||
*slot = node;
|
||||
n += count;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global
|
||||
/// swatches, recording each paint visited. Returns the count and the visits.
|
||||
fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option<String>)>) {
|
||||
let names: HashMap<u32, String> = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect();
|
||||
let mut visits = vec![];
|
||||
let n = map(d, ids, &mut |c, s, _| {
|
||||
visits.push((*c, s.clone()));
|
||||
match names.get(&red_bits(c)) {
|
||||
Some(name) if s.is_none() => {
|
||||
*s = Some(name.clone());
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
(n, visits)
|
||||
}
|
||||
|
||||
fn rect(d: &mut Document, i: usize) -> Arc<Node> {
|
||||
let id = d.alloc_id();
|
||||
let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
|
||||
let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0));
|
||||
let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0);
|
||||
Arc::new(Node::path(id, r, a))
|
||||
}
|
||||
|
||||
/// `n` rectangles in the first layer, all selected.
|
||||
fn flat(n: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(1600.0, 1200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut ids = vec![];
|
||||
for i in 0..n {
|
||||
let node = rect(&mut d, i);
|
||||
ids.push(node.id);
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap();
|
||||
}
|
||||
(d, ids)
|
||||
}
|
||||
|
||||
/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with
|
||||
/// `groups` the two groups above each of them too, listed first.
|
||||
fn nested(groups: bool) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(1600.0, 1200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut outer_ids, mut leaves) = (vec![], vec![]);
|
||||
for g in 0..1_000 {
|
||||
let rects: Vec<Arc<Node>> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect();
|
||||
leaves.extend(rects.iter().map(|r| r.id));
|
||||
let inner = Node::group(d.alloc_id(), rects);
|
||||
let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]);
|
||||
if groups {
|
||||
outer_ids.extend([outer.id, inner.id]);
|
||||
}
|
||||
d.insert(Some(l), usize::MAX, outer).unwrap();
|
||||
}
|
||||
outer_ids.extend(leaves);
|
||||
(d, outer_ids)
|
||||
}
|
||||
|
||||
fn bench(name: &str, (doc, ids): (Document, Vec<NodeId>)) {
|
||||
let mut shipped = doc.clone();
|
||||
let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f));
|
||||
for roots in [roots_by_search as Roots, roots_by_set] {
|
||||
let mut d = doc.clone();
|
||||
let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f));
|
||||
assert_eq!(got, want, "{name}: the same count and visits");
|
||||
assert_eq!(d.layers, shipped.layers, "{name}: the same document");
|
||||
}
|
||||
let (mut old, mut new, mut real) = (vec![], vec![], vec![]);
|
||||
let timed = |map: &mut Map| {
|
||||
let mut docs = vec![doc.clone(); REPS];
|
||||
measure(|| {
|
||||
for d in &mut docs {
|
||||
black_box(link(d, black_box(&ids), &mut *map));
|
||||
}
|
||||
}) / REPS as f64
|
||||
};
|
||||
for i in 0..iters() {
|
||||
let run = |roots: Roots, out: &mut Vec<f64>| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f)));
|
||||
if i % 2 == 0 {
|
||||
run(roots_by_search, &mut old);
|
||||
run(roots_by_set, &mut new);
|
||||
} else {
|
||||
run(roots_by_set, &mut new);
|
||||
run(roots_by_search, &mut old);
|
||||
}
|
||||
real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f)));
|
||||
}
|
||||
let (old, new, real) = (median(old), median(new), median(real));
|
||||
println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
|
||||
println!(
|
||||
" {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}",
|
||||
"document",
|
||||
"ids",
|
||||
"linked",
|
||||
format!("search, {unit}"),
|
||||
format!("set, {unit}"),
|
||||
format!("shipped, {unit}"),
|
||||
"speedup"
|
||||
);
|
||||
bench("2,000 rectangles in one layer", flat(2_000));
|
||||
bench("20,000 rectangles in one layer", flat(20_000));
|
||||
bench("5,000 rectangles in 1,000 groups of groups", nested(false));
|
||||
bench("the same with the 2,000 groups listed first", nested(true));
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set`
|
||||
//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For
|
||||
//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and
|
||||
//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole
|
||||
//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named.
|
||||
//! The whole-command rows include the document copy the command makes for undo; each run is undone
|
||||
//! before the next, outside the timed part.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times
|
||||
//! and gives the time of one.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares in one group, and the squares' ids in stacking order.
|
||||
fn document(n: usize) -> (Document, NodeId, Vec<NodeId>) {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let kids: Vec<_> = (0..n)
|
||||
.map(|i| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
})
|
||||
.collect();
|
||||
let leaves = kids.iter().map(|k| k.id).collect();
|
||||
let group = b.group(kids, false);
|
||||
(b.build(), group, leaves)
|
||||
}
|
||||
|
||||
/// The merge that checks each leaf against the growing list.
|
||||
fn listed(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
|
||||
for id in leaves {
|
||||
if !out.contains(&id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The merge that checks each leaf against a set seeded with `out`.
|
||||
fn with_set(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let mut seen: HashSet<NodeId> = out.iter().copied().collect();
|
||||
for id in leaves {
|
||||
if seen.insert(id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<52} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part.
|
||||
fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 {
|
||||
let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "weight": 3});
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut r = Value::Null;
|
||||
let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap()));
|
||||
assert_eq!(r["objects"], n, "{r}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
t
|
||||
})
|
||||
.collect();
|
||||
median(runs)
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths in one group");
|
||||
let (doc, group, leaves) = document(n);
|
||||
|
||||
// Each run merges `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(Vec<NodeId>, Vec<NodeId>) -> Vec<NodeId>| -> (f64, Vec<NodeId>) {
|
||||
let mut last = Vec::new();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| leaves.clone()).collect();
|
||||
let mut done = Vec::with_capacity(reps);
|
||||
let t = ms(|| {
|
||||
for input in &mut work {
|
||||
done.push(f(Vec::new(), black_box(std::mem::take(input))));
|
||||
}
|
||||
});
|
||||
last = done.pop().unwrap();
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(listed);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both merges give the same list");
|
||||
assert_eq!(a, leaves);
|
||||
row("target merge, list search", old);
|
||||
row("target merge, set", new);
|
||||
println!(" {:<52} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc, None);
|
||||
row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n));
|
||||
row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -821,10 +821,12 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{fold_source, print_hidden};
|
||||
/// Document Info's category titles and the Objects category's count labels.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
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};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
@@ -886,6 +888,9 @@ pub(crate) use buildcmds::TracePresetChanges;
|
||||
/// The shapes a group selected alone gives the Pathfinder panel.
|
||||
pub use pathops::shape_count;
|
||||
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
@@ -901,6 +906,10 @@ pub use brushsym::current_symbol;
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{fold_source, print_hidden};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -35,5 +37,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v.extend(units::specs());
|
||||
v
|
||||
}
|
||||
@@ -6,8 +6,10 @@
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod check;
|
||||
mod fold;
|
||||
mod roles;
|
||||
|
||||
pub use fold::{fold_source, print_hidden};
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
@@ -15,6 +17,7 @@ use super::super::CommandSpec;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v.extend(fold::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
|
||||
use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks};
|
||||
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
||||
@@ -14,7 +14,7 @@ use crate::{Result, Session};
|
||||
const CHECK: &str = "addon.packaging.check";
|
||||
|
||||
/// How far apart the ends of two lines may be and still be joined, in points.
|
||||
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
|
||||
pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind {
|
||||
}
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let select = switch_or(p, "select", false, CHECK)?;
|
||||
let tolerance = match length_given(p, "tolerance", CHECK)? {
|
||||
None => TOLERANCE.1,
|
||||
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
|
||||
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
|
||||
};
|
||||
/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or
|
||||
/// `document`), the lines, and the ids of those on a non-printing layer.
|
||||
pub(super) struct Lines {
|
||||
pub scope: &'static str,
|
||||
pub lines: Vec<FoldLine>,
|
||||
pub non_printing: Vec<u64>,
|
||||
}
|
||||
|
||||
/// The tolerance `p` gives for `cmd`, or the default.
|
||||
pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> {
|
||||
match length_given(p, "tolerance", cmd)? {
|
||||
None => Ok(TOLERANCE.1),
|
||||
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t),
|
||||
Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while
|
||||
/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines
|
||||
/// are left out in every scope, members of a selected group included.
|
||||
pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, CHECK)?;
|
||||
let roots = checked_ids_or_selection(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Hidden lines are left out in every scope, members of a selected group included.
|
||||
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
|
||||
let (scope, targets) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
|
||||
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
|
||||
(false, true) => ("document", shown_targets(d)),
|
||||
};
|
||||
Ok(match (given, roots.is_empty()) {
|
||||
(true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)),
|
||||
(false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)),
|
||||
(false, true) => document_lines(d),
|
||||
})
|
||||
}
|
||||
|
||||
/// Every shown fold line of `d`.
|
||||
pub(super) fn document_lines(d: &Document) -> Lines {
|
||||
lines_of(d, "document", shown_targets(d))
|
||||
}
|
||||
|
||||
fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
|
||||
let table = RoleTable::of(d);
|
||||
let mut lines = vec![];
|
||||
let mut non_printing = vec![];
|
||||
@@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
|
||||
}
|
||||
let (found, mut issues) = blanks(&lines, tolerance);
|
||||
if !non_printing.is_empty() {
|
||||
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
|
||||
Lines { scope, lines, non_printing }
|
||||
}
|
||||
|
||||
/// The blanks `lines` make and their issues, the non-printing one last.
|
||||
pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) {
|
||||
let (found, mut issues) = blanks(&lines.lines, tolerance);
|
||||
if !lines.non_printing.is_empty() {
|
||||
issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None });
|
||||
}
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let rows: Vec<Value> = issues
|
||||
(found, issues)
|
||||
}
|
||||
|
||||
/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with.
|
||||
pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> {
|
||||
issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut row = json!({
|
||||
@@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let select = switch_or(p, "select", false, CHECK)?;
|
||||
let tolerance = tolerance(p, CHECK)?;
|
||||
let lines = lines(s, p, CHECK)?;
|
||||
let scope = lines.scope;
|
||||
let (found, issues) = found(&lines, tolerance);
|
||||
let d = &s.doc()?.doc;
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let rows = issue_rows(&issues, scope);
|
||||
if select {
|
||||
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
|
||||
ids.sort_unstable_by_key(|id| id.0);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by
|
||||
//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the
|
||||
//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_three_d::fold::{Blank, Issue, fold, pick};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or};
|
||||
use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance};
|
||||
use super::roles::{RoleTable, can_carry};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const FOLD: &str = "addon.packaging.fold";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "addon.packaging.fold",
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
}
|
||||
|
||||
/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the
|
||||
/// whole document): what the Fold Preview window folds.
|
||||
pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) {
|
||||
found(&document_lines(d), TOLERANCE.1)
|
||||
}
|
||||
|
||||
/// The objects the print on a folded blank leaves out: the layers that do not print and, unless
|
||||
/// `fold_lines`, every object with a line role.
|
||||
pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { printable: false, .. } => out.push(n.id),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)),
|
||||
_ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let table = RoleTable::of(d);
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
fn fold_command(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tolerance = tolerance(p, FOLD)?;
|
||||
let amount = number_or(p, "amount", 1.0, FOLD)?;
|
||||
if !(0.0..=1.0).contains(&amount) {
|
||||
return Err(bad(FOLD, "`amount` must be from 0 to 1"));
|
||||
}
|
||||
let base = match p.get("base") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?;
|
||||
Some(vectorcraft_geom::Point::new(x, y))
|
||||
}
|
||||
};
|
||||
let lines = lines(s, p, FOLD)?;
|
||||
let (blanks, issues) = found(&lines, tolerance);
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let picked = pick(&blanks, base);
|
||||
if base.is_some() && picked.is_none() {
|
||||
return Err(bad(FOLD, "`base` is in no panel"));
|
||||
}
|
||||
let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?)));
|
||||
let Some((index, blank, f)) = folded else {
|
||||
return Ok(json!({
|
||||
"ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [],
|
||||
"issues": issue_rows(&issues, lines.scope),
|
||||
}));
|
||||
};
|
||||
let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]);
|
||||
let panels: Vec<Value> = blank
|
||||
.panels
|
||||
.iter()
|
||||
.zip(&f.panels)
|
||||
.map(|(panel, placed)| {
|
||||
json!({
|
||||
"outline": panel.outline.to_bezpath().to_svg(),
|
||||
"frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t},
|
||||
"parent": placed.parent,
|
||||
"depth": placed.depth,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let hinges: Vec<Value> = f
|
||||
.hinges
|
||||
.iter()
|
||||
.map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap}))
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"ok": ok,
|
||||
"blank": index,
|
||||
"blanks": blanks.len(),
|
||||
"base": f.base,
|
||||
"panels": panels,
|
||||
"hinges": hinges,
|
||||
"collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(),
|
||||
"issues": issue_rows(&issues, lines.scope),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> u64 {
|
||||
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn role(s: &mut Session, role: &str, ids: &[u64]) {
|
||||
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
|
||||
}
|
||||
|
||||
fn fold(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.fold", &p).unwrap()
|
||||
}
|
||||
|
||||
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
|
||||
/// (outline, creases).
|
||||
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
|
||||
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
|
||||
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
|
||||
role(s, "cut", &[outline]);
|
||||
role(s, "crease", &creases);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(outline, creases)
|
||||
}
|
||||
|
||||
fn vector(v: &Value) -> [f64; 3] {
|
||||
let a = v.as_array().unwrap();
|
||||
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
|
||||
}
|
||||
|
||||
/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only).
|
||||
fn middle(d: &str) -> [f64; 2] {
|
||||
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
|
||||
let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
|
||||
let ((x0, x1), (y0, y1)) = (span(0), span(1));
|
||||
[(x0 + x1) / 2.0, (y0 + y1) / 2.0]
|
||||
}
|
||||
|
||||
fn near(a: [f64; 3], b: [f64; 3]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tray_folds_its_walls_up_round_the_base() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = fold(&mut s, json!({}));
|
||||
assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}");
|
||||
let panels = r["panels"].as_array().unwrap();
|
||||
assert_eq!(panels.len(), 5);
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let frame = &panels[base]["frame"];
|
||||
assert!(
|
||||
near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]),
|
||||
"{frame}"
|
||||
);
|
||||
assert!(panels[base]["parent"].is_null());
|
||||
assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data");
|
||||
for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) {
|
||||
assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}");
|
||||
// Each wall stands square to the base, below it (away from the print), its print facing out:
|
||||
// away from the base's middle (190, 190), toward the side the wall lies on.
|
||||
let [cx, cy] = middle(p["outline"].as_str().unwrap());
|
||||
let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"]));
|
||||
let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy);
|
||||
let (dx, dy) = (cx - 190.0, 190.0 - cy);
|
||||
let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] };
|
||||
assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}");
|
||||
assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}");
|
||||
}
|
||||
let hinges = r["hinges"].as_array().unwrap();
|
||||
assert_eq!(hinges.len(), 4);
|
||||
assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}");
|
||||
assert_eq!(r["collisions"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step");
|
||||
|
||||
// Flat, every frame is the flat blank's own.
|
||||
let r = fold(&mut s, json!({ "amount": 0 }));
|
||||
for p in r["panels"].as_array().unwrap() {
|
||||
assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_base_is_the_panel_under_a_point() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
// The left wall: x 100 to 140, y 140 to 240.
|
||||
let r = fold(&mut s, json!({ "base": [120, 190] }));
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let panels = r["panels"].as_array().unwrap();
|
||||
assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0]));
|
||||
// The tray's base is now a child of the wall, and the other walls its children.
|
||||
let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect();
|
||||
let mut sorted = depths.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}");
|
||||
let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string();
|
||||
assert!(e.contains("`base` is in no panel"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_are_refused() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
for (p, want) in [
|
||||
(json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"),
|
||||
(json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"),
|
||||
(json!({ "amount": "1" }), "`amount` must be a number"),
|
||||
(json!({ "base": [1] }), "`base` must be a point"),
|
||||
(json!({ "base": "middle" }), "`base` must be a point"),
|
||||
(json!({ "tolerance": 50 }), "`tolerance` must be from"),
|
||||
] {
|
||||
let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_blank_nothing_is_folded_and_the_issues_say_why() {
|
||||
let mut s = session();
|
||||
let r = fold(&mut s, json!({}));
|
||||
assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}");
|
||||
assert_eq!(r["panels"], json!([]));
|
||||
assert_eq!(r["issues"][0]["code"], "noCut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let art = path(&mut s, "M150 150 L200 150 L200 200 Z");
|
||||
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect();
|
||||
for id in creases.iter().chain([&outline, ¬es]) {
|
||||
assert!(hidden.contains(id), "{id} in {hidden:?}");
|
||||
}
|
||||
assert!(!hidden.contains(&art));
|
||||
let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect();
|
||||
assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out");
|
||||
let (blanks, issues) = cmd::fold_source(d);
|
||||
assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5));
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
//! UI's; the panel applies a length to the selection with `object.setBounds`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CONVERT: &str = "addon.units.convert";
|
||||
const SELECTION_SIZE: &str = "addon.units.selectionSize";
|
||||
/// The most characters of a refused value an error message shows.
|
||||
const SHOWN_CHARS: usize = 64;
|
||||
/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes.
|
||||
const MAX_TEXT_LEN: usize = 1024;
|
||||
/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one
|
||||
/// level of recursion per sign.
|
||||
const MAX_OPERATORS: usize = 128;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "addon.units.convert",
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
cmd!(
|
||||
query "addon.units.selectionSize",
|
||||
"Selection Size in Units",
|
||||
[],
|
||||
None,
|
||||
"{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}",
|
||||
has_selection,
|
||||
selection_size
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit,
|
||||
/// label, number, text}]}`.
|
||||
pub fn in_every_unit(pt: f64) -> Value {
|
||||
let units: Vec<Value> =
|
||||
Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect();
|
||||
json!({ "points": pt, "units": units })
|
||||
}
|
||||
|
||||
/// The unit `p` gives for a number without a suffix (points when left out; null is an error).
|
||||
fn unit_param(p: &Value) -> Result<Unit> {
|
||||
let Some(given) = p.get("unit") else { return Ok(Unit::Points) };
|
||||
let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian);
|
||||
named.ok_or_else(|| {
|
||||
let u = match given {
|
||||
Value::String(s) => clipped(s).escape_debug().to_string(),
|
||||
other => shown(other),
|
||||
};
|
||||
bad(CONVERT, format!("unknown units `{u}`"))
|
||||
})
|
||||
}
|
||||
|
||||
fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let unit = unit_param(p)?;
|
||||
let Some(v) = p.get("value").filter(|v| !v.is_null()) else {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
let pt = pt.filter(|&pt| finite_in_every_unit(pt));
|
||||
pt.map(in_every_unit).ok_or_else(|| {
|
||||
let v = shown(v);
|
||||
bad(CONVERT, format!("`value` must be a number, not {v}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /`
|
||||
/// signs?
|
||||
fn readable(s: &str) -> bool {
|
||||
s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS
|
||||
}
|
||||
|
||||
/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON,
|
||||
/// an array as `[…]` and an object as `{…}`.
|
||||
fn shown(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => Value::String(clipped(s)).to_string(),
|
||||
Value::Array(_) => "[…]".into(),
|
||||
Value::Object(_) => "{…}".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer.
|
||||
fn clipped(s: &str) -> String {
|
||||
match s.char_indices().nth(SHOWN_CHARS) {
|
||||
Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_size(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let measure = s.bounds_measure();
|
||||
let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) {
|
||||
Some(r) => Some(OrientedBox::aligned(r)),
|
||||
None => s.transform_box(&st.selection.objects),
|
||||
};
|
||||
let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?;
|
||||
Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) }))
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's
|
||||
//! size as the Transform panel measures it, bad params refused, and nothing in the document changed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn convert(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.units.convert", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The row of `r` for the unit with key `key`.
|
||||
fn row<'a>(r: &'a Value, key: &str) -> &'a Value {
|
||||
r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}"))
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_length_comes_back_in_every_unit_in_order() {
|
||||
let mut s = session();
|
||||
let r = convert(&mut s, json!({"value": "10mm"}));
|
||||
assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4));
|
||||
let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect();
|
||||
assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key));
|
||||
assert_eq!(row(&r, "millimeters")["number"], "10");
|
||||
assert_eq!(row(&r, "millimeters")["text"], "10 mm");
|
||||
assert_eq!(row(&r, "centimeters")["text"], "1 cm");
|
||||
assert_eq!(row(&r, "inches")["text"], "0.3937 in");
|
||||
assert_eq!(row(&r, "points")["text"], "28.346 pt");
|
||||
assert_eq!(row(&r, "q")["text"], "40 Q");
|
||||
assert_eq!(row(&r, "ha")["text"], "40 H");
|
||||
assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points");
|
||||
assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches");
|
||||
// Each row is what a field of that unit shows for the length.
|
||||
for u in Unit::EAST_ASIAN {
|
||||
let pt = 720.0 / 25.4;
|
||||
assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}");
|
||||
assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6));
|
||||
// A number without a unit is in `unit`, points by default.
|
||||
assert!(near(pt(&mut s, json!({"value": 12})), 12.0));
|
||||
assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54));
|
||||
assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6));
|
||||
assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0));
|
||||
// A suffix wins over `unit`.
|
||||
assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0));
|
||||
// A decimal comma reads as a point, as in the number fields.
|
||||
assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0));
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap();
|
||||
s.check_params("addon.units.selectionSize", &json!({})).unwrap();
|
||||
for (id, p) in [
|
||||
("addon.units.convert", json!({"value": 1, "units": "mm"})),
|
||||
("addon.units.convert", json!({"value": 1, "ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"ids": [1]})),
|
||||
("addon.units.selectionSize", json!({"value": 1})),
|
||||
] {
|
||||
match s.check_params(id, &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"),
|
||||
other => panic!("{id} {p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_follows_preview_bounds_and_selected_anchors() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap();
|
||||
let wh = |s: &mut Session| {
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
(r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap())
|
||||
};
|
||||
assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds");
|
||||
// Use Preview Bounds: the stroke's outer half on every side.
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}");
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap();
|
||||
// Two neighboring anchors selected (Direct Selection): the box around them, one edge of the
|
||||
// rectangle.
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
let (w, h) = wh(&mut s);
|
||||
assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_no_document_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0));
|
||||
let mut s = session();
|
||||
let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
convert(&mut s, json!({"value": "5mm"}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_and_units_are_refused() {
|
||||
let mut s = session();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"value": null}),
|
||||
json!({"value": "abc"}),
|
||||
json!({"value": "10 furlongs"}),
|
||||
json!({"value": "1in/0"}),
|
||||
json!({"value": "1e400"}),
|
||||
// Finite in points, too large in Q and Ha.
|
||||
json!({"value": 1.5e308}),
|
||||
json!({"value": "1.5e308"}),
|
||||
// A thousands comma is refused, as the number fields refuse it.
|
||||
json!({"value": "1,000 mm"}),
|
||||
json!({"value": "1,000.5"}),
|
||||
json!({"value": "+1,000"}),
|
||||
json!({"value": "1,000\""}),
|
||||
json!({"value": "1,000'"}),
|
||||
// A long expression is refused instead of exhausting the stack.
|
||||
json!({"value": format!("1{}", "+1".repeat(200_000))}),
|
||||
json!({"value": format!("1{}", "+1".repeat(129))}),
|
||||
json!({"value": true}),
|
||||
json!({"value": [1]}),
|
||||
json!({"value": 1, "unit": "furlongs"}),
|
||||
json!({"value": 1, "unit": 5}),
|
||||
json!({"value": 1, "unit": ["mm"]}),
|
||||
// Only an omitted `unit` is points.
|
||||
json!({"value": 1, "unit": null}),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"),
|
||||
other => panic!("{p}: expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_value_or_unit_is_refused_with_a_short_message() {
|
||||
let mut s = session();
|
||||
let long = "9".repeat(100_000);
|
||||
for (p, says) in [
|
||||
(json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))),
|
||||
(json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()),
|
||||
(json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))),
|
||||
(json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()),
|
||||
(json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()),
|
||||
] {
|
||||
match s.execute("addon.units.convert", &p) {
|
||||
Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"),
|
||||
other => panic!("expected BadParams, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_size_is_the_transform_panels() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected");
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(row(&r["width"], "inches")["text"], "1 in");
|
||||
assert_eq!(row(&r["height"], "picas")["text"], "3 p");
|
||||
// A turned object keeps its own sides, as the Transform panel's W and H show them.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let r = s.execute("addon.units.selectionSize", &json!({})).unwrap();
|
||||
let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap();
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width()));
|
||||
assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0));
|
||||
assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step");
|
||||
}
|
||||
@@ -36,8 +36,8 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
|
||||
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
@@ -169,6 +169,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
cmd!(
|
||||
"brush.objectOptions",
|
||||
"Options of Selected Object…",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}",
|
||||
has_doc,
|
||||
brush_object_options
|
||||
),
|
||||
cmd!(
|
||||
"object.expandBrush",
|
||||
"Expand Brush Strokes",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{
|
||||
AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value,
|
||||
anchor, bad, brush, check_numbers, find_command, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, str_param,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
// ---------- brushes ----------
|
||||
@@ -57,6 +58,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke:
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +88,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for it in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(st) = it {
|
||||
st.brush = None;
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,13 +133,17 @@ fn merge(base: &mut Value, patch: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`.
|
||||
/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps
|
||||
/// each stroke's own settings for it; a stroke left without a brush loses them.
|
||||
fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) {
|
||||
for it in items {
|
||||
if let AppearanceItem::Stroke(st) = it
|
||||
&& st.brush.as_deref() == Some(from)
|
||||
{
|
||||
st.brush = to.map(str::to_string);
|
||||
if to.is_none() {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,6 +502,166 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths
|
||||
/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's
|
||||
/// own settings, `reset` clears them; without either, nothing changes and the settings are given.
|
||||
pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.objectOptions";
|
||||
let params = match p.get("params") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(o)) => o.clone(),
|
||||
Some(_) => {
|
||||
let key = "params";
|
||||
return Err(bad(C, format!("`{key}` must be an object")));
|
||||
}
|
||||
};
|
||||
let reset = switch_or(p, "reset", false, C)?;
|
||||
if reset && !params.is_empty() {
|
||||
return Err(bad(C, "give `params` or `reset`, not both"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let ids = brush_targets(d, &roots(s, p)?);
|
||||
// Each brushed stroke: its path, its place in the appearance, its brush and its settings now.
|
||||
let mut strokes = vec![];
|
||||
for id in &ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
for (i, it) in n.appearance.items.iter().enumerate() {
|
||||
let AppearanceItem::Stroke(st) = it else { continue };
|
||||
if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) {
|
||||
strokes.push((*id, i, b, &st.brush_options));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) };
|
||||
if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) {
|
||||
return Err(bad(C, "the selected paths are painted with brushes of different types"));
|
||||
}
|
||||
// Only a bristle brush has none.
|
||||
if first.kind.stroke_option_keys().is_empty() {
|
||||
return Err(bad(C, "a bristle brush has no options of its own on a path"));
|
||||
}
|
||||
let out: Vec<NodeId> = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect();
|
||||
// Without params or reset the settings are only given: nothing is normalized or changed.
|
||||
if !reset && params.is_empty() {
|
||||
let keys = first.kind.stroke_option_keys();
|
||||
let own: serde_json::Map<String, Value> =
|
||||
strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own }));
|
||||
}
|
||||
let mut changes = vec![];
|
||||
let mut options = None;
|
||||
for (id, i, b, own) in &strokes {
|
||||
let next = if reset {
|
||||
serde_json::Map::new()
|
||||
} else {
|
||||
// Settings saved for another type of brush are left out.
|
||||
let keys = b.kind.stroke_option_keys();
|
||||
let mut merged: serde_json::Map<String, Value> =
|
||||
own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let was = merged.clone();
|
||||
// A colorization object changes only the fields it gives, and a null item of an
|
||||
// array keeps the stroke's own item (else the brush's).
|
||||
for (k, v) in ¶ms {
|
||||
let next = match (merged.get(k), v) {
|
||||
(Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => {
|
||||
let mut c = mine.clone();
|
||||
c.extend(fields.clone());
|
||||
Value::Object(c)
|
||||
}
|
||||
(Some(mine), _) => brush::keep_items(v, mine),
|
||||
(None, _) => v.clone(),
|
||||
};
|
||||
merged.insert(k.clone(), next);
|
||||
}
|
||||
keep_drawn_modes(b, &was, ¶ms, &mut merged);
|
||||
keep_largest_width(b, &was, ¶ms, &mut merged);
|
||||
b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))?
|
||||
};
|
||||
options.get_or_insert_with(|| next.clone());
|
||||
if &next != *own {
|
||||
changes.push((*id, *i, next));
|
||||
}
|
||||
}
|
||||
let changed: Vec<NodeId> = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect();
|
||||
if !changes.is_empty() {
|
||||
s.edit("Options of Selected Object", |d, _| {
|
||||
for (id, i, next) in changes {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) {
|
||||
st.brush_options = next;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() }))
|
||||
}
|
||||
|
||||
/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush.
|
||||
fn drawn_modes(b: &Brush) -> Option<Vec<Value>> {
|
||||
let modes = match &b.kind {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(s.modes()),
|
||||
_ => return None,
|
||||
};
|
||||
match modes {
|
||||
Ok(Value::Array(m)) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params`
|
||||
/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`,
|
||||
/// would change. A mode the stroke leaves to its values follows them, so without this a changed
|
||||
/// variation or range would also change the mode.
|
||||
fn keep_drawn_modes(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
let given = match params.get("modes") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(m)) => m.clone(),
|
||||
// A value of the wrong kind is refused when the settings are checked.
|
||||
Some(_) => return,
|
||||
};
|
||||
let (Some(before), Some(after)) =
|
||||
(b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if before == after {
|
||||
return;
|
||||
}
|
||||
let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect();
|
||||
merged.insert("modes".into(), Value::Array(kept));
|
||||
}
|
||||
|
||||
/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when
|
||||
/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is
|
||||
/// the width, so without this a changed width would also change the largest width.
|
||||
fn keep_largest_width(
|
||||
b: &Brush,
|
||||
was: &serde_json::Map<String, Value>,
|
||||
params: &serde_json::Map<String, Value>,
|
||||
merged: &mut serde_json::Map<String, Value>,
|
||||
) {
|
||||
if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) {
|
||||
return;
|
||||
}
|
||||
let art = |o: &serde_json::Map<String, Value>| match b.with_stroke_options(o).ok().map(|b| b.kind) {
|
||||
Some(BrushKind::Art(a)) => Some(a),
|
||||
_ => None,
|
||||
};
|
||||
let (Some(before), Some(after)) = (art(was), art(merged)) else { return };
|
||||
let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen());
|
||||
// Only a width that followed the pen has a largest width, and only one that still does uses it.
|
||||
if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width {
|
||||
merged.insert("width_max".into(), json!(before.width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them; `brush.replaceArt` reads a group of that name as that tile.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
@@ -659,6 +659,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
s.brush_options.clear();
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
|
||||
@@ -579,6 +579,11 @@ impl SwatchChoices {
|
||||
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
|
||||
}
|
||||
}
|
||||
/// Add for every conflict: each pasted swatch whose name the document gives another color
|
||||
/// comes in renamed.
|
||||
pub(crate) fn add_all() -> Self {
|
||||
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
|
||||
}
|
||||
fn of(&self, name: &str) -> SwatchChoice {
|
||||
self.by_name.get(name).copied().unwrap_or(self.all)
|
||||
}
|
||||
|
||||
@@ -754,10 +754,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof
|
||||
}
|
||||
|
||||
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
|
||||
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
|
||||
/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings
|
||||
/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps
|
||||
/// ([`map_graph_colors`]) and the art of every opacity mask.
|
||||
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
map_effect_colors(&mut n.appearance, f);
|
||||
map_stroke_brush_keys(&mut n.appearance, f);
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
if let Some(g) = e.graph.as_deref_mut() {
|
||||
map_graph_colors(g, f);
|
||||
@@ -773,6 +775,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a`
|
||||
/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key
|
||||
/// that does not read is left as it is.
|
||||
///
|
||||
/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options
|
||||
fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for it in &mut a.items {
|
||||
let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue };
|
||||
let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue };
|
||||
let Some(key) = c.get("key").and_then(|k| serde_json::from_value::<Color>(k.clone()).ok()) else { continue };
|
||||
let n = f(&key, None);
|
||||
if n != key {
|
||||
c.insert("key".into(), json!(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's
|
||||
/// colorization matches it with.
|
||||
fn matches_key(c: &Color, key: &Color) -> bool {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
(entry, (name, format!("{}, {detail}", kind.label())))
|
||||
}
|
||||
|
||||
/// The artboards the Artboard tool has selected while it is the current tool, in artboard order,
|
||||
/// with the index of its active artboard; none with another tool or when it has none of the
|
||||
/// document's artboards selected. Indices the document does not have are left out.
|
||||
fn artboard_tool_selection(s: &Session) -> Option<(Vec<usize>, usize)> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return None;
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let t = s.tool_options_of("artboard");
|
||||
let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let mut picked: Vec<usize> = t["selected"].as_array().into_iter().flatten().filter_map(index).collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
let first = *picked.first()?;
|
||||
let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first);
|
||||
Some((picked, active))
|
||||
}
|
||||
|
||||
/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the
|
||||
/// current tool: their `selectedArtboards` entries (in the document's units), and for each its
|
||||
/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of
|
||||
/// artboard `active`.
|
||||
fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec<Value>, Vec<(String, String)>) {
|
||||
let (u, per) = (d.units, d.units.points());
|
||||
let origin = d.ruler_origin_for(active);
|
||||
let mut entries = vec![];
|
||||
let mut rows = vec![];
|
||||
for &i in picked {
|
||||
let Some(a) = d.artboards.get(i) else { continue };
|
||||
let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y);
|
||||
entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per }));
|
||||
rows.extend([
|
||||
("Artboard".to_string(), a.name.clone()),
|
||||
("Width".into(), u.format(w)),
|
||||
("Height".into(), u.format(h)),
|
||||
("X".into(), u.format(x)),
|
||||
("Y".into(), u.format(y)),
|
||||
]);
|
||||
}
|
||||
(entries, rows)
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of
|
||||
/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or
|
||||
/// stroked with a spot color, with a pattern and with a gradient.
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
|
||||
/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows
|
||||
/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
|
||||
/// pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
selected_artboards: &[(String, String)],
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
font_details: &[(String, String)],
|
||||
images: &[ImageRow],
|
||||
@@ -215,7 +259,19 @@ fn sections(
|
||||
rows.extend(
|
||||
d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))),
|
||||
);
|
||||
rows.extend(selected_artboards.iter().cloned());
|
||||
rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi)));
|
||||
let setup = &d.setup;
|
||||
let colors = match setup.grid_colors_name() {
|
||||
"Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "),
|
||||
name => name.to_string(),
|
||||
};
|
||||
rows.extend([
|
||||
("Grid Size".to_string(), setup.grid_size.label().to_string()),
|
||||
("Grid Colors".into(), colors),
|
||||
("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()),
|
||||
("Flattener Preset".into(), setup.flattener().to_string()),
|
||||
]);
|
||||
let counts = [
|
||||
("Swatches", "swatches"),
|
||||
("Character Styles", "characterStyles"),
|
||||
@@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("text") => true,
|
||||
Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))),
|
||||
};
|
||||
let artboard_tool = artboard_tool_selection(s);
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
@@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default();
|
||||
out["document"]["selectedArtboards"] = json!(selected_entries);
|
||||
let sections = sections(
|
||||
d,
|
||||
&out,
|
||||
&selected_rows,
|
||||
&fonts,
|
||||
&font_rows,
|
||||
&image_rows,
|
||||
&brush_rows,
|
||||
&repeat_rows,
|
||||
&spot_rows,
|
||||
&pattern_rows,
|
||||
&gradient_rows,
|
||||
category,
|
||||
);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value {
|
||||
"unitId": d.units.key(),
|
||||
"artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::<Vec<_>>(),
|
||||
"rasterEffectsPpi": d.raster_effects_ppi,
|
||||
"transparency": {
|
||||
"gridSize": d.setup.grid_size.id(),
|
||||
"gridColors": d.setup.grid_colors.map(|c| c.to_hex()),
|
||||
"gridColorsName": d.setup.grid_colors_name(),
|
||||
"simulatePaper": d.setup.simulate_paper,
|
||||
"flattenerPreset": d.setup.flattener(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -875,6 +954,101 @@ mod tests {
|
||||
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
|
||||
}
|
||||
|
||||
/// The Document category's rows from `info`, as (label, value) pairs.
|
||||
fn document_rows(i: &Value) -> Vec<(String, String)> {
|
||||
let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap();
|
||||
doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect()
|
||||
}
|
||||
|
||||
/// Document lists File › Document Setup's transparency settings: the grid's size and colors
|
||||
/// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset.
|
||||
#[test]
|
||||
fn info_lists_the_transparency_settings() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
let t = &i["document"]["transparency"];
|
||||
assert_eq!(
|
||||
(t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()),
|
||||
(json!("medium"), json!("Light"), json!(false), json!("Medium Resolution"))
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap();
|
||||
let expected =
|
||||
[("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
s.execute(
|
||||
"document.setup",
|
||||
&json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}),
|
||||
)
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"]));
|
||||
assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom");
|
||||
let rows = document_rows(&i);
|
||||
let expected =
|
||||
[("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")];
|
||||
assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}");
|
||||
}
|
||||
|
||||
/// While the Artboard tool is the current tool, Document lists each artboard it has selected
|
||||
/// after the artboards: its name, width, height and the X and Y of its top-left corner from the
|
||||
/// ruler origin of the tool's active artboard. With another tool it lists none.
|
||||
#[test]
|
||||
fn info_lists_the_artboards_the_artboard_tool_selected() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap();
|
||||
let before = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(before["document"]["selectedArtboards"], json!([]));
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([2, 1, 7]));
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
// Artboard 2 is active: positions are measured from its top-left corner.
|
||||
assert_eq!(
|
||||
i["document"]["selectedArtboards"],
|
||||
json!([
|
||||
{"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0},
|
||||
{"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0},
|
||||
])
|
||||
);
|
||||
let rows = document_rows(&i);
|
||||
let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4;
|
||||
let expected = [
|
||||
("Artboard", "Artboard 2"),
|
||||
("Width", "60 pt"),
|
||||
("Height", "80 pt"),
|
||||
("X", "-250 pt"),
|
||||
("Y", "30 pt"),
|
||||
("Artboard", "Back"),
|
||||
("Width", "100 pt"),
|
||||
("Height", "50 pt"),
|
||||
("X", "0 pt"),
|
||||
("Y", "0 pt"),
|
||||
("Raster Effects", "72 ppi"),
|
||||
];
|
||||
assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}");
|
||||
// The rows follow the document's units and its ruler origin.
|
||||
s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap();
|
||||
s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap();
|
||||
s.set_tool_option("selected", &json!([2]));
|
||||
let i = s.execute("document.info", &json!({"category": "document"})).unwrap();
|
||||
let entry = &i["document"]["selectedArtboards"];
|
||||
assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2)));
|
||||
assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}");
|
||||
let rows = document_rows(&i);
|
||||
assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}");
|
||||
// Another tool: no artboard rows.
|
||||
s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(i["document"]["selectedArtboards"], json!([]));
|
||||
assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i));
|
||||
}
|
||||
|
||||
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
|
||||
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
|
||||
#[test]
|
||||
|
||||
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Path Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes",
|
||||
has_selection,
|
||||
erase_segments
|
||||
),
|
||||
|
||||
@@ -522,13 +522,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>)
|
||||
Ok(ids_json(&ids))
|
||||
}
|
||||
|
||||
/// The Path Eraser's band width, in points (VectorCraft's own range).
|
||||
const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0);
|
||||
|
||||
pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseSegments";
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let w = number_or(p, "width", 8.0, C)?;
|
||||
if !(w.is_finite() && w > 0.0) {
|
||||
return Err(bad(C, "width must be positive"));
|
||||
}
|
||||
let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) {
|
||||
|
||||
@@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError {
|
||||
bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke"))
|
||||
}
|
||||
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`.
|
||||
/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another
|
||||
/// brush (Options of Selected Object) are cleared.
|
||||
fn set_brush(d: &mut Document, id: NodeId, name: &str) {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
if st.brush.as_deref() != Some(name) {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
@@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The document state that commands also change without an undo step: the perspective grid's view
|
||||
/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its
|
||||
/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each
|
||||
/// undo and redo step keeps it as the document on its other side had it
|
||||
/// ([`crate::HistoryEntry::unrecorded`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Unrecorded {
|
||||
grid: vectorcraft_doc::GridPrefs,
|
||||
export_settings: serde_json::Map<String, Value>,
|
||||
brush: Option<Value>,
|
||||
symbol: Option<Value>,
|
||||
options: [bool; 5],
|
||||
plane: Plane,
|
||||
}
|
||||
|
||||
impl Unrecorded {
|
||||
pub(crate) fn of(d: &Document) -> Self {
|
||||
let g = PerspectiveGrid::current(d);
|
||||
Unrecorded {
|
||||
grid: d.grid.clone(),
|
||||
export_settings: d.export_settings.clone(),
|
||||
brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(),
|
||||
symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(),
|
||||
options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers],
|
||||
plane: g.plane,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had
|
||||
/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the
|
||||
/// document before the undo or redo, since it changed after the step without an undo step. A part
|
||||
/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also
|
||||
/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the
|
||||
/// active plane kept is not the one it holds.
|
||||
fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) {
|
||||
fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T {
|
||||
if back == step { now.clone() } else { back.clone() }
|
||||
}
|
||||
let back = Unrecorded::of(d);
|
||||
let cur = Unrecorded::of(now);
|
||||
let mut want = Unrecorded {
|
||||
grid: pick(&back.grid, &step.grid, &cur.grid),
|
||||
export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings),
|
||||
brush: pick(&back.brush, &step.brush, &cur.brush),
|
||||
symbol: pick(&back.symbol, &step.symbol, &cur.symbol),
|
||||
options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])),
|
||||
plane: pick(&back.plane, &step.plane, &cur.plane),
|
||||
};
|
||||
if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) {
|
||||
want.brush = back.brush.clone();
|
||||
}
|
||||
if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) {
|
||||
want.symbol = back.symbol.clone();
|
||||
}
|
||||
if want == back {
|
||||
return;
|
||||
}
|
||||
let m = Arc::make_mut(d);
|
||||
for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] {
|
||||
match v {
|
||||
Some(v) => m.unknown.insert(key.into(), v.clone()),
|
||||
None => m.unknown.remove(key),
|
||||
};
|
||||
}
|
||||
if (want.options, want.plane) != (back.options, back.plane) {
|
||||
let mut g = PerspectiveGrid::current(m);
|
||||
[g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options;
|
||||
if g.plane != want.plane {
|
||||
g.plane = want.plane;
|
||||
g.inferred = None;
|
||||
}
|
||||
g.keep_positioning_valid();
|
||||
super::distortcmds::store_grid(m, &g);
|
||||
}
|
||||
m.grid = want.grid;
|
||||
m.export_settings = want.export_settings;
|
||||
}
|
||||
|
||||
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
settle_interaction(s)?;
|
||||
let menu = s.menu.clone();
|
||||
@@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let editing = st.doc.mask_edit.map(|m| m.layer);
|
||||
let editing_symbol = st.doc.symbol_edit.clone();
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
@@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let editing = st.doc.mask_edit.map(|m| m.layer);
|
||||
let editing_symbol = st.doc.symbol_edit.clone();
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
@@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Select every surviving piece while retaining intentional compound-path structure.
|
||||
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
|
||||
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
|
||||
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
|
||||
/// references with surviving object IDs.
|
||||
/// parent if now empty; a compound left with one member stays a compound path, as after Clear;
|
||||
/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which
|
||||
/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on
|
||||
/// success, replacing direct-selection references with surviving object IDs.
|
||||
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.clone();
|
||||
@@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
// The selected ruler guides were copied too (#3226): they go in the same undo step.
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
// The compound paths that hold a root; one left with no members goes too.
|
||||
let compounds: BTreeSet<NodeId> = roots
|
||||
.iter()
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect();
|
||||
let mut survivors = vec![];
|
||||
let mut pieces = super::pathops::Beside::replacing(d, roots);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(*id) else { continue };
|
||||
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
|
||||
if !has_direct || node.path_data().is_none() {
|
||||
remove_leaving_no_empty_compound(d, *id)?;
|
||||
pieces.put(d, *id, vec![])?;
|
||||
continue;
|
||||
}
|
||||
let original = super::path::deletion_source(d, *id)?;
|
||||
@@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if subpaths.is_empty() {
|
||||
remove_leaving_no_empty_compound(d, *id)?;
|
||||
pieces.put(d, *id, vec![])?;
|
||||
} else {
|
||||
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
|
||||
}
|
||||
}
|
||||
pieces.finish(d)?;
|
||||
let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect();
|
||||
super::pathops::remove_each(d, &emptied)?;
|
||||
selection.set(survivors);
|
||||
selection.anchors.clear();
|
||||
selection.segments.clear();
|
||||
@@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
|
||||
/// A compound left with one member stays a compound path, as after Clear.
|
||||
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
|
||||
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(id)?;
|
||||
if let Some(p) = parent
|
||||
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
|
||||
{
|
||||
d.remove(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
@@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
|
||||
pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> {
|
||||
v.into_iter().map(Arc::new).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties
|
||||
//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection,
|
||||
//! the clipboard and the undo history exactly as removing each of them on its own does.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks};
|
||||
|
||||
use super::*;
|
||||
use crate::tests_large_edits::{session, square};
|
||||
|
||||
/// Cut's removal with every root selected whole or emptied taken out by its own
|
||||
/// [`Document::remove`], and its compound path removed right after when that left it empty. The
|
||||
/// tests compare [`cut_direct_selection`] with it.
|
||||
fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.clone();
|
||||
s.edit("Cut", |d, selection| {
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
|
||||
let mut survivors = vec![];
|
||||
let mut pieces = super::super::pathops::Beside::replacing(d, roots);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(*id) else { continue };
|
||||
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
|
||||
if !has_direct || node.path_data().is_none() {
|
||||
remove_one(d, *id)?;
|
||||
continue;
|
||||
}
|
||||
let original = super::super::path::deletion_source(d, *id)?;
|
||||
let seg_refs = sel.segments.get(id);
|
||||
let anchor_refs = sel.anchors.get(id);
|
||||
let mut subpaths = Vec::new();
|
||||
let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths);
|
||||
for (si, sp) in owned.into_iter().enumerate() {
|
||||
let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
|
||||
if cuts.is_empty() {
|
||||
subpaths.push(sp);
|
||||
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
|
||||
subpaths.extend(super::super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect();
|
||||
subpaths.extend(super::super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if subpaths.is_empty() {
|
||||
remove_one(d, *id)?;
|
||||
} else {
|
||||
survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
|
||||
}
|
||||
}
|
||||
pieces.finish(d)?;
|
||||
selection.set(survivors);
|
||||
selection.anchors.clear();
|
||||
selection.segments.clear();
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Removes object `id`, and the compound path that held it when it was the compound's last member.
|
||||
fn remove_one(d: &mut Document, id: NodeId) -> Result<()> {
|
||||
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(id)?;
|
||||
if let Some(p) = parent
|
||||
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
|
||||
{
|
||||
d.remove(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of
|
||||
/// [`cut_direct_selection`].
|
||||
fn reference_cut(s: &mut Session) {
|
||||
let (direct, roots) = copy_cut_targets(s).unwrap();
|
||||
assert!(direct, "the selection is a direct selection");
|
||||
copy(s, &json!({})).unwrap();
|
||||
cut_one_at_a_time(s, &roots).unwrap();
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`.
|
||||
fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) {
|
||||
run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
for (id, anchors) in partial {
|
||||
run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of every node of the document, depth first, with the depth of each.
|
||||
fn tree(d: &Document) -> Vec<(usize, NodeId)> {
|
||||
fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) {
|
||||
out.push((depth, n.id));
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, 0, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo
|
||||
/// steps.
|
||||
fn assert_same(a: &Session, b: &Session, when: &str) {
|
||||
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
|
||||
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
|
||||
assert!(*x.doc == *y.doc, "{when}: the document");
|
||||
assert_eq!(x.selection, y.selection, "{when}: the selection");
|
||||
// Each session's document has its own uid; the clipboard names the one it came from.
|
||||
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
|
||||
let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() };
|
||||
assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard");
|
||||
assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps");
|
||||
assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps");
|
||||
}
|
||||
|
||||
/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks
|
||||
/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after
|
||||
/// the Cut.
|
||||
fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session {
|
||||
let (mut a, mut b) = (make(), make());
|
||||
let before = a.doc().unwrap().doc.clone();
|
||||
assert_same(&a, &b, "before");
|
||||
run(&mut a, "edit.cut", json!({}));
|
||||
reference_cut(&mut b);
|
||||
assert_same(&a, &b, "Cut");
|
||||
let after = a.doc().unwrap().doc.clone();
|
||||
run(&mut a, "edit.undo", json!({}));
|
||||
run(&mut b, "edit.undo", json!({}));
|
||||
assert_same(&a, &b, "Undo");
|
||||
assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document");
|
||||
run(&mut a, "edit.redo", json!({}));
|
||||
run(&mut b, "edit.redo", json!({}));
|
||||
assert_same(&a, &b, "Redo");
|
||||
assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut");
|
||||
run(&mut a, "edit.undo", json!({}));
|
||||
run(&mut a, "edit.redo", json!({}));
|
||||
a
|
||||
}
|
||||
|
||||
/// A new document; [`rect`] adds squares to it.
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
s
|
||||
}
|
||||
|
||||
/// Adds a 10 pt square to the current layer, 20 pt right of the last one.
|
||||
fn rect(s: &mut Session) -> NodeId {
|
||||
let x = 20.0 * s.doc().unwrap().doc.node_count() as f64;
|
||||
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Makes a compound path of `ids` and returns it with its members in order.
|
||||
fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
|
||||
let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect();
|
||||
(c, members)
|
||||
}
|
||||
|
||||
/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed.
|
||||
fn three_anchors() -> Value {
|
||||
json!([[0, 0], [0, 1], [0, 2]])
|
||||
}
|
||||
|
||||
/// Anchors 0 and 1 of a square: Cut keeps its other three sides.
|
||||
fn two_anchors() -> Value {
|
||||
json!([[0, 0], [0, 1]])
|
||||
}
|
||||
|
||||
/// The compound path whose members are cut one whole and one emptied goes with them; the other
|
||||
/// compound path keeps its one member left, as a compound path.
|
||||
#[test]
|
||||
fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let first = [(); 2].map(|()| rect(&mut s));
|
||||
let (gone, gone_members) = compound(&mut s, &first);
|
||||
let second = [(); 3].map(|()| rect(&mut s));
|
||||
let (kept, kept_members) = compound(&mut s, &second);
|
||||
let other = rect(&mut s);
|
||||
select_direct(
|
||||
&mut s,
|
||||
&[gone_members[0], kept_members[0]],
|
||||
&[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())],
|
||||
);
|
||||
(s, gone, kept, kept_members[2], other)
|
||||
};
|
||||
let s = same_as_one_at_a_time(|| make().0);
|
||||
let (_, gone, kept, left, other) = make();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(gone).is_none(), "the compound path whose members all went is removed");
|
||||
let kept = d.node(kept).expect("the compound path with a member left stays");
|
||||
assert!(matches!(kept.kind, NodeKind::Compound { .. }));
|
||||
assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected");
|
||||
}
|
||||
|
||||
/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept
|
||||
/// siblings, keep the order and ids that removing them one at a time leaves.
|
||||
#[test]
|
||||
fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let a = [(); 4].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
let b = [(); 4].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
let c = [(); 4].map(|()| rect(&mut s));
|
||||
select_direct(
|
||||
&mut s,
|
||||
&[a[0], a[2], b[3], c[1]],
|
||||
&[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())],
|
||||
);
|
||||
s
|
||||
};
|
||||
let s = same_as_one_at_a_time(make);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected");
|
||||
}
|
||||
|
||||
/// Selected ruler guides go with the objects, in the Cut's undo step.
|
||||
#[test]
|
||||
fn cut_removes_the_selected_guides_with_the_objects() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let [a, b, c] = [(); 3].map(|()| rect(&mut s));
|
||||
run(&mut s, "guide.add", json!({"vertical": true, "pos": 30}));
|
||||
run(&mut s, "guide.add", json!({"vertical": false, "pos": 40}));
|
||||
select_direct(&mut s, &[a, c], &[(b, two_anchors())]);
|
||||
run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true}));
|
||||
s
|
||||
};
|
||||
let s = same_as_one_at_a_time(make);
|
||||
assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed");
|
||||
assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard");
|
||||
}
|
||||
|
||||
/// Roots that are not separate (one inside another) are removed one at a time, as before.
|
||||
#[test]
|
||||
fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() {
|
||||
let make = || {
|
||||
let mut s = new_doc();
|
||||
let a = [(); 3].map(|()| rect(&mut s));
|
||||
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s);
|
||||
select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]);
|
||||
(s, vec![a[1], group, b])
|
||||
};
|
||||
let (mut x, roots) = make();
|
||||
let (mut y, _) = make();
|
||||
copy(&mut x, &json!({})).unwrap();
|
||||
copy(&mut y, &json!({})).unwrap();
|
||||
cut_direct_selection(&mut x, &roots).unwrap();
|
||||
cut_one_at_a_time(&mut y, &roots).unwrap();
|
||||
assert_same(&x, &y, "Cut");
|
||||
}
|
||||
|
||||
/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and
|
||||
/// anchors 0 and 1 of the square after them picked.
|
||||
fn many() -> Session {
|
||||
let mut s = session(10_001, square);
|
||||
let ids = crate::tests_large_edits::layer(&s, 0);
|
||||
let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect();
|
||||
select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The tree walks [`tree_walks`] counts while `f` runs on `s`.
|
||||
fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 {
|
||||
let before = tree_walks();
|
||||
f(s);
|
||||
tree_walks() - before
|
||||
}
|
||||
|
||||
/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's
|
||||
/// tree a few times, where removing them one at a time walks it several times for each object.
|
||||
#[test]
|
||||
fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() {
|
||||
let s = same_as_one_at_a_time(many);
|
||||
assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001);
|
||||
let (mut a, mut b) = (many(), many());
|
||||
let batched = walks(&mut a, |s| {
|
||||
run(s, "edit.cut", json!({}));
|
||||
});
|
||||
let one_at_a_time = walks(&mut b, reference_cut);
|
||||
println!("tree walks: Cut {batched}, one at a time {one_at_a_time}");
|
||||
assert!(batched <= 64, "Cut walked the document's tree {batched} times");
|
||||
assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}");
|
||||
}
|
||||
|
||||
/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux).
|
||||
fn cpu_time() -> 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 middle of `v`.
|
||||
fn median(mut v: Vec<Duration>) -> Duration {
|
||||
v.sort_unstable();
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's
|
||||
/// CPU and wall-clock time with the medians. Run it with
|
||||
/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing; prints the numbers"]
|
||||
fn direct_selection_cut_timing() {
|
||||
let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default();
|
||||
for round in 0..7 {
|
||||
for (k, (cpu, wall)) in runs.iter_mut().enumerate() {
|
||||
let mut s = many();
|
||||
let (c0, w0) = (cpu_time(), Instant::now());
|
||||
if k == 0 {
|
||||
reference_cut(&mut s);
|
||||
} else {
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
}
|
||||
let w = w0.elapsed();
|
||||
let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w);
|
||||
println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]);
|
||||
cpu.push(c);
|
||||
wall.push(w);
|
||||
}
|
||||
}
|
||||
for (k, (cpu, wall)) in runs.into_iter().enumerate() {
|
||||
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
|
||||
}
|
||||
}
|
||||
@@ -1150,21 +1150,27 @@ fn random_brushes_baked<'a>(
|
||||
std::borrow::Cow::Owned(def)
|
||||
}
|
||||
|
||||
/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or
|
||||
/// scatter brush with Random variation, or a bristle brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool {
|
||||
/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different
|
||||
/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle
|
||||
/// brush?
|
||||
fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map<String, Value>) -> bool {
|
||||
use vectorcraft_brush::{BrushKind, Variation};
|
||||
brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind {
|
||||
let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false };
|
||||
let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() };
|
||||
let b = edited.as_ref().unwrap_or(brush);
|
||||
match &b.kind {
|
||||
BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random),
|
||||
BrushKind::Scatter(s) => s.modes().contains(&Variation::Random),
|
||||
BrushKind::Bristle(_) => true,
|
||||
BrushKind::Art(_) | BrushKind::Pattern(_) => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])?
|
||||
fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool {
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b));
|
||||
let random = |st: &vectorcraft_doc::appearance::StrokeLayer| {
|
||||
st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options))
|
||||
};
|
||||
matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st)))
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
|
||||
pub(crate) use psdlayers::import_active as psd_layers;
|
||||
pub use psdlayers::{PsdInfo, info as psd_info};
|
||||
pub(crate) use psdslices::over as psd_slices;
|
||||
@@ -133,7 +133,7 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub(crate) use access::{check_images_in, check_scripts_of};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
|
||||
@@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
/// The error for a file that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in
|
||||
/// force and the file would name a linked image's file outside them (a relative path taken from
|
||||
/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it
|
||||
/// carries the native document ([`check_native_images`]). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
@@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(format, "svg" | "svgz") {
|
||||
return check_native_images(cmd, format, d, base, p);
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
|
||||
// layers kept and SVG 1.1: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
|
||||
@@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `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
|
||||
/// [`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
|
||||
/// read). The error names no file or folder.
|
||||
pub(crate) fn check_native_images(
|
||||
cmd: &str,
|
||||
format: &str,
|
||||
d: &vectorcraft_doc::Document,
|
||||
base: crate::cmd::links::LinkBase,
|
||||
p: &Value,
|
||||
) -> Result<()> {
|
||||
let carried =
|
||||
crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len());
|
||||
if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// `doc` as a file written for the request being served carries it: without an Export for Screens
|
||||
/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The
|
||||
/// open document keeps it.
|
||||
pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return std::borrow::Cow::Borrowed(doc);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
std::borrow::Cow::Owned(kept)
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
vec![(Some(b), rect(b)?, false)]
|
||||
}
|
||||
};
|
||||
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
|
||||
let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for (board, region, crop) in drawings {
|
||||
let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?;
|
||||
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
|
||||
enc.files.push((board, out.bytes));
|
||||
for w in out.warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
|
||||
@@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result<Raster> {
|
||||
}
|
||||
|
||||
/// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of
|
||||
/// several artboards), with linked images whole when `include_linked`.
|
||||
/// several artboards), with linked images whole when `include_linked`, and without an Export for
|
||||
/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]).
|
||||
fn native(doc: &Document, board: Option<usize>, include_linked: bool) -> Vec<u8> {
|
||||
let doc = &*super::access::with_readable_settings_folder(doc);
|
||||
let several = board.filter(|_| doc.artboards.len() > 1);
|
||||
if several.is_none() && !include_linked {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
|
||||
@@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'stati
|
||||
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
|
||||
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
|
||||
/// match the default filter) still list `.ase` and the other library extensions; then the same
|
||||
/// filters as [`builtin_open_filters`], without a second copy of the library filter, so a document
|
||||
/// filters as [`builtin_open_filters`], without a second filter of that label, so a document
|
||||
/// can be picked for its swatches or graphic styles.
|
||||
pub fn library_open_filters(
|
||||
library_label: &'static str,
|
||||
library_exts: &'static [&'static str],
|
||||
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts)))
|
||||
std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label))
|
||||
}
|
||||
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
|
||||
@@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
let rects = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
|
||||
let flat = crate::flatten_raster_effects(doc);
|
||||
let src = flat.as_ref().unwrap_or(doc);
|
||||
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for b in boards {
|
||||
let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect;
|
||||
let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?;
|
||||
for (b, out) in boards.into_iter().zip(outs) {
|
||||
enc.files.push((Some(b), out.bytes));
|
||||
for w in out.warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
|
||||
@@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
so.pretty = so.pretty_fits(&native);
|
||||
vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
@@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result<V
|
||||
} else {
|
||||
Cow::Borrowed(doc)
|
||||
};
|
||||
// Without an Export for Screens folder outside the read roots.
|
||||
let native = super::access::with_readable_settings_folder(&native);
|
||||
vectorcraft_format::save_with(&native, so).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
@@ -338,7 +338,9 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i
|
||||
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(doc);
|
||||
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
|
||||
// The editing data leaves out an Export for Screens folder outside the read roots.
|
||||
let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false));
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?;
|
||||
notes.extend(drawn);
|
||||
if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None {
|
||||
for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) {
|
||||
@@ -504,6 +506,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &*expanded;
|
||||
let st = s.doc()?;
|
||||
super::check_linked_scripts(C, "pdf", st, p)?;
|
||||
super::check_linked_images(C, "pdf", st, &st.doc, p)?;
|
||||
let display_doc_title = super::has_own_title(&st.doc);
|
||||
let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf");
|
||||
let mut q = p.clone();
|
||||
|
||||
@@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
|
||||
/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password
|
||||
/// and `textAs` are checked apart ([`linked_pages`]).
|
||||
pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
|
||||
bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes)
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
|
||||
@@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// Other formats are checked below, with the options the encoder reads.
|
||||
if is_svg(plan.format) {
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
}
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -941,6 +944,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
_ => std::borrow::Cow::Borrowed(¶ms),
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
}
|
||||
|
||||
|
||||
@@ -1129,6 +1129,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
|
||||
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
|
||||
}
|
||||
|
||||
/// The document the file of `item` that row `r` writes carries when it carries one
|
||||
/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a
|
||||
/// native, `.ai` or EPS row ([`board_document`]), else the item's document.
|
||||
fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> {
|
||||
match (&item.every_artboard, r.format.id, single) {
|
||||
(Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all),
|
||||
_ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)),
|
||||
_ => std::borrow::Cow::Borrowed(&*item.doc),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with
|
||||
/// its background color and the art on it, as Save's separateArtboards writes it (#3868).
|
||||
fn board_document(item: &Item) -> Document {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
d
|
||||
}
|
||||
|
||||
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
@@ -1177,6 +1199,23 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// The native document the files of the other rows carry, each document looked through once.
|
||||
if crate::file_access::current().is_some() {
|
||||
let mut looked: HashSet<(usize, bool, Option<usize>)> = HashSet::new();
|
||||
for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) {
|
||||
// A single-file PDF carries the first item's document alone, as the writer writes it.
|
||||
let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0));
|
||||
for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) {
|
||||
let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none();
|
||||
let board = item.artboard.filter(|_| !all && r.whole_document());
|
||||
if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board))
|
||||
&& crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base)
|
||||
{
|
||||
return Err(bad(C, super::access::IMAGE_OUTSIDE));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
@@ -1318,8 +1357,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
// A whole-document copy of an artboard, for the formats that write documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<usize, Arc<Document>> = std::collections::HashMap::new();
|
||||
// A whole-document copy of an artboard of an item's document, for the formats that write
|
||||
// documents to edit.
|
||||
let mut board_docs: std::collections::HashMap<(usize, usize), Arc<Document>> = std::collections::HashMap::new();
|
||||
let mut files = 0u64;
|
||||
// One step per item and row, the files a name collision skips included.
|
||||
let steps = (items.len() * rows.len()) as u64;
|
||||
@@ -1358,19 +1398,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
write(pdf_doc.unwrap_or(all), "pdf", &options)?
|
||||
} else if r.whole_document() && item.artboard.is_some() {
|
||||
let b = item.artboard.unwrap_or(0);
|
||||
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
|
||||
let d = board_docs
|
||||
.entry(b)
|
||||
.or_insert_with(|| {
|
||||
let mut d = single_artboard(&item.doc, item.region, &item.name);
|
||||
// It keeps its background color.
|
||||
if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) {
|
||||
a.color = from.color;
|
||||
}
|
||||
super::save::keep_art_on(&mut d, item.region);
|
||||
Arc::new(d)
|
||||
})
|
||||
.clone();
|
||||
let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone();
|
||||
let mut options = r.options_for(item.region, None)?;
|
||||
// An EPS page is the artboard, not its art's bounds: an artboard without art still writes.
|
||||
if r.format.id == "eps" {
|
||||
|
||||
@@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
|
||||
@@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load
|
||||
/// as a library, and it is the only filter of that label.
|
||||
#[test]
|
||||
fn the_swatch_library_filter_lists_ai_and_eps_files() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect();
|
||||
for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] {
|
||||
assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]);
|
||||
}
|
||||
assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}");
|
||||
// File › Open still opens a `.ai` as a document, not as a swatch library.
|
||||
assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai"));
|
||||
}
|
||||
|
||||
/// The extensions usage texts list for export: one per writable format, each picking that format
|
||||
/// (`.png` picks PNG; PNG-8 is asked for by `format`).
|
||||
#[test]
|
||||
|
||||
@@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
|
||||
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
|
||||
}
|
||||
|
||||
/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the
|
||||
/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with
|
||||
/// `square` (a color operator), a color the palette doesn't list.
|
||||
fn textures_library(square: &str) -> Vec<u8> {
|
||||
let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n");
|
||||
let gradient =
|
||||
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
|
||||
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\
|
||||
1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n";
|
||||
let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}"));
|
||||
ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")
|
||||
}
|
||||
|
||||
/// `swatch.library.load` of `file` named `name` → its library id.
|
||||
fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value {
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name});
|
||||
s.execute("swatch.library.load", &p).unwrap()["library"].clone()
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its
|
||||
/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's
|
||||
/// tile and art in the document, in the library's color group, not the pattern's colors.
|
||||
#[test]
|
||||
fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let kinds: Vec<(&str, &str, Option<&str>)> =
|
||||
lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect();
|
||||
assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}");
|
||||
assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}");
|
||||
// The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own.
|
||||
let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap();
|
||||
let tiles = library.iter().find(|w| w.name == "Tiles").unwrap();
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some()));
|
||||
assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none());
|
||||
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap();
|
||||
assert_eq!(r["added"], json!(["Tiles"]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let dots = doc.pattern("Dots").expect("the pattern comes with its swatch");
|
||||
assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0));
|
||||
assert_eq!(dots.art.len(), 1, "{:?}", dots.art);
|
||||
let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too");
|
||||
let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect();
|
||||
assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}");
|
||||
// Added again, the swatch the document has is used.
|
||||
let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list
|
||||
/// still comes in with that color in its art.
|
||||
#[test]
|
||||
fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() {
|
||||
let mut s = Session::new();
|
||||
let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k"));
|
||||
let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap();
|
||||
let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let art = &doc.pattern("Dots").unwrap().art;
|
||||
let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color());
|
||||
assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}");
|
||||
// Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is
|
||||
// refused, writes nothing and leaves the library loaded.
|
||||
let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id()));
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string();
|
||||
assert!(e.contains("`textures` has pattern swatches"), "{e}");
|
||||
assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written");
|
||||
assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok());
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as
|
||||
/// swatch libraries with a message, not listed as the default swatches or as an empty library. A
|
||||
/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file
|
||||
/// with no swatches loads as an empty library.
|
||||
#[test]
|
||||
fn swatch_library_documents_without_swatches_or_damaged_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.edit("Clear", |d, _| {
|
||||
d.swatches.clear();
|
||||
d.swatch_groups.clear();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
||||
let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0))));
|
||||
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"});
|
||||
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`art.ai` has no swatches of its own"), "{e}");
|
||||
let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"});
|
||||
assert!(s.execute("swatch.library.load", &damaged).is_err());
|
||||
let list = s.execute("swatch.library.list", &json!({})).unwrap();
|
||||
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}");
|
||||
// A library file without swatches still loads, as an empty library.
|
||||
let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap();
|
||||
assert_eq!(r["count"], json!(0), "{r}");
|
||||
}
|
||||
|
||||
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
|
||||
/// library the styles of its list, in the list's order, not the default styles; the file opens with
|
||||
/// them too.
|
||||
|
||||
@@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() {
|
||||
assert!(e.contains("useArtboards"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() {
|
||||
let mut s = two_boards();
|
||||
// A second rectangle on the second artboard, so the two drawings differ.
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let o = dxf::options(&json!({"unit": "pt"})).unwrap();
|
||||
assert_eq!(files.len(), doc.artboards.len());
|
||||
assert_ne!(b64(&files[0]), b64(&files[1]));
|
||||
for (f, board) in files.iter().zip(&doc.artboards) {
|
||||
let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap();
|
||||
assert_eq!(b64(f), alone.bytes, "{}", f["name"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_only_exports_the_selection_in_its_layers() {
|
||||
let mut s = two_boards();
|
||||
|
||||
@@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() {
|
||||
assert!(open(&mut s, &two, json!({"pages": "1"})).is_err());
|
||||
open(&mut s, &two, json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// `linkPages` takes a PDF up to the largest file placed, and nothing else.
|
||||
#[test]
|
||||
fn pages_can_link_a_pdf_up_to_the_largest_file_placed() {
|
||||
let small = three_pages();
|
||||
assert!(pages_can_link("pages.pdf", &small));
|
||||
assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
|
||||
let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1];
|
||||
big[..small.len()].copy_from_slice(&small);
|
||||
assert!(!pages_can_link("pages.pdf", &big), "over the limit");
|
||||
big.pop();
|
||||
assert!(pages_can_link("pages.pdf", &big), "at the limit");
|
||||
}
|
||||
@@ -1461,3 +1461,25 @@ fn an_export_preset_adds_no_notes() {
|
||||
let r = export(&mut s, json!({"exportPreset": "Mixed"}));
|
||||
assert!(unused(&r).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art:
|
||||
/// every piece's file holds its own artboard, named after it, not the first piece's.
|
||||
#[test]
|
||||
fn each_piece_writes_its_own_native_document() {
|
||||
let mut s = session(1);
|
||||
s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let ids: Vec<u64> = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
let mut assets = vec![];
|
||||
for (id, name) in ids.iter().zip(["Square", "Circle"]) {
|
||||
assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap());
|
||||
}
|
||||
let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]}));
|
||||
let written = files(&r);
|
||||
assert_eq!(written.len(), 4, "{r}");
|
||||
for (name, bytes) in written {
|
||||
let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes };
|
||||
let doc = vectorcraft_format::load(&native).unwrap();
|
||||
let board = doc.artboards[0].name.clone();
|
||||
assert!(name.contains(&board), "{name} holds the artboard {board}");
|
||||
}
|
||||
}
|
||||
@@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
arrow_scale,
|
||||
profile,
|
||||
brush,
|
||||
brush_options,
|
||||
opacity,
|
||||
blend,
|
||||
visible,
|
||||
@@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
bearing: _,
|
||||
rotation: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
|
||||
if a.brush != b.brush {
|
||||
n.brush_options = brush_options.clone();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, to_csv};
|
||||
pub use edit::{GraphTypeSubject, graph_type_subject};
|
||||
|
||||
@@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String {
|
||||
g.to_csv()
|
||||
}
|
||||
|
||||
// ---------- graph data files ----------
|
||||
|
||||
/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns
|
||||
/// read, 1 MB (1,048,576 bytes).
|
||||
pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20;
|
||||
|
||||
/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels
|
||||
/// before its series; a cell's longest text.
|
||||
const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1;
|
||||
const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1;
|
||||
const SHEET_CELL: usize = 256;
|
||||
|
||||
/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode
|
||||
/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives
|
||||
/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one.
|
||||
/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired
|
||||
/// surrogate reads as U+FFFD.
|
||||
pub fn graph_data_text(bytes: &[u8]) -> String {
|
||||
let utf16 = |rest: &[u8], le: bool| {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
};
|
||||
match bytes {
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
|
||||
_ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() {
|
||||
Some(le) => utf16(bytes, le),
|
||||
None => String::from_utf8_lossy(bytes).into_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256
|
||||
/// characters.
|
||||
pub fn graph_cell_text(s: &str) -> String {
|
||||
s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect()
|
||||
}
|
||||
|
||||
/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds
|
||||
/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file
|
||||
/// stays whole), at most a graph's rows and columns.
|
||||
pub fn graph_grid_from_text(text: &str) -> Vec<Vec<String>> {
|
||||
let sep = if text.contains('\t') { '\t' } else { ',' };
|
||||
text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect()
|
||||
}
|
||||
|
||||
/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the
|
||||
/// first column the category labels (none when all are blank), and the other cells the values (a
|
||||
/// blank cell, or text that isn't a number, has none), without the empty rows and columns past
|
||||
/// the data.
|
||||
pub fn graph_data_from_grid(grid: &[Vec<String>]) -> Value {
|
||||
let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default();
|
||||
let filled = |s: &String| !s.trim().is_empty();
|
||||
// At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by
|
||||
// automation is any size, and the values are their product.
|
||||
let grid = &grid[..grid.len().min(SHEET_ROWS)];
|
||||
let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1);
|
||||
let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1);
|
||||
let label = |s: &str| {
|
||||
let s = s.trim();
|
||||
// A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside.
|
||||
s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string()
|
||||
};
|
||||
// Series labels up to the last one given (none when all are blank).
|
||||
let mut series: Vec<String> = (1..cols).map(|c| label(&cell(0, c))).collect();
|
||||
while series.last().is_some_and(String::is_empty) {
|
||||
series.pop();
|
||||
}
|
||||
let mut categories: Vec<String> = (1..rows).map(|r| label(&cell(r, 0))).collect();
|
||||
if categories.iter().all(String::is_empty) {
|
||||
categories.clear();
|
||||
}
|
||||
let values: Vec<Vec<Value>> = (1..rows)
|
||||
.map(|r| {
|
||||
(1..cols)
|
||||
.map(|c| {
|
||||
let t = cell(r, c);
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
json!({ "series": series, "categories": categories, "rows": values })
|
||||
}
|
||||
|
||||
/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph
|
||||
/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the
|
||||
/// value gives a graph the data that Import Data and Apply give it.
|
||||
pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result<String> {
|
||||
let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes)));
|
||||
let mut spec = GraphSpec::default();
|
||||
apply_data(&mut spec, &data, "dataset.import")?;
|
||||
Ok(spec.to_csv())
|
||||
}
|
||||
|
||||
/// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with
|
||||
/// `csv` does. Data the graph already holds leaves the graph as it is.
|
||||
pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
@@ -149,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool
|
||||
if let Some(csv) = csv {
|
||||
let (s, c, r) = parse_csv(csv);
|
||||
g.series = s;
|
||||
// Series labels up to the last one given, as Graph Data's sheet keeps them
|
||||
// ([`graph_data_from_grid`]): `to_csv` writes a blank label for each series without one.
|
||||
while g.series.last().is_some_and(String::is_empty) {
|
||||
g.series.pop();
|
||||
}
|
||||
g.categories = c;
|
||||
g.set_cells(r);
|
||||
changed = true;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::text::INLINE_MAX_SCALE;
|
||||
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::brushsym::current_symbol;
|
||||
@@ -25,12 +25,33 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
|
||||
/// resolve the inline art of every text again, in the layers and in the art of symbols, graph
|
||||
/// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a
|
||||
/// symbol's type before the type that shows that symbol inline).
|
||||
pub(crate) fn refresh(before: &Document, d: &mut Document) {
|
||||
/// symbol's type before the type that shows that symbol inline). `last` is the document the last
|
||||
/// refresh left resolved, with what it measured: when nothing the inline art depends on changed
|
||||
/// since, only the layer trees that differ from its own are checked
|
||||
/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when
|
||||
/// neither document has symbols and nothing was checked.
|
||||
pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> {
|
||||
if before.symbols.is_empty() && d.symbols.is_empty() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
d.resolve_inline_art_with(&mut refresh_bounds);
|
||||
#[cfg(test)]
|
||||
let last = last.filter(|_| !FULL_PASS.get());
|
||||
let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds);
|
||||
#[cfg(test)]
|
||||
PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone())));
|
||||
Some(pass.measured)
|
||||
}
|
||||
|
||||
/// A document a [`refresh`] left resolved, and what that refresh measured.
|
||||
pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured);
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Each [`refresh`] on this thread that checked the document: whether it checked only the
|
||||
/// changed layer trees, and the ids of the texts in the layers that changed.
|
||||
pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) };
|
||||
/// Set: every [`refresh`] on this thread takes the full pass.
|
||||
pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -47,18 +68,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let from_tool = editing == Some(id);
|
||||
let (a, b) = match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
// Where the graphic goes in text `len` bytes long.
|
||||
let range = |len: usize| -> Result<(usize, usize)> {
|
||||
Ok(match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
})
|
||||
};
|
||||
let (mut a, mut b) = range(len)?;
|
||||
let symbol = match str_param(p, "symbol") {
|
||||
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
|
||||
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
|
||||
@@ -76,11 +101,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
|
||||
};
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
// A typing session ends first: the insertion is a step of its own. Typing that Real-time
|
||||
// Drawing off left unapplied is applied first, and the caret is read in the typed text.
|
||||
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
|
||||
if typing && from_tool {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::settle_interaction(s)?;
|
||||
let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
|
||||
return Err(bad(C, format!("node {} is not text", id.0)));
|
||||
};
|
||||
(a, b) = range(edit::runs_len(&t.runs))?;
|
||||
}
|
||||
let caret = s.edit("Insert Inline Symbol", |d, _| {
|
||||
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Rows",
|
||||
[],
|
||||
None,
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
has_doc,
|
||||
move_rows
|
||||
),
|
||||
@@ -774,9 +774,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no such rows"));
|
||||
}
|
||||
// Never into itself or a row inside it.
|
||||
// Never into itself or a row inside it. A copy may go above or below one of the rows it
|
||||
// copies, which a move there would leave where it is (#8237).
|
||||
let beside_itself = copy && place != Place::Inside && ids.contains(&target);
|
||||
let around = d.ancestry(target).unwrap_or_default();
|
||||
if ids.iter().any(|i| around.contains(i)) {
|
||||
if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) {
|
||||
return Err(bad(C, "a row can't go into itself"));
|
||||
}
|
||||
let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect();
|
||||
@@ -788,6 +790,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
parent => (parent, Some(target)),
|
||||
},
|
||||
};
|
||||
// A copy beside a top-level layer it copies, with objects among the rows, would go inside
|
||||
// that layer: into itself.
|
||||
if parent.is_some_and(|p| ids.contains(&p)) {
|
||||
return Err(bad(C, "a row can't go into itself"));
|
||||
}
|
||||
if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) {
|
||||
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
|
||||
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
|
||||
|
||||
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Locate Object",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}",
|
||||
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
|
||||
has_doc,
|
||||
locate
|
||||
),
|
||||
@@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "layer.locate")?;
|
||||
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
|
||||
let st = s.doc_mut()?;
|
||||
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![id];
|
||||
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
if layers_only {
|
||||
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
|
||||
let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?;
|
||||
ancestry.truncate(at + 1);
|
||||
}
|
||||
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![row];
|
||||
st.locate_reveal = Some(row);
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
|
||||
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
|
||||
}
|
||||
@@ -36,7 +36,7 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unembed",
|
||||
[],
|
||||
None,
|
||||
"{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)",
|
||||
"{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors",
|
||||
has_doc,
|
||||
unembed
|
||||
),
|
||||
@@ -2686,11 +2686,35 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
|
||||
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't
|
||||
/// name).
|
||||
fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str {
|
||||
fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"))
|
||||
}
|
||||
|
||||
/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is
|
||||
/// stored in that format, else converted.
|
||||
fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime);
|
||||
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
|
||||
}
|
||||
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
|
||||
// `id` with `ids`, and `path` with `folder`, are refused, in a replayed step too.
|
||||
super::params::check_exclusive_keys(C, p)?;
|
||||
let ids = ids_param(p, "ids", C)?;
|
||||
if given("folder") || ids.as_ref().is_some_and(|ids| ids.len() != 1) {
|
||||
return unembed_to_folder(s, p, ids);
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let id = image_param(st, &doc, p, C)?;
|
||||
// `ids` of one image is `id`.
|
||||
let id = match ids.as_deref() {
|
||||
Some(&[id]) => id,
|
||||
_ => image_param(st, &doc, p, C)?,
|
||||
};
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
@@ -2698,15 +2722,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
|
||||
let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png"));
|
||||
let stored = stored_extension(blob);
|
||||
let path = str_param(p, "path");
|
||||
let ext = match path.map(fileio::extension) {
|
||||
Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e,
|
||||
Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))),
|
||||
_ => stored.to_string(),
|
||||
};
|
||||
let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime);
|
||||
let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? };
|
||||
let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?;
|
||||
let Some(path) = path else {
|
||||
let name = n.display_name();
|
||||
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
|
||||
@@ -2722,6 +2745,146 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
/// `links.unembed {ids?, folder}`: each embedded image of `ids` (`id` as `ids` of one; default: the
|
||||
/// selected embedded images) written to a new file in `folder` as stored (as PNG when that format is not one of
|
||||
/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it
|
||||
/// are removed and the document does not change.
|
||||
fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?;
|
||||
let ids = match ids {
|
||||
Some(ids) => Some(ids),
|
||||
None => object_param(p, "id", C)?.map(|id| vec![id]),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let ids = ids.unwrap_or_else(|| selected_images(st, |im| im.link.is_none()));
|
||||
let mut seen = BTreeSet::new();
|
||||
if !ids.iter().all(|id| seen.insert(id.0)) {
|
||||
return Err(bad(C, "`ids` names an object twice"));
|
||||
}
|
||||
let (mut embedded, mut skipped) = (vec![], vec![]);
|
||||
for &id in &ids {
|
||||
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
|
||||
embedded.push((id, n.display_name(), blob));
|
||||
}
|
||||
match (embedded.is_empty(), skipped.first()) {
|
||||
(true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))),
|
||||
(true, None) => return Err(bad(C, "select an image")),
|
||||
_ => {}
|
||||
}
|
||||
let dir = absolute_path(folder);
|
||||
writable_folder(&dir)?;
|
||||
// One image at a time: its bytes are read before its file is written, so pixels that can't be
|
||||
// read leave no file behind.
|
||||
let mut written: Vec<String> = vec![];
|
||||
let mut reads = Vec::with_capacity(embedded.len());
|
||||
let wrote = embedded.iter().try_for_each(|(id, name, blob)| {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let ext = stored_extension(blob);
|
||||
let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?;
|
||||
let name = format!("{}.{ext}", unembed_stem(name));
|
||||
let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?;
|
||||
let path = write_numbered(&dir, &name, &bytes)?;
|
||||
written.push(path.clone());
|
||||
reads.push((*id, (link_info(&path, &bytes), img)));
|
||||
Ok(())
|
||||
});
|
||||
let remove_written = |written: &[String]| {
|
||||
for path in written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
};
|
||||
if let Err(e) = wrote {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None)))
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) }))
|
||||
}
|
||||
|
||||
/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without
|
||||
/// a folder part or extension, each character a file name can't hold on some system
|
||||
/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and
|
||||
/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a
|
||||
/// device (`CON`, `NUL`, `COM1` …) gets `_` after it.
|
||||
fn unembed_stem(name: &str) -> String {
|
||||
let base = name.rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
let stem = match base.rfind('.') {
|
||||
Some(i) if i > 0 => &base[..i],
|
||||
_ => base,
|
||||
};
|
||||
let mut clean = String::new();
|
||||
for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) {
|
||||
if clean.len() + c.len_utf8() > 150 {
|
||||
break;
|
||||
}
|
||||
clean.push(c);
|
||||
}
|
||||
let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']);
|
||||
if clean.is_empty() {
|
||||
return "Image".to_string();
|
||||
}
|
||||
let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase();
|
||||
let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9')));
|
||||
if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") {
|
||||
format!("{clean}_")
|
||||
} else {
|
||||
clean.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn writable_folder(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)?;
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) {
|
||||
return Err(EngineError::Other(format!("{path} is not a folder")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`,
|
||||
/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result<String> {
|
||||
use std::io::Write as _;
|
||||
let create = |to: &Path| {
|
||||
crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?;
|
||||
vectorcraft_format::write_new_with(to, |f| f.write_all(bytes))
|
||||
};
|
||||
match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) {
|
||||
Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()),
|
||||
Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))),
|
||||
Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The web has no folders to write to.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn writable_folder(_: &str) -> Result<()> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result<String> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
/// Placement Options as `{preserve, align, clip}`.
|
||||
fn placement_json(o: PlacementOptions) -> Value {
|
||||
json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip })
|
||||
@@ -2901,4 +3064,28 @@ mod tests {
|
||||
let c = read();
|
||||
assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() {
|
||||
for (name, stem) in [
|
||||
("photo.png", "photo"),
|
||||
("Image", "Image"),
|
||||
("../../etc/passwd", "passwd"),
|
||||
("C:\\art\\logo.tif", "logo"),
|
||||
("a:b*c?d\"e<f>g|h", "a_b_c_d_e_f_g_h"),
|
||||
("tab\there", "tab_here"),
|
||||
(" name. .png", "name"),
|
||||
("..", "Image"),
|
||||
("", "Image"),
|
||||
(".hidden", ".hidden"),
|
||||
("CON.png", "CON_"),
|
||||
("lpt1", "lpt1_"),
|
||||
("COM0", "COM0"),
|
||||
("console", "console"),
|
||||
] {
|
||||
assert_eq!(unembed_stem(name), stem, "{name:?}");
|
||||
}
|
||||
let long = unembed_stem(&"é".repeat(200));
|
||||
assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
|
||||
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
|
||||
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
|
||||
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
|
||||
|
||||
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
|
||||
has_selection, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
|
||||
has_selected_member, has_selection, switch_or,
|
||||
};
|
||||
|
||||
/// Session-level (not saved) state owned by the menu commands.
|
||||
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
reset_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rotateBoundingBox",
|
||||
"Rotate Bounding Box…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
|
||||
has_selection,
|
||||
rotate_bounding_box
|
||||
),
|
||||
cmd!(
|
||||
"object.rasterize",
|
||||
"Rasterize…",
|
||||
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
|
||||
// ---------- Reset Bounding Box ----------
|
||||
|
||||
/// Squares each selected object and every object inside it: the children of groups, compound paths,
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
|
||||
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
|
||||
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let mut changed = 0;
|
||||
let squared: Vec<(NodeId, Node)> = ids
|
||||
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
// ---------- Rotate Bounding Box ----------
|
||||
|
||||
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
|
||||
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
|
||||
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
|
||||
/// groups and the art of linked opacity masks), which keep their angle relative to it.
|
||||
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.rotateBoundingBox";
|
||||
// A JSON number is always finite.
|
||||
let angle = f64_req(p, "angle", C)?;
|
||||
let absolute = switch_or(p, "absolute", false, C)?;
|
||||
// The same objects the transforms move: a path of a compound path selected on its own turns
|
||||
// its own box. Layers are left out, as they have no box.
|
||||
let owners = selected_roots_to_transform(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
|
||||
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
|
||||
let target = match vectorcraft_geom::normalize_deg(start + angle) {
|
||||
a if a.abs() <= BOX_EPS_DEG => 0.0,
|
||||
a => a,
|
||||
};
|
||||
let mut changed = 0;
|
||||
let turned: Vec<(NodeId, Node)> = owners
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let n = d.node(*id)?;
|
||||
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
|
||||
(by.abs() > BOX_EPS_DEG).then(|| {
|
||||
let mut c = n.clone();
|
||||
c.turn_boxes(by);
|
||||
// The selected object's box is set to the target itself, so repeated turns add no
|
||||
// rounding error to it.
|
||||
c.bbox_angle = target;
|
||||
changed += boxes(&c);
|
||||
(*id, c)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !turned.is_empty() {
|
||||
s.edit("Rotate Bounding Box", |d, _| {
|
||||
for (id, n) in turned {
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = n;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "angle": target, "changed": changed }))
|
||||
}
|
||||
|
||||
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
|
||||
const BOX_EPS_DEG: f64 = 1e-6;
|
||||
|
||||
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
|
||||
/// and the art of a linked opacity mask, layers left out.
|
||||
fn boxes(n: &Node) -> usize {
|
||||
let own = usize::from(!n.is_layer());
|
||||
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
|
||||
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
|
||||
own + children + mask
|
||||
}
|
||||
|
||||
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
|
||||
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
|
||||
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
//!
|
||||
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
|
||||
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
|
||||
//! resets new art when it opens such a document.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_tools::PaintDefaults;
|
||||
|
||||
use super::gradient::unplaced;
|
||||
@@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template.
|
||||
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template;
|
||||
/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects
|
||||
/// at full opacity, not linked to the style.
|
||||
pub(crate) fn reset(s: &mut Session) {
|
||||
s.paint = PaintDefaults::default();
|
||||
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
|
||||
if let Some(g) = style {
|
||||
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
|
||||
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the
|
||||
/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode
|
||||
/// as a New Document profile's are.
|
||||
pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> {
|
||||
let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?;
|
||||
let same =
|
||||
|o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout);
|
||||
if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) {
|
||||
return None;
|
||||
}
|
||||
if d.color_mode != ColorMode::Rgb {
|
||||
let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb);
|
||||
shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE);
|
||||
super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile);
|
||||
if shipped.graphic_styles.first().is_some_and(same) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(g)
|
||||
}
|
||||
@@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The profile's links keep their relative paths, which name places from the profile's file, as
|
||||
// a new document from a history state keeps its source's.
|
||||
s.doc_mut()?.links_from = links_from;
|
||||
// A profile whose Default Graphic Style was redefined gives new art in the document that style.
|
||||
if super::newart::redefined_default_style(&s.doc()?.doc).is_some() {
|
||||
super::newart::reset(s);
|
||||
}
|
||||
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
|
||||
// are views of the whole app, so Default leaves them as they are.
|
||||
if settings.preview_mode == PreviewMode::Overprint {
|
||||
|
||||
@@ -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)} (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)",
|
||||
"{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)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::{
|
||||
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
|
||||
convert_radii_relative, ok, selected_roots, set_corners, targets,
|
||||
};
|
||||
use crate::MAX_COORD;
|
||||
|
||||
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
|
||||
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
|
||||
@@ -98,6 +99,30 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
|
||||
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
|
||||
let now = l.line_length()?;
|
||||
let mut new = l.clone();
|
||||
let mut changed = false;
|
||||
if let Some(len) = len
|
||||
&& (len - now).abs() > 1e-9 * len.max(now)
|
||||
{
|
||||
new.set_line_length(len);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(a) = angle
|
||||
&& new.line_length().is_some_and(|n| n > 0.0)
|
||||
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
|
||||
&& turn > 1e-9
|
||||
&& turn < 360.0 - 1e-9
|
||||
{
|
||||
new.set_line_angle(a);
|
||||
changed = true;
|
||||
}
|
||||
(changed && new != *l).then_some(new)
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
@@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
|
||||
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
|
||||
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
|
||||
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
|
||||
@@ -171,6 +196,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 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);
|
||||
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
|
||||
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
|
||||
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
|
||||
let line_angle = angle("lineAngle")?;
|
||||
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
|
||||
// ellipse as 0° to 360°).
|
||||
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
|
||||
@@ -181,8 +210,26 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
// are.
|
||||
let st = s.doc()?;
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
if line_length.is_some() || line_angle.is_some() {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
|
||||
if let Some(new) = line_edit(l, line_length, line_angle) {
|
||||
let LiveShape::Line { a, b } = &new else { continue };
|
||||
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
|
||||
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
lines.insert(*id, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
let has_values = |id: &NodeId| {
|
||||
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
|
||||
if lines.contains_key(id) {
|
||||
return false;
|
||||
}
|
||||
match live.as_deref() {
|
||||
Some(l @ LiveShape::Polygon { sides: now, .. })
|
||||
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
|
||||
@@ -244,6 +291,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(new) = lines.get(id)
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
*l = new.clone();
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(on) = relative_radii
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
|
||||
@@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy with an Export for Screens folder outside
|
||||
/// the read roots in the native document it is or carries.
|
||||
const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when
|
||||
/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder
|
||||
/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not
|
||||
/// rewritten, would name it. The error names no file or folder.
|
||||
fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
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)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
@@ -363,6 +381,7 @@ impl<'a> Collector<'a> {
|
||||
options.profiles = saved.profiles;
|
||||
options.compress = compressed;
|
||||
options.include_linked = include_linked;
|
||||
let nested = super::fileio::with_readable_settings_folder(&nested);
|
||||
match vectorcraft_format::save_with(&nested, &options) {
|
||||
Ok(rewritten) => bytes = rewritten,
|
||||
Err(e) => self.warn(
|
||||
@@ -381,6 +400,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
check_carried_folder(&file.name, &bytes)?;
|
||||
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
|
||||
self.copies.insert(found_path.to_string(), copy.clone());
|
||||
local.insert(file.path.clone(), copy);
|
||||
@@ -520,7 +540,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
}
|
||||
let root = folder.map(|f| Path::new(f).join(&name));
|
||||
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
|
||||
// The package's document leaves out an Export for Screens folder outside the read roots.
|
||||
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 })
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a 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 on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -1035,6 +1035,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
|
||||
let style = super::newart::redefined_default_style(&before).cloned();
|
||||
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
|
||||
for id in &ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
@@ -1045,7 +1047,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.style.stroke = Paint::None;
|
||||
}
|
||||
}
|
||||
_ => n.appearance = Appearance::default_art().into(),
|
||||
_ => {
|
||||
n.appearance = match &style {
|
||||
Some(g) => g.appearance_on(n).into_owned().into(),
|
||||
None => Appearance::default_art().into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
|
||||
|
||||
Loaded 100 of 492 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user