mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
Merge main into feat/object-mosaic-dialog
This commit is contained in:
@@ -128,11 +128,13 @@ 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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -70,8 +70,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"
|
||||
|
||||
|
||||
@@ -888,6 +888,8 @@ pub use pathops::shape_count;
|
||||
|
||||
/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them).
|
||||
pub use menucmds::mosaic_counts;
|
||||
/// The Shape Mode commands' warning when a selected open path encloses no area.
|
||||
pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
@@ -904,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,6 +14,7 @@ mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
@@ -35,5 +36,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v.extend(units::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
|
||||
@@ -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<()> {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -47,18 +47,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 +80,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()) };
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -258,11 +258,16 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
|
||||
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
|
||||
/// neither null, is a parameter error ([`check_exclusive_keys`]).
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
|
||||
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[
|
||||
("addon.pathtools.cornerSet", "items", "ids"),
|
||||
("addon.pathtools.cornerRemove", "items", "ids"),
|
||||
("links.unembed", "id", "ids"),
|
||||
("links.unembed", "path", "folder"),
|
||||
];
|
||||
|
||||
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
|
||||
/// error naming the pair.
|
||||
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
pub(crate) fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
|
||||
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
|
||||
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
|
||||
if given(key).is_some() && given(other).is_some() {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unite",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Unite)
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Front",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Intersect",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Intersect)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Exclude",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::Exclude)
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Minus Back",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result's shape (when such a path leaves the result empty, as in Intersect, the error says so)}",
|
||||
has_selection,
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
|
||||
),
|
||||
@@ -285,6 +285,37 @@ impl Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds
|
||||
/// a line or another open path that encloses no area once closed, and so does not change the result's
|
||||
/// shape (the result still takes its paint from the frontmost object, as without the warning).
|
||||
pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = "a line or other open path that encloses no area does not change the result's shape; to include it, apply Object › Path › Outline Stroke to it first";
|
||||
|
||||
/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd
|
||||
/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed
|
||||
/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it.
|
||||
fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool {
|
||||
path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| {
|
||||
// A point or a straight two-anchor line needs no area measurement.
|
||||
if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) {
|
||||
return true;
|
||||
}
|
||||
let mut closed = sp.clone();
|
||||
closed.closed = true;
|
||||
// The signed-area test alone only holds for nonzero: evenodd can fill nothing where the
|
||||
// signed area is not zero (a contour traced twice).
|
||||
!(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0
|
||||
})
|
||||
}
|
||||
|
||||
/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it.
|
||||
fn closed_area(path: &PathData, rule: FillRule) -> f64 {
|
||||
let mut closed = path.clone();
|
||||
for sp in &mut closed.subpaths {
|
||||
sp.closed = true;
|
||||
}
|
||||
po::area(&closed, rule)
|
||||
}
|
||||
|
||||
/// All subpaths of a path or compound path node, in document coordinates, with its fill rule.
|
||||
pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> {
|
||||
match &n.kind {
|
||||
@@ -685,8 +716,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
|
||||
let label = pf_label(op);
|
||||
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let (ids, no_area) = s.edit(label, |d, sel| {
|
||||
// Build the stack (back → front); names are separate from paint/style identity.
|
||||
let mut no_area = false;
|
||||
let mut styles: Vec<Style> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
let mut names: Vec<Option<String>> = vec![];
|
||||
@@ -759,6 +791,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
continue;
|
||||
};
|
||||
let top = *top;
|
||||
no_area = no_area || parts.iter().any(|(_, p, r)| has_open_subpath_without_area(p, *r));
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
|
||||
push(
|
||||
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
@@ -771,6 +804,7 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
} else {
|
||||
for (l, clip) in &lv {
|
||||
if let Some((p, r)) = node_path(l) {
|
||||
no_area = no_area || (shape_mode && has_open_subpath_without_area(&p, r));
|
||||
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
|
||||
}
|
||||
}
|
||||
@@ -798,6 +832,21 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if results.iter().all(|r| r.path.is_empty()) {
|
||||
// The lines left the result empty when the other shapes give a result without them, or
|
||||
// when nothing else is selected. A closed shape without area stays among the others.
|
||||
let lines_emptied = no_area && {
|
||||
let kept: Vec<po::Shape> = shapes
|
||||
.iter()
|
||||
.filter(|s| closed_area(&s.path, s.rule) > 0.0 || !has_open_subpath_without_area(&s.path, s.rule))
|
||||
.cloned()
|
||||
.collect();
|
||||
kept.is_empty() || po::pathfinder_with(op, &kept, options.precision).iter().any(|r| !r.path.is_empty())
|
||||
};
|
||||
if lines_emptied {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first"
|
||||
)));
|
||||
}
|
||||
return Err(EngineError::Other(format!("{label} produced an empty result")));
|
||||
}
|
||||
let new_node = if shape_mode {
|
||||
@@ -833,9 +882,13 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
};
|
||||
let nid = d.wrap(&roots, |_| new_node)?;
|
||||
sel.set([nid]);
|
||||
Ok(vec![nid])
|
||||
Ok((vec![nid], no_area))
|
||||
})?;
|
||||
Ok(ids_json(&ids))
|
||||
let mut out = ids_json(&ids);
|
||||
if no_area {
|
||||
out["warning"] = json!(SHAPE_MODE_OPEN_PATH_NO_AREA);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Trap ----------
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::Result;
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::clipboard::resources::{Imported, SwatchChoices};
|
||||
use super::swatchlib::LibraryInfo;
|
||||
|
||||
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
|
||||
@@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
|
||||
|
||||
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
|
||||
/// painted with it does: the same pattern there already is used, and a name another pattern or
|
||||
/// swatch has gets a number → the pattern's name in `d`.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
|
||||
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
|
||||
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
|
||||
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
|
||||
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
|
||||
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
|
||||
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
|
||||
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
|
||||
let from = |to: &str| {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
|
||||
renamed.unwrap_or(to).to_string()
|
||||
};
|
||||
let added = d
|
||||
.swatches_iter()
|
||||
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
|
||||
.map(|w| (from(&w.name), w.name.clone()))
|
||||
.collect();
|
||||
Ok((imported_name(&imported, name), added))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
|
||||
fn gather(lib: &Document, name: &str) -> Clipboard {
|
||||
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
|
||||
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
|
||||
Clipboard::gather(lib, vec![user])
|
||||
}
|
||||
|
||||
/// The name pattern `name` has in the document `imported` went into.
|
||||
fn imported_name(imported: &Imported, name: &str) -> String {
|
||||
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
|
||||
Ok(renamed.unwrap_or(name).to_string())
|
||||
renamed.unwrap_or(name).to_string()
|
||||
}
|
||||
|
||||
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
|
||||
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
|
||||
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
|
||||
/// with, is imported into a copy of `d`, so that those resources are compared too.
|
||||
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
|
||||
let gathered = gather(lib, name);
|
||||
let only_pattern = gathered.patterns.len() == 1
|
||||
&& gathered.symbols.is_empty()
|
||||
&& gathered.swatches.is_empty()
|
||||
&& gathered.graphic_styles.is_empty()
|
||||
&& gathered.char_styles.is_empty()
|
||||
&& gathered.para_styles.is_empty()
|
||||
&& gathered.brushes.is_empty()
|
||||
&& gathered.images.is_empty();
|
||||
if only_pattern {
|
||||
return existing_pattern(d, lib, name);
|
||||
}
|
||||
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
|
||||
// options and as many art objects; without one, the document is not copied.
|
||||
let def = lib.pattern(name)?;
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let copy = |n: &str| {
|
||||
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
|
||||
return None;
|
||||
}
|
||||
let mut probe = d.clone();
|
||||
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
|
||||
(imported.added == 0).then(|| imported_name(&imported, name))
|
||||
}
|
||||
|
||||
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
|
||||
|
||||
@@ -84,6 +84,8 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.shapes.star",
|
||||
"addon.type.releasePath",
|
||||
"addon.type.textTweaker",
|
||||
"addon.units.convert",
|
||||
"addon.units.selectionSize",
|
||||
"appearance.addEffect",
|
||||
"appearance.addFill",
|
||||
"appearance.addStroke",
|
||||
@@ -124,6 +126,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"brush.list",
|
||||
"brush.move",
|
||||
"brush.new",
|
||||
"brush.objectOptions",
|
||||
"brush.options",
|
||||
"brush.placeArt",
|
||||
"brush.remove",
|
||||
@@ -366,6 +369,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"object.repeat.release",
|
||||
"object.resetBoundingBox",
|
||||
"object.rotate",
|
||||
"object.rotateBoundingBox",
|
||||
"object.scale",
|
||||
"object.setBounds",
|
||||
"object.setLiveShape",
|
||||
|
||||
@@ -368,6 +368,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool),
|
||||
p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool),
|
||||
p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)),
|
||||
// Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013).
|
||||
p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool),
|
||||
p!("historyStates", "Performance", "", "History States", int(5, 1000)),
|
||||
p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool),
|
||||
p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)),
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Array(cs)) => Some(cs),
|
||||
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
|
||||
};
|
||||
// A null in groupColors removes the group's swatch at its place.
|
||||
// A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch
|
||||
// at its place its color, without the Global Adjust.
|
||||
let own: Vec<Option<Color>> = match group {
|
||||
Some(g) => {
|
||||
s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default()
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
let new: Vec<Option<Color>> = match group_colors {
|
||||
Some(cs) => cs
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
.enumerate()
|
||||
.map(|(i, v)| match v {
|
||||
Value::Null => Ok(None),
|
||||
// Past the group's swatches it adds nothing.
|
||||
Value::String(k) if k == "keep" => match own.get(i) {
|
||||
Some(Some(c)) => Ok(Some(*c)),
|
||||
Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))),
|
||||
None => Ok(None),
|
||||
},
|
||||
v => color_value(v)
|
||||
.map(|c| adjust.apply(c))
|
||||
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -549,6 +549,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
|
||||
arrows_and_profile(st);
|
||||
if let Some(b) = &brush {
|
||||
// The path's own brush settings (Options of Selected Object) go with the brush they set.
|
||||
if st.brush != *b {
|
||||
st.brush_options.clear();
|
||||
}
|
||||
st.brush = b.clone();
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
has_doc,
|
||||
swatch_edit_group
|
||||
),
|
||||
@@ -1340,21 +1340,45 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Colo
|
||||
fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.editGroup";
|
||||
let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?;
|
||||
let colors: Vec<Color> = p
|
||||
// A null removes the swatch at that place.
|
||||
let colors: Vec<Option<Color>> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| bad(C, "missing `colors`"))?
|
||||
.iter()
|
||||
.map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}"))))
|
||||
.map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) })
|
||||
.collect::<Result<_>>()?;
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
// A color its swatch already has keeps its model. The others take the document's.
|
||||
// A color its swatch already has keeps its model. The others take the document's. A color key
|
||||
// (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color
|
||||
// gives the swatch that color, unrounded.
|
||||
let old: Vec<Option<Color>> =
|
||||
s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default();
|
||||
let colors: Vec<Color> =
|
||||
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
|
||||
let entries = p.get("colors").and_then(Value::as_array);
|
||||
let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse);
|
||||
let mut colors: Vec<Option<Color>> = colors
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
c.map(|c| match old.get(i).copied().flatten() {
|
||||
Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o,
|
||||
_ => super::paint::new_color(s, p, c),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A null past the group's swatches removes nothing.
|
||||
while colors.len() > old.len() && colors.last() == Some(&None) {
|
||||
colors.pop();
|
||||
}
|
||||
let rename = str_param(p, "rename");
|
||||
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
|
||||
// The group's own colors, in order, under its own name change nothing: no undo step.
|
||||
if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group)
|
||||
&& rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group)
|
||||
&& old.len() == colors.len()
|
||||
&& old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c)
|
||||
{
|
||||
return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::<Vec<_>>(), "relinked": 0}));
|
||||
}
|
||||
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
|
||||
e.defaults(s)?;
|
||||
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Swatches",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number → {library, added: [names in the document], existing: [names already there], applied?: name}",
|
||||
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy to User Defined",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
"{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}",
|
||||
has_user_folder,
|
||||
copy_to_user
|
||||
),
|
||||
@@ -109,6 +109,9 @@ pub struct Libraries<L = SwatchLibrary> {
|
||||
/// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those
|
||||
/// bytes, and keeps one whose file is missing so a file put back can be checked.
|
||||
saved_as: HashMap<String, SavedAs>,
|
||||
/// The documents loaded swatch libraries were read from, by library id, for those with pattern
|
||||
/// swatches: the patterns live there ([`Libraries::pattern_doc`]).
|
||||
pattern_docs: HashMap<String, Arc<vectorcraft_doc::Document>>,
|
||||
}
|
||||
|
||||
/// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`]
|
||||
@@ -149,6 +152,38 @@ impl LibraryFile for SwatchLibrary {
|
||||
/// The extensions of library files [`palette_io::read_bytes`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"];
|
||||
|
||||
/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the
|
||||
/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`).
|
||||
pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"];
|
||||
|
||||
impl Libraries<SwatchLibrary> {
|
||||
/// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None`
|
||||
/// forgets the one kept for `id`.
|
||||
fn set_pattern_doc(&mut self, id: &str, doc: Option<Arc<vectorcraft_doc::Document>>) {
|
||||
match doc {
|
||||
Some(doc) => self.pattern_docs.insert(id.to_string(), doc),
|
||||
None => self.pattern_docs.remove(id),
|
||||
};
|
||||
}
|
||||
|
||||
/// The document holding the patterns of loaded library `id`'s pattern swatches.
|
||||
pub fn pattern_doc(&self, id: &str) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
self.pattern_docs.get(id).cloned()
|
||||
}
|
||||
|
||||
/// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own
|
||||
/// pattern swatches (a library panel draws them from it). Only the libraries that have pattern
|
||||
/// swatches are looked at, each by the address ranges of its swatch lists.
|
||||
pub fn pattern_source(&self, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
let Paint::Pattern { pattern, .. } = &w.paint else { return None };
|
||||
let at = std::ptr::from_ref(w);
|
||||
let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at);
|
||||
let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches));
|
||||
let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?;
|
||||
Some(doc.clone()).filter(|d| d.pattern(pattern).is_some())
|
||||
}
|
||||
}
|
||||
|
||||
/// A library file the save commands write ([`Libraries::write`]).
|
||||
pub(crate) enum FileData {
|
||||
/// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`.
|
||||
@@ -646,6 +681,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option<Vec<Swatch>> {
|
||||
Some(library(s, key)?.1.iter().filter(own).cloned().collect())
|
||||
}
|
||||
|
||||
/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded
|
||||
/// library's own pattern swatch (a library panel draws them from it).
|
||||
pub fn pattern_source(s: &Session, w: &Swatch) -> Option<Arc<vectorcraft_doc::Document>> {
|
||||
patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w))
|
||||
}
|
||||
|
||||
/// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null).
|
||||
/// A `limitTo` that is not a string, such as `5`, names no library.
|
||||
pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Palette>> {
|
||||
@@ -694,13 +735,17 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The document's swatches `names` (swatches or colour groups; empty: all) as a library named
|
||||
/// `name`, without None and patterns.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result<SwatchLibrary> {
|
||||
/// `name`, without None, and without pattern swatches unless `patterns`.
|
||||
fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result<SwatchLibrary> {
|
||||
if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) {
|
||||
return Err(bad(cmd, format!("no swatch or colour group `{n}`")));
|
||||
}
|
||||
let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n);
|
||||
let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_));
|
||||
let savable = |w: &&Swatch| match w.paint {
|
||||
Paint::Solid { .. } | Paint::Gradient(_) => true,
|
||||
Paint::Pattern { .. } => patterns,
|
||||
_ => false,
|
||||
};
|
||||
let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect();
|
||||
let groups = d
|
||||
.swatch_groups
|
||||
@@ -724,7 +769,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let names = names_param(p, C)?;
|
||||
let st = s.doc()?;
|
||||
let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = document_library(&st.doc, &names, name, C)?;
|
||||
let lib = document_library(&st.doc, &names, name, false, C)?;
|
||||
let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?;
|
||||
let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) };
|
||||
let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()});
|
||||
@@ -734,21 +779,44 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
// The document a library with pattern swatches was read from, which holds their patterns.
|
||||
let mut patterns = None;
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
|
||||
}
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
|
||||
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
|
||||
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
|
||||
if defaults || lib.is_empty() {
|
||||
return Err(bad(C, format!("`{file}` has no swatches of its own")));
|
||||
}
|
||||
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
|
||||
patterns = Some(Arc::new(loaded.doc));
|
||||
}
|
||||
Ok(lib)
|
||||
})?;
|
||||
if info.category == "loaded" {
|
||||
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
|
||||
}
|
||||
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
|
||||
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
|
||||
/// document's are.
|
||||
fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool {
|
||||
use vectorcraft_color::cms::Model;
|
||||
[Model::Rgb, Model::Cmyk].into_iter().any(|model| {
|
||||
let (swatches, groups) = default_swatches(model);
|
||||
d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..]
|
||||
})
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "swatch.library.get")?;
|
||||
let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None));
|
||||
@@ -772,6 +840,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.copyToUser";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let (info, lib, copied) = match info.category {
|
||||
"loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => {
|
||||
return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name)));
|
||||
}
|
||||
"loaded" => {
|
||||
let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e));
|
||||
s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)?
|
||||
@@ -811,6 +882,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The swatch of `d` that library pattern swatch `w` stands for once its pattern is `target` in `d`:
|
||||
/// one that paints `target` placed as `w` places its pattern, named as `w` or a numbered copy of
|
||||
/// that name ("Tiles 2"); for a swatch named after its pattern, under any name.
|
||||
fn library_pattern_swatch(d: &vectorcraft_doc::Document, w: &Swatch, target: &str) -> Option<String> {
|
||||
let Paint::Pattern { pattern, xf } = &w.paint else { return None };
|
||||
let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf };
|
||||
let named = |n: &str| {
|
||||
w.name == *pattern
|
||||
|| n == w.name
|
||||
|| n.strip_prefix(w.name.as_str())
|
||||
.and_then(|r| r.strip_prefix(' '))
|
||||
.is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone())
|
||||
}
|
||||
|
||||
/// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch).
|
||||
fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> {
|
||||
let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name));
|
||||
@@ -840,8 +927,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let focus = switch_or(p, "focus", true, C)?;
|
||||
let picked = picked(&lib, &names_param(p, C)?, C)?;
|
||||
// Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the
|
||||
// same pattern) are reused, not added again.
|
||||
let patterns = patternlib::library_doc(&info.id);
|
||||
// same pattern) are reused, not added again. The patterns are in a built-in pattern library's
|
||||
// document, or in the document a loaded library was read from.
|
||||
let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id));
|
||||
let d = &s.doc()?.doc;
|
||||
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
|
||||
// up once so that a large palette takes linear time.
|
||||
@@ -851,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let there = |w: &Swatch| match (&w.paint, &patterns) {
|
||||
(Paint::Pattern { pattern, .. }, Some(src)) => {
|
||||
patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target))
|
||||
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
|
||||
}
|
||||
_ => match by_name.get(w.name.as_str()) {
|
||||
Some(x) => x.paint == w.paint,
|
||||
@@ -873,32 +961,64 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let added: Vec<(String, String)> = if fresh.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
let (added, reused) = s.edit("Add to Swatches", |d, _| {
|
||||
let mut out = vec![];
|
||||
// Library pattern swatches that stand for a swatch added earlier in this call.
|
||||
let mut reused = vec![];
|
||||
// Each library group goes into one document group: the group of that name the document
|
||||
// already had, or one made here.
|
||||
let before = d.swatch_groups.len();
|
||||
let mut placed: Vec<(&str, usize)> = vec![];
|
||||
let mut taken = taken_names(d);
|
||||
// The swatches the patterns imported in this call brought with their art: (library
|
||||
// name, document name).
|
||||
let mut brought: Vec<(String, String)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
|
||||
// The pattern comes with its swatch; a pattern the document has without one
|
||||
// gets one.
|
||||
let target = patternlib::import(d, src, pattern)?;
|
||||
let name = match patternlib::pattern_swatch(d, &target) {
|
||||
Some(name) => name,
|
||||
None => {
|
||||
let name = d.free_swatch_name(&target);
|
||||
d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false });
|
||||
name
|
||||
}
|
||||
};
|
||||
out.push((w.name.clone(), name));
|
||||
// gets one. The swatch a pattern that comes in brings is named after the pattern:
|
||||
// it takes the library swatch's name and color group instead.
|
||||
let had = taken_names(d);
|
||||
let (target, colors) = patternlib::import(d, src, pattern)?;
|
||||
brought.extend(colors);
|
||||
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
|
||||
reused.push((w.name.clone(), name));
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n));
|
||||
if let Some(made) = &made {
|
||||
d.swatches.retain(|x| x.name != *made);
|
||||
}
|
||||
taken = taken_names(d);
|
||||
continue;
|
||||
}
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
let sw = Swatch { name: name.clone(), ..(*w).clone() };
|
||||
let name = match made {
|
||||
Some(made) if w.name == *pattern => made,
|
||||
None if w.name == *pattern => d.free_swatch_name(&target),
|
||||
_ => free_in(&mut taken, &w.name),
|
||||
};
|
||||
taken.insert(name.clone());
|
||||
// The library swatch's placement of its pattern is kept.
|
||||
let paint = match &w.paint {
|
||||
Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf },
|
||||
_ => pattern_paint(&target),
|
||||
};
|
||||
(name.clone(), Swatch { name, paint, global: false, spot: false })
|
||||
} else {
|
||||
// A color a pattern added earlier in this call brought with its art is that
|
||||
// swatch: it moves to the library swatch's place.
|
||||
let at = brought.iter().position(|(from, _)| *from == w.name);
|
||||
let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| {
|
||||
let i = d.swatches.iter().position(|x| x.name == n)?;
|
||||
Some(d.swatches.remove(i))
|
||||
});
|
||||
match moved {
|
||||
Some(sw) => (sw.name.clone(), sw),
|
||||
None => {
|
||||
let name = free_in(&mut taken, &w.name);
|
||||
(name.clone(), Swatch { name, ..(*w).clone() })
|
||||
}
|
||||
}
|
||||
};
|
||||
match group {
|
||||
Some(g) => {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
@@ -919,8 +1039,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
out.push((w.name.clone(), name));
|
||||
}
|
||||
Ok(out)
|
||||
})?
|
||||
Ok((out, reused))
|
||||
})?;
|
||||
existing.extend(reused);
|
||||
added
|
||||
};
|
||||
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
|
||||
|
||||
@@ -1883,13 +1883,14 @@ enum Step {
|
||||
BaselineShift,
|
||||
}
|
||||
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo step).
|
||||
/// The Type tool's selected text while it edits (its typing session ends first: one undo step,
|
||||
/// with typing that Real-time Drawing off left unapplied applied first).
|
||||
pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, usize)>> {
|
||||
let o = s.tool_options();
|
||||
let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
|
||||
if super::edit::typing_in_progress(s) {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let at = |k: &str| byte_param(&o, k).unwrap_or(0);
|
||||
Ok(Some((id, at("start"), at("end"))))
|
||||
|
||||
@@ -488,8 +488,14 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind, verb: &str) -> Result<Opt
|
||||
};
|
||||
char_attrs(&style)
|
||||
}
|
||||
// The paragraph at `start`.
|
||||
Kind::Para => para_attrs(t.para_at(t.paragraphs_in(at, at).start)),
|
||||
// The paragraph at `start`, without the number its list gives that paragraph alone.
|
||||
Kind::Para => {
|
||||
let mut para = t.para_at(t.paragraphs_in(at, at).start).clone();
|
||||
if let Some(l) = para.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
para_attrs(¶)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -639,6 +645,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
Kind::Para => {
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
// A list's number belongs to one paragraph, not to a style.
|
||||
if st.list.is_some_and(|l| l.start.is_some()) {
|
||||
let k = "list.start";
|
||||
return Err(bad(&c, format!("unknown attribute `{k}`")));
|
||||
}
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
|
||||
@@ -736,6 +736,189 @@ fn numbered_lists_are_set_per_paragraph_saved_and_styled() {
|
||||
assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None));
|
||||
}
|
||||
|
||||
/// `text.setFormat {startNumber}` gives the first numbered paragraph it touches a number, and the
|
||||
/// paragraphs after it count on from it; `restartNumbering` true gives it 1 and false takes the
|
||||
/// numbers away. Each change is one undo step, a call that changes nothing records none, and a
|
||||
/// bad value or both keys change nothing. The file keeps the number, Return and paragraph styles
|
||||
/// do not take it, a bulleted paragraph keeps none, and Convert to Text writes the numbers shown.
|
||||
#[test]
|
||||
fn a_numbered_paragraph_starts_at_a_given_number_or_restarts() {
|
||||
use vectorcraft_doc::text::{Bullet, ParaList};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": "Intro\nOne\nTwo\nThree\nFour", "area": {"width": 300, "height": 200}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let starts = |s: &Session| text(s).paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
|
||||
let numbers = |s: &Session| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let undo = |s: &Session| s.active().unwrap().history.undo.len();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
// A call over all the text gives the number to the first paragraph the same call numbers.
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 24, "number": "arabic", "startNumber": 5})).unwrap();
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, None]);
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."]);
|
||||
// On "Three": `restartNumbering` gives it 1, and "Four" counts on from it.
|
||||
let steps = undo(&s);
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "restartNumbering": true})).unwrap();
|
||||
assert_eq!((numbers(&s), undo(&s)), (vec!["5.".to_string(), "6.".into(), "1.".into(), "2.".into()], steps + 1));
|
||||
// The same number again, or a call on a paragraph in no list, changes nothing.
|
||||
s.execute("text.setFormat", &json!({"start": 14, "end": 14, "startNumber": 1.0})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 3})).unwrap();
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
// Bad values and both keys at once are errors and change nothing.
|
||||
for bad in [
|
||||
json!({"startNumber": 0}),
|
||||
json!({"startNumber": -2}),
|
||||
json!({"startNumber": 2.5}),
|
||||
json!({"startNumber": 1_000_000_000}),
|
||||
json!({"startNumber": "5"}),
|
||||
json!({"restartNumbering": "yes"}),
|
||||
json!({"startNumber": 3, "restartNumbering": true}),
|
||||
] {
|
||||
assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((starts(&s), undo(&s)), (vec![None, Some(5), None, Some(1), None], steps + 1));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "8."], "one Undo takes the restart back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// The file keeps the numbers.
|
||||
assert_eq!(serde_json::to_value(text(&s).para_at(1)).unwrap()["list"], json!({"bullet": "dot", "number": "arabic", "start": 5}));
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert_eq!(back.paragraph_styles(), text(&s).paragraph_styles());
|
||||
// Return at the end of "One" makes an item that counts on, without a number of its own.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 9, "end": 9, "insert": "\nOne and a half"})).unwrap();
|
||||
assert_eq!(numbers(&s), ["5.", "6.", "7.", "1.", "2."]);
|
||||
assert_eq!(starts(&s), [None, Some(5), None, None, Some(1), None]);
|
||||
// A paragraph style made from the paragraph does not keep its number, and a style's list
|
||||
// with a number is an error.
|
||||
s.execute("paraStyle.new", &json!({"name": "Item", "id": id, "start": 6, "end": 6})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Item", "id": id})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert_eq!(numbers(&s), ["1.", "2.", "3.", "4.", "5.", "6."]);
|
||||
let given = json!({"name": "Given", "attrs": {"list": {"number": "arabic", "start": 4}}});
|
||||
assert!(s.execute("paraStyle.new", &given).is_err());
|
||||
// `restartNumbering` false takes every number the call touches away; a paragraph made bulleted
|
||||
// keeps none.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 6, "end": 6, "startNumber": 3})).unwrap();
|
||||
assert_eq!(starts(&s)[..2], [Some(7), Some(3)]);
|
||||
s.execute("text.setFormat", &json!({"restartNumbering": false})).unwrap();
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "startNumber": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "bullet": "dot"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list, Some(ParaList::bulleted(Bullet::Dot)));
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "upperRoman"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(0).list.and_then(|l| l.start), None, "numbered again, it counts on");
|
||||
// Convert to Text writes the numbers the paragraphs showed.
|
||||
s.execute("text.setFormat", &json!({"start": 0, "end": 0, "number": "arabic", "startNumber": 10})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"start": 30, "end": 30, "restartNumbering": true})).unwrap();
|
||||
let shown = numbers(&s);
|
||||
assert_eq!(shown, ["10.", "11.", "12.", "13.", "1.", "2."]);
|
||||
s.execute("text.convertListToText", &json!({})).unwrap();
|
||||
let written: Vec<String> = text(&s).plain_text().split('\n').map(|p| p.split('\t').next().unwrap_or("").to_string()).collect();
|
||||
assert_eq!(written, shown);
|
||||
assert_eq!(starts(&s), [None; 6]);
|
||||
assert!(text(&s).paragraph_styles().iter().all(|p| p.list.is_none()));
|
||||
}
|
||||
|
||||
/// In threaded type, a paragraph given a number in the first frame carries its count on through
|
||||
/// the later frames, and a paragraph given 1 in a later frame starts the count again there.
|
||||
#[test]
|
||||
fn a_given_number_carries_through_threaded_frames() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let story = (1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
let first = numbers(&s, a).len();
|
||||
assert!((2..10).contains(&first), "both frames hold items: {first}");
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 20})).unwrap();
|
||||
let want: Vec<String> = (20..30).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// The first paragraph of the second frame given 1: the second frame counts from 1.
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "start": 0, "end": 0, "restartNumbering": true})).unwrap();
|
||||
let want: Vec<String> = (20..20 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
// Editing the first frame's number moves every later number on with it.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 0, "startNumber": 2})).unwrap();
|
||||
let want: Vec<String> = (2..2 + first).chain(1..=10 - first).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!([numbers(&s, a), numbers(&s, b)].concat(), want);
|
||||
}
|
||||
|
||||
/// A number given in a threaded frame whose first paragraph continues from the frame before goes
|
||||
/// to the next numbered paragraph that begins in that frame, not to the item the earlier frame shows,
|
||||
/// and `restartNumbering` false there leaves that item's number alone.
|
||||
#[test]
|
||||
fn a_given_number_skips_the_paragraph_continued_from_the_frame_before() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let text = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let long = (1..=40).map(|i| format!("word{i}")).collect::<Vec<_>>().join(" ");
|
||||
let story = format!("One\n{long}\nThree");
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 250})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
assert!(text(&s, b).first_para_continues, "the second frame starts inside the long paragraph");
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["3.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "startNumber": 5})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "2.".into()], vec!["5.".to_string()]));
|
||||
// The long item, numbered in the first frame, keeps its number when the second frame's are taken away.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 4, "end": 4, "startNumber": 8})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["5.".to_string()]));
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "restartNumbering": false})).unwrap();
|
||||
assert_eq!((numbers(&s, a), numbers(&s, b)), (vec!["1.".to_string(), "8.".into()], vec!["9.".to_string()]));
|
||||
}
|
||||
|
||||
/// `startNumber` over several type objects goes to the first numbered paragraph with text among
|
||||
/// all of them, past an empty numbered object listed first; with no text anywhere it goes to the
|
||||
/// first numbered paragraph.
|
||||
#[test]
|
||||
fn a_given_number_goes_to_the_first_numbered_text_across_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let make =
|
||||
|s: &mut Session, y: u32, text: &str| s.execute("text.create", &json!({"x": 10, "y": y, "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
let empty = make(&mut s, 10, "");
|
||||
let full = make(&mut s, 60, "One\nTwo");
|
||||
let start = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.para_at(0).list.and_then(|l| l.start),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [empty, full], "startNumber": 4})).unwrap();
|
||||
assert_eq!((start(&s, empty), start(&s, full)), (None, Some(4)));
|
||||
let other = make(&mut s, 120, "");
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "number": "arabic"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [other, empty], "startNumber": 6})).unwrap();
|
||||
assert_eq!((start(&s, other), start(&s, empty)), (Some(6), None));
|
||||
}
|
||||
|
||||
/// Bullets and Numbering… › Alignment: `text.setFormat {listAlign}` sets where the marker
|
||||
/// stands in the list paragraphs it touches, in one undo step, and refuses unknown values;
|
||||
/// a paragraph in no list gets no list from it. A list keeps its alignment when it changes
|
||||
@@ -2613,6 +2796,44 @@ fn area_options_columns_change_layout() {
|
||||
assert!(s.execute("text.areaOptions", &json!({"firstBaseline": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height: set, reported and undone like the other kinds, with Min as the
|
||||
/// least distance; setting it again adds no undo step, and the refusal of an unknown kind lists it.
|
||||
#[test]
|
||||
fn area_options_set_the_em_box_height_first_baseline() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "word ".repeat(20), "area": {"width": 300, "height": 120}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let first = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines[0].first_baseline,
|
||||
_ => panic!("area type"),
|
||||
};
|
||||
let ascent = first(&s);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(0.0)));
|
||||
let em_box = first(&s);
|
||||
assert!(em_box > 0.0 && (em_box - ascent).abs() > 0.1, "{em_box} {ascent}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no change, no undo step");
|
||||
// A Min nearer the top keeps the em box; one further down is the distance.
|
||||
s.execute("text.areaOptions", &json!({"firstBaselineMin": em_box / 2.0})).unwrap();
|
||||
assert!((first(&s) - em_box).abs() < 1e-9);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaselineMin": 30})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(30.0)));
|
||||
assert!((first(&s) - 30.0).abs() < 1e-9);
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
assert!((first(&s) - ascent).abs() < 1e-9);
|
||||
let e = s.execute("text.areaOptions", &json!({"firstBaseline": "emBox"})).unwrap_err().to_string();
|
||||
assert!(e.contains("emBoxHeight"), "{e}");
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
}
|
||||
|
||||
/// `rowGutter` sets a gutter between rows of its own, the reply passes it back, and a gutter
|
||||
/// given alone is the rows' and the columns' again.
|
||||
#[test]
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! variable name per column, which export writes with `#` before a visibility variable and `@`
|
||||
//! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…,
|
||||
//! also reads tab-separated files, and reads header cells that define new variables (`#` for
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for
|
||||
//! text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
|
||||
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
|
||||
@@ -1070,7 +1071,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Data Sets…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
"{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. The files are read at import. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused (an `@Name` column's relative paths are kept as they are and taken from the document's folder when a data set is selected). A path on another computer, or on a network share other than the one `base` or the CSV is on, a device and a URL other than a `file:` URL without a host are refused, as image variables' paths are, before anything is read. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
json, read_file_head, str_param, variables_unlocked, write_file,
|
||||
};
|
||||
use crate::cmd::place::text::windows_1252;
|
||||
use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param};
|
||||
|
||||
/// Cap on a graph variable's CSV (MCP and files are untrusted).
|
||||
pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024;
|
||||
@@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String {
|
||||
|
||||
/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`]
|
||||
/// writes, in a document without the variables: the first list names the variables whose header
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values
|
||||
/// aren't true or false, a header that names a variable an earlier column named), and the second
|
||||
/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`,
|
||||
/// and a graph variable, which no header cell defines).
|
||||
/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as
|
||||
/// paths of graph data files, a `#` header whose values aren't true or false, a header that names
|
||||
/// a variable an earlier column named), and the second the variables it reads as another variable
|
||||
/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph
|
||||
/// variable, which the export writes without `%`).
|
||||
fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
const C: &str = "dataset.import";
|
||||
let none = BTreeMap::new();
|
||||
@@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) {
|
||||
refused.push(v.name.as_str());
|
||||
continue;
|
||||
};
|
||||
// A `%` header's cells are paths of graph data files, which the values the export writes aren't.
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| {
|
||||
let cell = value_to_cell(val);
|
||||
cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok()
|
||||
if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() }
|
||||
});
|
||||
if !cells_read {
|
||||
refused.push(v.name.as_str());
|
||||
@@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result<String> {
|
||||
/// that earlier columns define) names that variable. Otherwise `#` before the name makes it a
|
||||
/// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text
|
||||
/// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new
|
||||
/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused.
|
||||
/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the
|
||||
/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart
|
||||
/// by a returned name that is not the cell.
|
||||
fn header_variable(
|
||||
cell: &str,
|
||||
column: usize,
|
||||
@@ -356,8 +362,8 @@ fn header_variable(
|
||||
(rest.trim(), VariableKind::Visibility)
|
||||
} else if let Some(rest) = cell.strip_prefix('@') {
|
||||
(rest.trim(), VariableKind::Image)
|
||||
} else if cell.starts_with('%') {
|
||||
return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read")));
|
||||
} else if let Some(rest) = cell.strip_prefix('%') {
|
||||
(rest.trim(), VariableKind::Graph)
|
||||
} else {
|
||||
(cell, VariableKind::Text)
|
||||
};
|
||||
@@ -375,13 +381,94 @@ fn header_variable(
|
||||
}
|
||||
}
|
||||
|
||||
/// The most bytes the `%` columns of one import read from graph data files and keep as graph
|
||||
/// values, counted together: each file's bytes once (it is read once, however many cells name it),
|
||||
/// and the graph value of every cell, which each data set holds a copy of.
|
||||
const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576;
|
||||
|
||||
/// The graph data files the `%` columns of one import have read, by path, and the bytes counted
|
||||
/// against [`MAX_GRAPH_FILES_TOTAL`] so far.
|
||||
#[derive(Default)]
|
||||
struct GraphFiles {
|
||||
read: BTreeMap<String, String>,
|
||||
total: usize,
|
||||
}
|
||||
|
||||
/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the
|
||||
/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when
|
||||
/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]),
|
||||
/// or no value for an empty cell. The path is followed as an image variable's path is
|
||||
/// ([`crate::cmd::fileio::document_path`]): only files on this computer, or on the network share
|
||||
/// `base` is on, are read. A relative path without `base`, a path on another computer or share, a
|
||||
/// device or a URL, a file that can't be read or is larger than 1 MB, a file that gives a graph
|
||||
/// value longer than [`MAX_GRAPH_CSV`] bytes and more than [`MAX_GRAPH_FILES_TOTAL`] bytes in all
|
||||
/// are refused, with the line and the column.
|
||||
fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result<Option<DataValue>> {
|
||||
const C: &str = "dataset.import";
|
||||
let path = path.trim();
|
||||
if path.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// Without `base`, a path that stays relative once a `file:` URL is read is refused here, so the
|
||||
// error says what to give.
|
||||
if base.is_none() && craft_docpath::resolve(path, None).is_ok_and(|p| !p.is_absolute()) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"),
|
||||
));
|
||||
}
|
||||
// `document_path` takes a relative path from the folder of a document; any file name in `base`
|
||||
// stands for the CSV there.
|
||||
let document = base.map(|base| std::path::Path::new(base).join("data sets.csv").to_string_lossy().into_owned());
|
||||
let full = crate::cmd::fileio::document_path(path, document.as_deref())
|
||||
.map_err(|r| bad(C, format!("line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r}")))?;
|
||||
let csv = match files.read.get(&full) {
|
||||
Some(csv) => csv.clone(),
|
||||
None => {
|
||||
// One byte past the limit is enough to refuse the file.
|
||||
let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1)
|
||||
.map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?;
|
||||
if bytes.len() > MAX_GRAPH_DATA_FILE {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"),
|
||||
));
|
||||
}
|
||||
let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?;
|
||||
if csv.len() > MAX_GRAPH_CSV {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes"
|
||||
),
|
||||
));
|
||||
}
|
||||
files.total += bytes.len();
|
||||
files.read.insert(full, csv.clone());
|
||||
csv
|
||||
}
|
||||
};
|
||||
files.total += csv.len();
|
||||
if files.total > MAX_GRAPH_FILES_TOTAL {
|
||||
return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all")));
|
||||
}
|
||||
Ok(Some(DataValue::Graph(csv)))
|
||||
}
|
||||
|
||||
/// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it,
|
||||
/// and the variables the document doesn't define yet are defined, unbound. Two headers that name
|
||||
/// one variable are refused. The rows replace every dataset of the document and are named "Data
|
||||
/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// one variable are refused. The cells of a `%` column are paths of graph data files
|
||||
/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the
|
||||
/// folder of the file `path` names. The rows replace every dataset of the document and are named
|
||||
/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings
|
||||
/// stay. One undo step, and none when the variables and datasets stay as they were.
|
||||
pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "dataset.import";
|
||||
let base = match text_param(p, "base", C)? {
|
||||
Some("") => return Err(bad(C, "`base` is empty")),
|
||||
Some(base) => Some(absolute_path(base)),
|
||||
None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())),
|
||||
};
|
||||
let (bytes, given_as_text) = datasets_csv_bytes(p, C)?;
|
||||
// `data` and `csv` are already text, NUL characters included (`dataset.export` writes them).
|
||||
let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? };
|
||||
@@ -390,7 +477,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV is empty"));
|
||||
};
|
||||
let kinds: BTreeMap<String, VariableKind> = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect();
|
||||
let mut columns: Vec<(usize, String, VariableKind)> = Vec::new();
|
||||
// Each column: its index, its variable and kind, and whether its cells are graph data files.
|
||||
let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new();
|
||||
let mut defined: Vec<Variable> = Vec::new();
|
||||
for (i, h) in header.iter().enumerate() {
|
||||
let cell = h.trim();
|
||||
@@ -398,11 +486,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("empty header in column {}", i + 1)));
|
||||
}
|
||||
let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?;
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) {
|
||||
if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) {
|
||||
let (first, column) = (first + 1, i + 1);
|
||||
return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`")));
|
||||
}
|
||||
columns.push((i, name, kind));
|
||||
let files = kind == VariableKind::Graph && name != cell;
|
||||
columns.push((i, name, kind, files));
|
||||
}
|
||||
// Lock Variables refuses New Variable, so the import is refused when a header would define one.
|
||||
if !defined.is_empty() {
|
||||
@@ -412,13 +501,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "CSV has a header but no data rows"));
|
||||
}
|
||||
let mut parsed: Vec<DataSet> = Vec::new();
|
||||
let mut files = GraphFiles::default();
|
||||
for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() {
|
||||
let name = format!("Data Set {}", n + 1);
|
||||
let mut values = BTreeMap::new();
|
||||
for &(col, ref var, kind) in &columns {
|
||||
for &(col, ref var, kind, from_files) in &columns {
|
||||
let cell = row.get(col).map(String::as_str).unwrap_or("");
|
||||
let was_quoted = quoted.get(col).copied().unwrap_or(false);
|
||||
if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? {
|
||||
let value = if from_files {
|
||||
graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))?
|
||||
} else {
|
||||
cell_to_value(kind, cell, was_quoted, var, line, C)?
|
||||
};
|
||||
if let Some(v) = value {
|
||||
values.insert(var.clone(), v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,7 +619,21 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap
|
||||
}
|
||||
}
|
||||
doc.variables = vars.into();
|
||||
left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label())))
|
||||
left_out_warning(other.iter().map(|v| left_out_kind(v.kind, v.trait_name.as_deref())))
|
||||
}
|
||||
|
||||
/// How the warning about variables that aren't text names the kind of one: Visibility, Linked File
|
||||
/// or Graph Data for a `trait` VectorCraft reads, Unknown for a variable without a `trait`, and any
|
||||
/// other `trait` as the file writes it, in backticks, each backtick in it doubled, so that a `trait`
|
||||
/// such as `Unknown` or `a (1), b` reads as one kind the file names.
|
||||
fn left_out_kind(kind: VariableKind, trait_name: Option<&str>) -> String {
|
||||
match (kind, trait_name) {
|
||||
(VariableKind::Visibility, _) => "Visibility".into(),
|
||||
(VariableKind::Image, _) => "Linked File".into(),
|
||||
(VariableKind::Graph, _) => "Graph Data".into(),
|
||||
(_, None) => "Unknown".into(),
|
||||
(_, Some(t)) => format!("`{}`", t.replace('`', "``")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load Variable Library: replace the document's variables and data sets with a variable library's
|
||||
@@ -668,10 +682,11 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names}))
|
||||
}
|
||||
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each: every
|
||||
/// kind once, in the order it first comes, with how many variables have it. `None` without any.
|
||||
fn left_out_warning<'a>(kinds: impl Iterator<Item = &'a str>) -> Option<String> {
|
||||
let mut counted: Vec<(&str, usize)> = Vec::new();
|
||||
/// The warning about variables that aren't text and were left out, given the kind of each
|
||||
/// ([`left_out_kind`]): every kind once, in the order it first comes, with how many variables have
|
||||
/// it. `None` without any.
|
||||
fn left_out_warning(kinds: impl Iterator<Item = String>) -> Option<String> {
|
||||
let mut counted: Vec<(String, usize)> = Vec::new();
|
||||
for t in kinds {
|
||||
match counted.iter_mut().find(|(k, _)| *k == t) {
|
||||
Some((_, n)) => *n += 1,
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
//! guard against other programs on the computer.
|
||||
//!
|
||||
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
|
||||
//! are read from, inside the roots.
|
||||
//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots.
|
||||
//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the
|
||||
//! files of the open documents.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
@@ -174,7 +176,7 @@ fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
match roots {
|
||||
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
|
||||
Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
@@ -182,25 +184,111 @@ pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -
|
||||
/// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the
|
||||
/// app's own folders.
|
||||
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_scope(Some(Scope::Unconfined), f)
|
||||
with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f))
|
||||
}
|
||||
|
||||
/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]).
|
||||
thread_local! {
|
||||
/// Are reads on this thread exempt from the gate of the script command it runs? Only inside an
|
||||
/// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]).
|
||||
static GATE_READS_EXEMPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Puts the exemption it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreExempt(bool);
|
||||
|
||||
impl Drop for RestoreExempt {
|
||||
fn drop(&mut self) {
|
||||
GATE_READS_EXEMPT.with(|e| e.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScopeHandle(Option<Scope>);
|
||||
pub struct ScopeHandle(Option<Scope>, Option<Arc<ScriptGate>>, bool);
|
||||
|
||||
impl ScopeHandle {
|
||||
/// The scope of the calling thread.
|
||||
pub fn capture() -> Self {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()))
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
with_scope(self.0, f)
|
||||
let Self(scope, gate, exempt) = self;
|
||||
with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f)))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a command a running script runs (`vc.run`) may read and write: the places the script's
|
||||
/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app
|
||||
/// were opened from or saved to. The automation roots apply as well. A path refused by its name
|
||||
/// alone ([`ScriptScope::refused_by_name`]) is refused here too.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ScriptGate {
|
||||
pub(crate) read: ScriptScope,
|
||||
pub(crate) write: ScriptScope,
|
||||
/// The paths of the open documents' files, as the documents hold them.
|
||||
pub(crate) documents: Vec<String>,
|
||||
}
|
||||
|
||||
impl ScriptGate {
|
||||
fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The gate of the script command this thread runs ([`with_script_gate`]).
|
||||
static GATE: RefCell<Option<Arc<ScriptGate>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Puts the gate it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreGate(Option<Arc<ScriptGate>>);
|
||||
|
||||
impl Drop for RestoreGate {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
GATE.with(|g| *g.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate<T>(gate: Option<Arc<ScriptGate>>, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreGate(GATE.with(|g| g.replace(gate)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or
|
||||
/// writes must pass the gate as well as the automation roots, also when the run itself is
|
||||
/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an
|
||||
/// [`unconfined`] the command enters, are not checked; writes there are, so a script's command
|
||||
/// does not save into the app's libraries.
|
||||
pub(crate) fn with_script_gate<T>(gate: ScriptGate, f: impl FnOnce() -> T) -> T {
|
||||
with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f))
|
||||
}
|
||||
|
||||
/// May `path` be read (or written) by the script command this thread runs? Always outside one,
|
||||
/// and for a read inside an [`unconfined`] the command entered.
|
||||
fn check_gate(path: &str, access: Access) -> Result<(), String> {
|
||||
if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) {
|
||||
return Ok(());
|
||||
}
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access))
|
||||
}
|
||||
|
||||
/// The roots in force on this thread, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
match SCOPE.with(|s| s.borrow().clone()) {
|
||||
@@ -210,9 +298,11 @@ pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
/// May `path` be read here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_read(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))?;
|
||||
check_gate(path, Access::Read)
|
||||
}
|
||||
|
||||
/// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one
|
||||
@@ -229,9 +319,11 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
crate::cmd::key_location(key).is_some()
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -323,6 +415,12 @@ fn inside(path: &Path, root: &Path) -> bool {
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`]
|
||||
/// compares them?
|
||||
pub(crate) fn path_inside(path: &Path, root: &Path) -> bool {
|
||||
inside(path, root)
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
@@ -374,10 +472,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> {
|
||||
/// The file opened is the path with its links followed, and after reading, the path is followed
|
||||
/// again and must still lead to the same place: a process that changes the folders twice in between
|
||||
/// can still win that race.
|
||||
///
|
||||
/// A scope can also be given more folders ([`ScriptScope::add`]) and single files
|
||||
/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder
|
||||
/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its
|
||||
/// own path only, also when a folder later takes its place.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ScriptScope {
|
||||
/// The granted folders, made absolute with their links followed.
|
||||
roots: Vec<PathBuf>,
|
||||
/// The granted files, made absolute with their links followed.
|
||||
files: Vec<PathBuf>,
|
||||
/// The folders kept out, with their links followed.
|
||||
fenced: Vec<PathBuf>,
|
||||
/// The places inside a fenced folder that are not kept out.
|
||||
open: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Why a script's file was not read.
|
||||
@@ -396,18 +505,68 @@ pub(crate) enum ScriptRead {
|
||||
impl ScriptScope {
|
||||
/// The scope of a script run from a file in folder `dir`: that folder.
|
||||
pub(crate) fn of_folder(dir: &Path) -> Self {
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() }
|
||||
}
|
||||
|
||||
/// Grants the folder `real`, a path with its links followed, with everything inside it.
|
||||
pub(crate) fn add(&mut self, real: PathBuf) {
|
||||
if !self.roots.contains(&real) {
|
||||
self.roots.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants the file `real`, a path with its links followed: that path and nothing below it.
|
||||
pub(crate) fn add_file(&mut self, real: PathBuf) {
|
||||
if !self.files.contains(&real) {
|
||||
self.files.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or
|
||||
/// [`ScriptScope::add_file`] gave.
|
||||
pub(crate) fn remove(&mut self, real: &Path, folder: bool) {
|
||||
if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) }
|
||||
}
|
||||
|
||||
/// Is nothing granted?
|
||||
fn is_empty(&self) -> bool {
|
||||
self.roots.is_empty() && self.files.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the
|
||||
/// places inside it.
|
||||
pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) {
|
||||
self.fenced.push(real);
|
||||
self.open.extend(open.iter().cloned());
|
||||
}
|
||||
|
||||
/// Leaves the place `real` (links followed) and everything in it open inside a fenced folder.
|
||||
pub(crate) fn fence_open(&mut self, real: PathBuf) {
|
||||
self.open.push(real);
|
||||
}
|
||||
|
||||
/// The granted folders, with their links followed.
|
||||
pub(crate) fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place
|
||||
/// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it.
|
||||
pub(crate) fn allows(&self, real: &Path) -> bool {
|
||||
(self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count())
|
||||
|| self.roots.iter().any(|r| inside(real, r)))
|
||||
&& !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
|
||||
}
|
||||
|
||||
/// The scope of a script run from a file in the folder whose real path, with its links already
|
||||
/// followed, is `real`: that folder, which is not looked up again.
|
||||
pub(crate) fn of_real_folder(real: PathBuf) -> Self {
|
||||
Self { roots: vec![real] }
|
||||
Self { roots: vec![real], ..Self::default() }
|
||||
}
|
||||
|
||||
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
|
||||
/// stream, or a computer on the network?
|
||||
fn refused_by_name(path: &Path) -> bool {
|
||||
pub(crate) fn refused_by_name(path: &Path) -> bool {
|
||||
let text = path.to_string_lossy();
|
||||
text.contains('\0')
|
||||
|| path.components().any(|c| c == Component::ParentDir)
|
||||
@@ -417,7 +576,7 @@ impl ScriptScope {
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let real = match std::fs::canonicalize(path) {
|
||||
@@ -428,7 +587,7 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
@@ -456,24 +615,24 @@ impl ScriptScope {
|
||||
self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone()))
|
||||
}
|
||||
|
||||
/// Does the absolute path `path` name a granted folder or a place inside one, by its names
|
||||
/// alone, without regard to case? A path that does not is refused before the file system is
|
||||
/// asked anything about it.
|
||||
/// Does the absolute path `path` name a granted file, a granted folder or a place inside one,
|
||||
/// by its names alone, without regard to case? A path that does not is refused before the file
|
||||
/// system is asked anything about it.
|
||||
fn names_inside(&self, path: &Path) -> bool {
|
||||
let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase();
|
||||
path.is_absolute()
|
||||
&& self.roots.iter().any(|r| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
})
|
||||
let names_under = |r: &PathBuf| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
};
|
||||
path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under))
|
||||
}
|
||||
|
||||
/// The real path of the file or folder at `path`, which must be absolute: refused as
|
||||
/// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every
|
||||
/// granted folder, in which case the file system is not asked about it.
|
||||
pub(crate) fn locate(&self, path: &Path) -> Result<PathBuf, ScriptRead> {
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
@@ -490,22 +649,72 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted folder: does the nearest folder above it that exists
|
||||
/// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is
|
||||
/// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too,
|
||||
/// so a script cannot tell whether the folder a link leads to exists.
|
||||
/// The real path that writing to `path` writes: `path` with its links followed (the last
|
||||
/// name's too only when `follow`), and for a path that does not exist yet, its nearest existing
|
||||
/// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a
|
||||
/// path, also when a link on the way leads nowhere, and when the automation write roots in force
|
||||
/// ([`check_write`]) do not take it.
|
||||
pub(crate) fn target(&self, path: &Path, follow: bool) -> Result<PathBuf, ScriptRead> {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
if check_write(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) };
|
||||
let real = match std::fs::symlink_metadata(path) {
|
||||
Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?,
|
||||
Ok(m) => {
|
||||
// Where case does not matter, the name given can differ in case from the name the
|
||||
// file system keeps, so a file or folder that is not a link is checked under the
|
||||
// kept name too.
|
||||
if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let mut missing = vec![name.to_os_string()];
|
||||
let mut at = parent;
|
||||
loop {
|
||||
match std::fs::symlink_metadata(at) {
|
||||
Ok(_) => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string());
|
||||
at = at.parent().ok_or(ScriptRead::Refused)?;
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
}
|
||||
}
|
||||
let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?;
|
||||
real.extend(missing.iter().rev());
|
||||
real
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
// The automation write roots take the place written as well as the path named.
|
||||
if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted place: with the links of the nearest folder above it
|
||||
/// that exists followed, and the rest of its names appended, is it granted? On a file system
|
||||
/// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or
|
||||
/// not. A link above it that leads to nothing is outside too, so a script cannot tell whether
|
||||
/// the folder a link leads to exists.
|
||||
fn missing_inside(&self, path: &Path) -> bool {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.find(|a| std::fs::symlink_metadata(a).is_ok())
|
||||
.and_then(|a| std::fs::canonicalize(a).ok())
|
||||
.is_some_and(|real| self.roots.iter().any(|r| inside(&real, r)))
|
||||
let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false };
|
||||
let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false };
|
||||
self.allows(&real.join(rest))
|
||||
}
|
||||
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
|
||||
@@ -548,7 +757,7 @@ impl ScriptScope {
|
||||
continue;
|
||||
}
|
||||
let Ok(target) = std::fs::canonicalize(entry.path()) else { continue };
|
||||
if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= max {
|
||||
|
||||
@@ -185,6 +185,10 @@ pub struct Session {
|
||||
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
|
||||
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
|
||||
new_doc_profile_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of each script's data folder (`Folder.userData`), beside which the grants file
|
||||
/// keeps the file access people allowed scripts; `None`: no folder
|
||||
/// ([`Session::attach_script_data`]).
|
||||
script_data_dir: Option<std::path::PathBuf>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
|
||||
@@ -214,6 +214,10 @@ pub struct Prefs {
|
||||
/// runs on: a Wayland compositor may not show frames from another GPU (#502). Single-GPU
|
||||
/// machines are unaffected.
|
||||
pub gpu_preference: String,
|
||||
/// The desktop app's window presents without vsync, with frames capped at 240 a second (#6013).
|
||||
/// Read at startup (it takes effect after a restart); `--present-mode` and
|
||||
/// `VECTORCRAFT_PRESENT_MODE` take precedence over it.
|
||||
pub low_latency_drawing: bool,
|
||||
pub history_states: u32,
|
||||
pub real_time_drawing: bool,
|
||||
/// Rasterizer worker threads; -1 = automatic.
|
||||
@@ -503,6 +507,7 @@ impl Default for Prefs {
|
||||
gpu_performance: true,
|
||||
animated_zoom: true,
|
||||
gpu_preference: s("automatic"),
|
||||
low_latency_drawing: false,
|
||||
history_states: 500,
|
||||
real_time_drawing: true,
|
||||
render_threads: -1,
|
||||
|
||||
+1512
-58
File diff suppressed because it is too large
Load Diff
+152
-13
@@ -38,7 +38,8 @@
|
||||
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
|
||||
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
|
||||
//!
|
||||
//! `File` and `Folder` read files inside the script's own folder ([`files`]).
|
||||
//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary
|
||||
//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]).
|
||||
//!
|
||||
//! A script with `#targetengine name` runs in that named engine, which the session keeps with the
|
||||
//! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each
|
||||
@@ -103,6 +104,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20;
|
||||
const SLICE_HOST_CALLS: u32 = 256;
|
||||
/// The bytes that may cross between a script and the host in one run.
|
||||
const MAX_BRIDGE_BYTES: u64 = 4 << 30;
|
||||
/// The most files a run's report names in `written`; past them the report has `writtenMore`.
|
||||
pub const MAX_WRITTEN: usize = 4096;
|
||||
|
||||
/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the
|
||||
/// order they were first written, and whether it wrote more.
|
||||
#[derive(Default)]
|
||||
struct Written {
|
||||
paths: Vec<String>,
|
||||
seen: std::collections::HashSet<String>,
|
||||
more: bool,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
fn add(&mut self, path: String) {
|
||||
if self.seen.contains(&path) {
|
||||
return;
|
||||
}
|
||||
if self.paths.len() >= MAX_WRITTEN {
|
||||
self.more = true;
|
||||
return;
|
||||
}
|
||||
self.seen.insert(path.clone());
|
||||
self.paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
@@ -259,9 +285,29 @@ struct KeptMap {
|
||||
struct KeptMaps {
|
||||
maps: std::collections::VecDeque<KeptMap>,
|
||||
bytes: usize,
|
||||
/// The SHA-256 of each source the engine's runs compiled (their scripts and what they
|
||||
/// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file
|
||||
/// grants are in force only for code they were kept for ([`files::Disk`]).
|
||||
code: std::collections::BTreeSet<String>,
|
||||
code_full: bool,
|
||||
}
|
||||
|
||||
/// The most sources whose SHA-256 a named engine keeps.
|
||||
pub const MAX_ENGINE_CODE: usize = 1024;
|
||||
|
||||
impl KeptMaps {
|
||||
/// Adds the sources `code` (and whether a run had more than it counted) to the engine's code.
|
||||
fn keep_code(&mut self, (code, more): (Vec<String>, bool)) {
|
||||
self.code_full |= more;
|
||||
for hash in code {
|
||||
if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) {
|
||||
self.code_full = true;
|
||||
} else {
|
||||
self.code.insert(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option<Arc<str>>) {
|
||||
let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len());
|
||||
let limit = kept_map_bytes();
|
||||
@@ -705,7 +751,7 @@ struct Host {
|
||||
waiting: Cell<bool>,
|
||||
log: RefCell<Vec<Value>>,
|
||||
log_bytes: Cell<usize>,
|
||||
written: RefCell<Vec<String>>,
|
||||
written: RefCell<Written>,
|
||||
/// The run's number in its session, and the script's name, which its console lines carry.
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
@@ -822,6 +868,7 @@ impl Host {
|
||||
return;
|
||||
}
|
||||
let mut kept = kept.borrow_mut();
|
||||
kept.keep_code(self.disk.borrow().code());
|
||||
kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone()));
|
||||
for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() {
|
||||
match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) {
|
||||
@@ -944,6 +991,35 @@ impl Host {
|
||||
Some(left)
|
||||
}
|
||||
|
||||
/// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`.
|
||||
fn note_written(&self, paths: Vec<String>) {
|
||||
let mut written = self.written.borrow_mut();
|
||||
for path in paths {
|
||||
written.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names.
|
||||
fn more_written(&self, report: &mut Value) {
|
||||
if self.written.borrow().more
|
||||
&& let Some(o) = report.as_object_mut()
|
||||
{
|
||||
o.insert("writtenMore".into(), json!(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the files the script left open and adds every file written to the report's `written`.
|
||||
/// → the files it could not write.
|
||||
fn flush_files(&self) -> Vec<String> {
|
||||
let mut disk = self.disk.borrow_mut();
|
||||
let failed = disk.flush_all();
|
||||
disk.record_code();
|
||||
let paths = disk.take_written();
|
||||
drop(disk);
|
||||
self.note_written(paths);
|
||||
failed
|
||||
}
|
||||
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
@@ -1160,13 +1236,13 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
let before: Vec<(u64, Arc<crate::Document>, u64)> =
|
||||
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
|
||||
crate::file_access::start_recording_writes();
|
||||
let r = s.execute(id, params);
|
||||
// The command reads and writes only where the script's own files may, and the open documents' files.
|
||||
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
|
||||
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
|
||||
// A file a command wrote before it failed is on disk all the same.
|
||||
let mut written = host.written.borrow_mut();
|
||||
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
|
||||
if !written.contains(&path) {
|
||||
written.push(path);
|
||||
}
|
||||
written.add(path);
|
||||
}
|
||||
drop(written);
|
||||
match r {
|
||||
@@ -1733,6 +1809,32 @@ impl Session {
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
|
||||
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
|
||||
/// longer waits.
|
||||
pub fn script_picker(&self) -> Option<files::ScriptPicker> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten()
|
||||
}
|
||||
|
||||
/// Gives the file dialog the running script waits at its answer: the paths the person picked
|
||||
/// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false
|
||||
/// when no file dialog waits.
|
||||
pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
|
||||
with_job(k, |j| {
|
||||
let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false };
|
||||
j.host.note_written(j.host.disk.borrow_mut().take_written());
|
||||
if let Err(e) = j.realm.answer(data) {
|
||||
j.host.disk.borrow_mut().failed = Some(e);
|
||||
}
|
||||
true
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The name of the running script.
|
||||
pub fn script_name(&self) -> Option<String> {
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone()))
|
||||
@@ -1859,7 +1961,17 @@ impl Session {
|
||||
realm.set_limits(limits);
|
||||
realm
|
||||
}
|
||||
None => Realm::with_options(options, limits),
|
||||
None => {
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
// Code the run evaluates withdraws the kept file grants not kept for it, before it runs.
|
||||
let l = link.clone();
|
||||
realm.observe_code(move |units| {
|
||||
if let Ok(h) = current(&l) {
|
||||
h.disk.borrow_mut().saw_code(units);
|
||||
}
|
||||
});
|
||||
realm
|
||||
}
|
||||
};
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
@@ -1879,7 +1991,7 @@ impl Session {
|
||||
waiting: Cell::new(false),
|
||||
log: RefCell::new(Vec::new()),
|
||||
log_bytes: Cell::new(0),
|
||||
written: RefCell::new(Vec::new()),
|
||||
written: RefCell::new(Written::default()),
|
||||
run: self.script_runs,
|
||||
name: console::line_name(&name),
|
||||
console: RefCell::default(),
|
||||
@@ -1888,7 +2000,20 @@ impl Session {
|
||||
commands: RefCell::default(),
|
||||
run_nanos: Cell::new(0),
|
||||
dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers),
|
||||
disk: RefCell::new(files::Disk::new(files.scope())),
|
||||
disk: RefCell::new(files::Disk::new(
|
||||
files.scope(),
|
||||
files::Setup {
|
||||
framed: self.script_frames,
|
||||
script: request.file.clone(),
|
||||
// The text with its included files, so a changed included file asks again.
|
||||
source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()),
|
||||
data_dir: self.script_data_dir.clone(),
|
||||
engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| {
|
||||
let m = m.borrow();
|
||||
(m.code.iter().cloned().collect(), m.code_full)
|
||||
}),
|
||||
},
|
||||
)),
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
@@ -1978,14 +2103,16 @@ impl Session {
|
||||
self.script_gone(key, console::Ending::Internal);
|
||||
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
|
||||
};
|
||||
if let Some(e) = job.host.dialogs.take_failure() {
|
||||
let picker_failed = job.host.disk.borrow_mut().failed.take();
|
||||
if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) {
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// A canceled request ends a sleep or a wait at this pump.
|
||||
if vectorcraft_doc::cancel::check().is_err() {
|
||||
self.script_stop.set();
|
||||
}
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
let picking = job.host.disk.borrow().picker.is_some();
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
@@ -2029,6 +2156,9 @@ impl Session {
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
job.host.disk.borrow_mut().picker = None;
|
||||
// The run fails already; a file it could not write is left out of `written`.
|
||||
let _ = job.host.flush_files();
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let (e, file) = located(&job.host, &job.realm, e);
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
@@ -2046,6 +2176,12 @@ impl Session {
|
||||
/// Makes the working copy the session's state: one undo step for each document whose art
|
||||
/// changed, nothing for the others.
|
||||
fn script_commit(&mut self, mut job: Job) -> Result<Value> {
|
||||
let unwritten = job.host.flush_files();
|
||||
if !unwritten.is_empty() {
|
||||
let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", "));
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 };
|
||||
return self.script_failed(job, &e);
|
||||
}
|
||||
// The working copy goes into the session; `job.world` holds the state before the run.
|
||||
job.world.swap(self);
|
||||
self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs);
|
||||
@@ -2109,11 +2245,12 @@ impl Session {
|
||||
"ok": true,
|
||||
"name": job.name,
|
||||
"changed": changed_names,
|
||||
"written": *host.written.borrow(),
|
||||
"written": host.written.borrow().paths,
|
||||
"log": *host.log.borrow(),
|
||||
"fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(),
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.end_job(job, false);
|
||||
self.script_report = Some(report.clone());
|
||||
@@ -2140,6 +2277,7 @@ impl Session {
|
||||
|
||||
const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
const INVALID_RESULT: &str = "the script left a document that cannot be kept";
|
||||
const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written";
|
||||
const JOB_GONE: &str = "the script's run is no longer available";
|
||||
const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped";
|
||||
// Text a script reads from the errors it catches, or that ends its run with its name and place.
|
||||
@@ -2168,12 +2306,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue
|
||||
"name": name,
|
||||
"line": e.line,
|
||||
"column": e.column,
|
||||
"written": *host.written.borrow(),
|
||||
"written": host.written.borrow().paths,
|
||||
"log": *host.log.borrow(),
|
||||
"fuelLeft": fuel_left,
|
||||
"fuelUsed": fuel_used,
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
if let (Some(file), Some(o)) = (file, report.as_object_mut()) {
|
||||
o.insert("file".into(), json!(file));
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ impl Session {
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
script_data_dir: None,
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
|
||||
@@ -255,6 +255,21 @@ impl Session {
|
||||
(r, settled)
|
||||
}
|
||||
|
||||
/// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings
|
||||
/// of the preview that keeping typing in progress applied, for its status bar.
|
||||
pub fn begin_interaction_warned(&mut self, label: &str) -> Result<Vec<String>> {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.begin_interaction(label));
|
||||
r.map(|()| settled)
|
||||
}
|
||||
|
||||
/// Keep typing in progress as one undo step, applying the preview Real-time Drawing off left
|
||||
/// unapplied, and end the Type tool's typing session → the applied preview's warnings. Nothing
|
||||
/// changes when no typing is in progress.
|
||||
pub fn keep_typing(&mut self) -> Result<Vec<String>> {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| if cmd::typing_in_progress(s) { cmd::settle_interaction(s) } else { Ok(()) });
|
||||
r.map(|()| settled)
|
||||
}
|
||||
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -2809,6 +2809,26 @@ fn an_isolated_compound_paths_member_moves_alone() {
|
||||
assert_eq!((x0(&s, outer), x0(&s, hole)), (5.0, 55.0), "the compound path selected: the whole ring");
|
||||
}
|
||||
|
||||
/// Rotate Bounding Box and Reset Bounding Box take the same objects as the transforms: a path of
|
||||
/// a compound path selected alone turns or squares its own box, and the compound path selected
|
||||
/// turns its box and its paths'.
|
||||
#[test]
|
||||
fn rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path() {
|
||||
let angle = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().bbox_angle;
|
||||
let mut s = session();
|
||||
let (c, outer, hole) = isolated_ring(&mut s);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap();
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (0.0, 0.0, 30.0), "only the hole's box turned");
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap();
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 40.0), "the compound path and its paths");
|
||||
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 0.0), "Reset squared only the hole's box");
|
||||
}
|
||||
|
||||
/// The X, Y, W and H of the Properties and Transform panels run `object.setBounds`, which takes the
|
||||
/// same objects as the other transforms: a path of a compound path selected alone sets its own
|
||||
/// box and leaves the ring around it (#4046). The hole is off-centre, and a plain rectangle
|
||||
|
||||
@@ -579,6 +579,157 @@ fn reset_bounding_box_squares_the_turned_members_of_a_square_group() {
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_the_box_and_leaves_the_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let art = anchors(&s, a);
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 90})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["angle"].as_f64()), (Some(1), Some(90.0)));
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(anchors(&s, a), art, "the art stays where it is");
|
||||
// The box is at 90°, so its width runs along the rectangle's 50 pt side.
|
||||
let b = selection_box(&s);
|
||||
assert!(near(b.angle, 90.0));
|
||||
assert!(near(b.rect.width(), 50.0) && near(b.rect.height(), 100.0), "{b:?}");
|
||||
// By an angle from the box's angle; absolute sets it; the result wraps to (-180, 180].
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": 20})).unwrap();
|
||||
assert!(near(angle(&s, a), 110.0));
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 200, "absolute": true})).unwrap();
|
||||
assert!(near(r["angle"].as_f64().unwrap(), -160.0) && near(angle(&s, a), -160.0));
|
||||
// A box already at the angle changes nothing and adds no step.
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -160, "absolute": true})).unwrap();
|
||||
assert_eq!(r["changed"], 0);
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 360})).unwrap();
|
||||
assert_eq!(r["changed"], 0);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// Undo turns the box back; Reset Bounding Box squares it.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 110.0));
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
|
||||
assert_eq!(anchors(&s, a), art);
|
||||
}
|
||||
|
||||
/// Turns that add up to 0 within the tolerance leave the box at exactly 0, so the box measures
|
||||
/// square to the page and Reset Bounding Box has nothing to square.
|
||||
#[test]
|
||||
fn rotate_bounding_box_back_to_zero_stores_zero() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
for by in [0.3, -0.1] {
|
||||
s.execute("object.rotateBoundingBox", &json!({"angle": by})).unwrap();
|
||||
}
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.2})).unwrap();
|
||||
assert_eq!((r["angle"].as_f64(), angle(&s, a)), (Some(0.0), 0.0), "{r}");
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0);
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// A negative zero is reported and stored as 0.
|
||||
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.0, "absolute": true})).unwrap();
|
||||
let got = r["angle"].as_f64().unwrap();
|
||||
assert!(got == 0.0 && got.is_sign_positive(), "{r}");
|
||||
assert_eq!(r["changed"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_gives_a_mixed_selection_one_angle() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = turned_rect(&mut s);
|
||||
sel(&mut s, &[a, b]);
|
||||
// The objects share no angle, so the box is square to the page and turns from 0.
|
||||
assert_eq!(selection_box(&s).angle, 0.0);
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 2);
|
||||
assert_eq!(undo_len(&s), n + 1, "one step for both");
|
||||
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
|
||||
assert!(near(selection_box(&s).angle, 10.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 0.0) && near(angle(&s, b), 45.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_the_objects_inside_a_group_with_it() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let art = (anchors(&s, a), anchors(&s, b));
|
||||
// The group and both members, as Reset Bounding Box counts them.
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 3);
|
||||
// The members keep their 20° relative to the group's box.
|
||||
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
|
||||
assert_eq!((anchors(&s, a), anchors(&s, b)), art);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, g), 0.0) && near(angle(&s, a), 20.0) && near(angle(&s, b), 20.0));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
|
||||
// After Ungroup the members still share a turned box.
|
||||
s.execute("object.ungroup", &json!({})).unwrap();
|
||||
assert!(near(selection_box(&s).angle, 50.0));
|
||||
}
|
||||
|
||||
/// The art of a linked opacity mask turns with its object; an unlinked mask's art keeps its angle.
|
||||
#[test]
|
||||
fn rotate_bounding_box_turns_a_linked_masks_art_only() {
|
||||
let mask_angle = |s: &Session, a: NodeId| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 2);
|
||||
assert!(near(angle(&s, a), 30.0) && near(mask_angle(&s, a), 30.0));
|
||||
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 1);
|
||||
assert!(near(angle(&s, a), 40.0) && near(mask_angle(&s, a), 30.0));
|
||||
}
|
||||
|
||||
/// Rotate Bounding Box and Reset Bounding Box act on the same boxes: after a turn of a group that
|
||||
/// holds an object with a linked opacity mask, Reset squares every box it turned.
|
||||
#[test]
|
||||
fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a, c]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let art = (anchors(&s, a), anchors(&s, c));
|
||||
// The group, the masked object, its mask's art and the other rectangle.
|
||||
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4);
|
||||
assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s));
|
||||
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4);
|
||||
assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s));
|
||||
assert_eq!((anchors(&s, a), anchors(&s, c)), art);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_bounding_box_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
|
||||
sel(&mut s, &[a]);
|
||||
let n = undo_len(&s);
|
||||
for p in [json!({}), json!({"angle": null}), json!({"angle": "30"}), json!({"angle": 30, "absolute": "yes"})] {
|
||||
assert!(s.execute("object.rotateBoundingBox", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!((angle(&s, a), undo_len(&s)), (0.0, n));
|
||||
// Nothing selected: the command is not enabled.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).is_err());
|
||||
}
|
||||
|
||||
/// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then
|
||||
/// released by `release`: nothing stands at an angle before or after the release.
|
||||
fn reset_then_release(make: &str, release: &str) -> Session {
|
||||
|
||||
@@ -120,8 +120,9 @@ fn a_blend_and_an_object_make_one_blend_with_more_keys() {
|
||||
}
|
||||
|
||||
/// Choosing the Blend tool again (its button, W, `tool.select`) finishes the blend: the first
|
||||
/// pick and the chain are dropped, and the document and the selection stay. Choosing another
|
||||
/// tool again keeps its work: the Pen's open path stays open.
|
||||
/// pick and the chain are dropped, and the document and the selection stay. The Pen chosen again
|
||||
/// ends the path it is drawing, as Escape does: the path stays open and the next click starts a
|
||||
/// new one.
|
||||
#[test]
|
||||
fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
let mut s = session();
|
||||
@@ -148,7 +149,7 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
click(&mut s, 20.0, 20.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
|
||||
assert_eq!(spec(&s, g).0, vec![b, c], "a was not added");
|
||||
// The Pen chosen again goes on drawing its open path.
|
||||
// The Pen chosen again ends its open path; the next click starts a new one.
|
||||
s.select_tool("pen", v).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let pen = |s: &mut Session, x: f64, y: f64| {
|
||||
@@ -156,16 +157,27 @@ fn choosing_the_blend_tool_again_finishes_the_blend() {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
|
||||
}
|
||||
};
|
||||
let anchors = |s: &Session, id| match node(s, id).kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
// With no path being drawn, choosing the Pen again changes nothing.
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().selection.objects.len()), (depth, 0));
|
||||
pen(&mut s, 100.0, 300.0);
|
||||
pen(&mut s, 200.0, 300.0);
|
||||
let p = s.doc().unwrap().selection.objects[0];
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
s.select_tool("pen", v).unwrap();
|
||||
assert_eq!(s.tool_id(), "pen", "the Pen stays chosen");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "ending the path adds no undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![p], "the path stays selected");
|
||||
pen(&mut s, 300.0, 300.0);
|
||||
let anchors = match node(&s, p).kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths[0].anchors.len(),
|
||||
_ => 0,
|
||||
};
|
||||
assert_eq!(anchors, 3, "the Pen keeps drawing the same path");
|
||||
assert_eq!(anchors(&s, p), vec![(2, false)], "the path stays open with its two anchors");
|
||||
let q = s.doc().unwrap().selection.objects[0];
|
||||
assert_ne!(q, p, "the click starts a new path");
|
||||
assert_eq!(anchors(&s, q), vec![(1, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -81,6 +81,224 @@ fn apply_and_remove_brush_with_undo() {
|
||||
assert!(s.execute("brush.apply", &json!({"name": "Nope"})).is_err());
|
||||
}
|
||||
|
||||
/// The own brush settings of the first stroke of `id`.
|
||||
fn own_options(s: &Session, id: NodeId) -> Value {
|
||||
Value::Object(node(s, id).appearance.stroke().map(|st| st.brush_options.clone()).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The height of the brush art of `id`, drawn along a level line.
|
||||
fn art_height(s: &Session, id: NodeId) -> f64 {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
vectorcraft_brush::pieces_bounds(&vectorcraft_brush::node_pieces(d, &node(s, id)).unwrap()).unwrap().height()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_change_one_path_and_leave_the_brush() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
let width = s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"].clone();
|
||||
select(&mut s, &[a]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("brush.objectOptions", &json!({"params": {"width": 50, "flip_along": false}})).unwrap();
|
||||
assert_eq!(r["changed"], json!([a.0]));
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}), "flip_along equals the brush's own value and is dropped");
|
||||
assert_eq!(own_options(&s, b), json!({}));
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"], width, "the brush keeps its width");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!((art_height(&s, a) * 2.0 - art_height(&s, b)).abs() < 1e-6, "{} vs {}", art_height(&s, a), art_height(&s, b));
|
||||
// The same settings again, and a call without params, change nothing and add no undo step.
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap()["changed"], json!([]));
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"width": 50.0}));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
// An edit of the brush reaches the settings the path does not set.
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 200, "flip_across": true}})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// The settings are saved in the native file.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let st = back.node(a).and_then(|n| n.appearance.stroke().cloned()).unwrap();
|
||||
assert_eq!(Value::Object(st.brush_options), json!({"width": 50.0}));
|
||||
// Undo puts the path back on the brush's settings.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// Reset clears them, and so do applying a brush and removing it.
|
||||
s.execute("brush.objectOptions", &json!({"reset": true})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.remove", &json!({})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
// Stroke Options' brush change clears them as well, and keeping the same brush keeps them.
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("stroke.setAdvanced", &json!({"brush": "Arrow"})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"overlap": true}));
|
||||
s.execute("stroke.setAdvanced", &json!({"brush": null})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
// Asking for the settings changes nothing, even when the brush has come to equal them.
|
||||
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap();
|
||||
s.execute("brush.options", &json!({"name": "Arrow", "params": {"overlap": true}})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"overlap": true}));
|
||||
assert_eq!(own_options(&s, a), json!({"overlap": true}));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_null_items_keep_each_paths_own() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [a.0, b.0]})).unwrap();
|
||||
let brush_size = s.execute("brush.get", &json!({"name": "Confetti"})).unwrap()["size"].clone();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"size": [50, 80]}})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"size": [60, 120]}})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
// Only the smallest size changes: each path keeps its own largest size.
|
||||
let r = s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"size": [40, null]}})).unwrap();
|
||||
assert_eq!(r["changed"], json!([a.0, b.0]));
|
||||
assert_eq!(own_options(&s, a)["size"], json!([40.0, 80.0]));
|
||||
assert_eq!(own_options(&s, b)["size"], json!([40.0, 120.0]));
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for both paths");
|
||||
// A path without its own value keeps the brush's item.
|
||||
let c = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti", "ids": [c.0]})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [c.0], "params": {"size": [null, 150]}})).unwrap();
|
||||
assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}");
|
||||
}
|
||||
|
||||
/// The size mode the first stroke of `id`, painted with Confetti, draws with.
|
||||
fn confetti_size_mode(s: &Session, id: NodeId) -> vectorcraft_brush::Variation {
|
||||
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let b = lib.iter().find(|b| b.name == "Confetti").unwrap();
|
||||
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
|
||||
vectorcraft_brush::BrushKind::Scatter(sc) => sc.modes()[0],
|
||||
k => panic!("not a scatter brush: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keep_the_modes_each_path_draws_with() {
|
||||
use vectorcraft_brush::Variation;
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.apply", &json!({"name": "Confetti"})).unwrap();
|
||||
// Confetti's sizes vary at random from 60% to 140%; the second path's follow the pressure.
|
||||
select(&mut s, &[b]);
|
||||
s.execute("brush.objectOptions", &json!({"params": {"modes": ["pressure", null, null, null]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
|
||||
// One size with no mode keeps each path's mode.
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("brush.objectOptions", &json!({"params": {"size": [80, 80]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure));
|
||||
assert_eq!(own_options(&s, a)["size"], json!([80.0, 80.0]));
|
||||
// A mode the params give is set on each path.
|
||||
s.execute("brush.objectOptions", &json!({"params": {"size": [70, 90], "modes": ["fixed", null, null, null]}})).unwrap();
|
||||
assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed));
|
||||
}
|
||||
|
||||
/// The widths (%) the first stroke of `id`, painted with Arrow, draws with at the lightest and the
|
||||
/// heaviest pressure.
|
||||
fn arrow_width_range(s: &Session, id: NodeId) -> (f64, f64) {
|
||||
let lib = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let b = lib.iter().find(|b| b.name == "Arrow").unwrap();
|
||||
match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind {
|
||||
vectorcraft_brush::BrushKind::Art(a) => a.width_range(),
|
||||
k => panic!("not an art brush: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_changes() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let b = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0]})).unwrap();
|
||||
// Both widths follow the pressure; the first path's largest width is its width, the second
|
||||
// path's is its own.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100, "width_mode": "pressure"}})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 100, "width_mode": "pressure", "width_max": 150}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((100.0, 100.0), (100.0, 150.0)));
|
||||
// The width the path has already changes nothing.
|
||||
let steps = undo_steps(&s);
|
||||
assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100}})).unwrap()["changed"], json!([]));
|
||||
assert_eq!(own_options(&s, a), json!({"width_mode": "pressure"}));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// A new smallest width leaves each path's largest width as it was.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 50}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((50.0, 100.0), (50.0, 150.0)));
|
||||
// A largest width the params give is set on each path.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 40, "width_max": 120}})).unwrap();
|
||||
assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 50}})).unwrap();
|
||||
let extend = |s: &mut Session, brush: &str, points: Value| {
|
||||
s.execute("brush.freehand", &json!({"points": points, "style": "brush", "brush": brush, "extend": {"id": a.0}})).unwrap();
|
||||
};
|
||||
// Continuing the path with its own brush keeps the settings.
|
||||
extend(&mut s, "Arrow", json!([[0, 0], [40, 30], [80, 10]]));
|
||||
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
|
||||
// Another brush, with a stroke or with only the brush changing, clears them.
|
||||
extend(&mut s, "Diamonds", json!([[0, 0]]));
|
||||
assert_eq!(brush_of(&s, a).as_deref(), Some("Diamonds"));
|
||||
assert_eq!(own_options(&s, a), json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_keys_convert_with_the_document() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
let key = json!({"model": "rgb", "r": 0.2, "g": 0.6, "b": 0.3});
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"colorization": {"method": "hueShift", "key": key}}})).unwrap();
|
||||
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("rgb"));
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("cmyk"), "{}", own_options(&s, a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_of_selected_object_refuse_what_they_cannot_set() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s);
|
||||
let c = line(&mut s);
|
||||
let plain = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "3 pt. Round", "ids": [c.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let err = |s: &mut Session, p: Value| s.execute("brush.objectOptions", &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [plain.0], "params": {"width": 50}})).contains("brush"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0, c.0], "params": {"width": 50}})).contains("different types"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "params": {"angle": 10}})).contains("angle"));
|
||||
assert!(!err(&mut s, json!({"ids": [a.0], "params": {"width": "wide"}})).is_empty());
|
||||
assert!(!err(&mut s, json!({"ids": [a.0], "params": [1]})).is_empty());
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "params": {"width": 50}, "reset": true})).contains("reset"));
|
||||
assert!(err(&mut s, json!({"ids": [a.0], "reset": "yes"})).contains("reset"));
|
||||
s.execute("brush.apply", &json!({"name": "Bristle Round", "ids": [c.0]})).unwrap();
|
||||
let steps_bristle = undo_steps(&s);
|
||||
assert!(err(&mut s, json!({"ids": [c.0], "params": {"size": 2}})).contains("bristle"));
|
||||
assert_eq!(undo_steps(&s), steps_bristle);
|
||||
assert_eq!(steps + 1, steps_bristle, "only the bristle brush's apply added a step");
|
||||
// Values outside their ranges are clamped, as brush.options clamps them.
|
||||
s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 1e308}})).unwrap();
|
||||
assert_eq!(own_options(&s, a), json!({"width": 1000.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_adds_a_stroke_when_missing_and_reaches_into_groups() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() {
|
||||
assert_eq!(layer_children(&s), 1);
|
||||
}
|
||||
|
||||
/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the
|
||||
/// document, its undo history and the selection as they were; a click that merges shows no status.
|
||||
#[test]
|
||||
fn shape_builder_click_that_builds_nothing_shows_why() {
|
||||
use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS};
|
||||
let mut s = session();
|
||||
let (a, _) = two(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap()
|
||||
};
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty())
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]);
|
||||
assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]);
|
||||
assert_eq!(state(&s), before, "nothing changed");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]);
|
||||
assert_eq!(state(&s), before, "nothing changed");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status");
|
||||
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
|
||||
assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status");
|
||||
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
|
||||
}
|
||||
|
||||
/// A click of the Shape Builder merges over the map the tool built for the hover, as does the
|
||||
/// command over the same inputs with the same gap; another gap needs a map of its own.
|
||||
#[test]
|
||||
|
||||
@@ -3225,6 +3225,30 @@ fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `path.eraseSegments` refuses a `width` outside 0.001 to 1000 pt, and nothing changes. The ends of
|
||||
/// the range and null still erase.
|
||||
#[test]
|
||||
fn path_eraser_width_outside_its_range_is_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let drag = json!({"points": [[150, 90], [150, 110]]});
|
||||
for x in [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)] {
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
refuses_with(&mut s, "path.eraseSegments", &with(&drag, json!({"width": x})), "`width` must be from 0.001 to 1000");
|
||||
assert_eq!(s.doc().unwrap().selection, sel, "width {x} changed the selection");
|
||||
}
|
||||
for x in [json!(0.001), json!(1000), json!(null)] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_steps(&s);
|
||||
s.execute("path.eraseSegments", &with(&drag, json!({"width": x}))).unwrap_or_else(|e| panic!("width {x}: {e}"));
|
||||
assert!(s.doc().unwrap().doc != before, "width {x} erased nothing");
|
||||
assert_eq!(undo_steps(&s), undo + 1, "width {x}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness,
|
||||
/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change
|
||||
/// nothing; null is read as the key left out.
|
||||
|
||||
@@ -454,6 +454,24 @@ fn a_stroke_weight_change_leaves_each_members_own_fill_and_stroke_colour() {
|
||||
assert_eq!((fill(&s, a), fill(&s, c)), (a_fill, c_fill));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brush_change_clears_each_members_own_brush_settings_and_other_changes_keep_them() {
|
||||
let mut s = session();
|
||||
let [a, b, c, ..] = squares(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0, c.0]})).unwrap();
|
||||
s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 50}})).unwrap();
|
||||
let own = |s: &Session, id: NodeId| Value::Object(node(s, id).appearance.stroke().unwrap().brush_options.clone());
|
||||
assert_eq!(own(&s, b), json!({"width": 50.0}));
|
||||
start(&mut s, a, json!({}));
|
||||
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
|
||||
assert_eq!(own(&s, b), json!({"width": 50.0}), "a weight change keeps the copy's own settings");
|
||||
s.execute("brush.apply", &json!({"name": "Diamonds"})).unwrap();
|
||||
for id in [a, b, c] {
|
||||
assert_eq!(node(&s, id).appearance.stroke().unwrap().brush.as_deref(), Some("Diamonds"));
|
||||
assert_eq!(own(&s, id), json!({}), "the settings for the old brush go with it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_colour_change_reaches_the_fills_and_not_the_strokes() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -146,6 +146,31 @@ fn type_tool_inserts_at_its_caret_and_deletes_the_graphic_whole() {
|
||||
assert_eq!(inline_count(&obj(&s, id)), 1);
|
||||
}
|
||||
|
||||
/// With Performance › Real-time Drawing and Editing off, the typing waits for its session to end:
|
||||
/// a graphic inserted while typing applies it first, as a step of its own, and goes in at the
|
||||
/// caret after it.
|
||||
#[test]
|
||||
fn inserting_while_deferred_typing_keeps_the_typing() {
|
||||
let mut s = session();
|
||||
s.prefs.real_time_drawing = false;
|
||||
// The new type starts empty: the caret after "Pay " is past the end of the text until the
|
||||
// typing is applied.
|
||||
s.prefs.placeholder_text = false;
|
||||
circle_symbol(&mut s, "Mana", 10.0);
|
||||
s.execute("symbol.setCurrent", &json!({"name": "Mana"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
s.tool_text("Pay ", v).unwrap();
|
||||
s.execute("text.insertInline", &json!({})).unwrap();
|
||||
assert_eq!(obj(&s, id).plain_text(), format!("Pay {INLINE_CHAR}"));
|
||||
let labels: Vec<String> = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
|
||||
assert_eq!(labels[labels.len() - 2..], ["Typing", "Insert Inline Symbol"], "{labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_graphics_follow_their_symbol() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2377,6 +2377,255 @@ fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_ro
|
||||
every(&mut s, true, Some(&inside));
|
||||
}
|
||||
|
||||
/// The native document a file of `format` carries: the file itself, a PDF's or `.ai` file's
|
||||
/// editing data, or an EPS file's.
|
||||
fn carried_document(format: &str, bytes: &[u8]) -> Document {
|
||||
let native = if bytes.starts_with(b"%PDF") {
|
||||
vectorcraft_pdf::editing(bytes).expect("editing data").data
|
||||
} else if format == "eps" {
|
||||
vectorcraft_eps::native(bytes).expect("native document")
|
||||
} else {
|
||||
bytes.to_vec()
|
||||
};
|
||||
vectorcraft_format::load(&native).unwrap()
|
||||
}
|
||||
|
||||
/// A confined caller: every output that carries the native document (a native file or template, a
|
||||
/// `.ai` or EPS file, a PDF with Preserve Editing) of a document that links an image
|
||||
/// file outside the read roots is refused before a file or folder is written, with an error that
|
||||
/// names no file or folder, and the document keeps the link.
|
||||
#[test]
|
||||
fn confined_native_output_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("native-image-away");
|
||||
let home = Folder::new("native-image-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [a.0]})).unwrap();
|
||||
let own = home.file("own.vectorcraft");
|
||||
s.execute("file.saveAs", &json!({"path": own})).unwrap();
|
||||
let before = std::fs::read(&own).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()];
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd);
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let file = |name: &str| home.file(name);
|
||||
let out = file("out");
|
||||
refused(&mut s, "document.serialize", json!({}));
|
||||
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
|
||||
refused(&mut s, "document.serialize", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
|
||||
refused(&mut s, "document.exportSelection", json!({"format": format}));
|
||||
}
|
||||
refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")}));
|
||||
refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")}));
|
||||
refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")}));
|
||||
refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")}));
|
||||
refused(&mut s, "document.exportPdf", json!({}));
|
||||
refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")}));
|
||||
refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")}));
|
||||
refused(&mut s, "document.save", json!({}));
|
||||
refused(&mut s, "document.save", json!({"path": file("save.pdf")}));
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")}));
|
||||
// A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says.
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false}));
|
||||
refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")}));
|
||||
refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")}));
|
||||
refused(&mut s, "file.saveAsTemplate", json!({}));
|
||||
refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
|
||||
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]}));
|
||||
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]}));
|
||||
assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was");
|
||||
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(written, ["own.vectorcraft"]);
|
||||
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
|
||||
}
|
||||
|
||||
/// A confined caller's native outputs are refused when the document they carry names a file
|
||||
/// outside the read roots only as a data set's image, or holds stored brushes that cannot be read.
|
||||
/// Outputs that carry no native document (a PDF without Preserve Editing, a PDF or `.ai` file of
|
||||
/// some artboards or of the art's bounds, a legacy `.ai` file, an image, an SVG without Preserve
|
||||
/// Editing) are written, and so is a native file whose data set image is inside the read roots, or
|
||||
/// any data set image without roots.
|
||||
#[test]
|
||||
fn confined_native_output_refuses_a_data_set_image_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("native-dataset-away");
|
||||
let home = Folder::new("native-dataset-home");
|
||||
let outside = away.file("photo.png");
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
let set_image = |s: &mut Session, path: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect();
|
||||
doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }];
|
||||
};
|
||||
set_image(&mut s, &outside);
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{cmd} {p}: {e}");
|
||||
};
|
||||
let written = |s: &mut Session, p: Value| {
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap_or_else(|e| panic!("{p}: {e}"));
|
||||
};
|
||||
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
|
||||
refused(&mut s, "document.serialize", json!({"format": format}));
|
||||
}
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "preserveEditing": true}));
|
||||
refused(&mut s, "document.exportPdf", json!({}));
|
||||
for p in [
|
||||
json!({"format": "pdf", "preserveEditing": false}),
|
||||
json!({"format": "pdf", "useArtboards": false}),
|
||||
json!({"format": "pdf", "range": "2"}),
|
||||
json!({"format": "ai", "artboards": [1]}),
|
||||
json!({"format": "ai", "useArtboards": false}),
|
||||
json!({"format": "ai", "aiVersion": "7"}),
|
||||
json!({"format": "png"}),
|
||||
json!({"format": "svg"}),
|
||||
] {
|
||||
written(&mut s, p);
|
||||
}
|
||||
// Without roots, the native document keeps the data set's image as stored.
|
||||
let r = s.execute("document.serialize", &json!({})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let carried = carried_document("vectorcraft", &bytes);
|
||||
assert_eq!(carried.variables.datasets[0].values["Photo"], vectorcraft_doc::DataValue::Image(outside.clone()));
|
||||
// An image inside the read roots.
|
||||
set_image(&mut s, &home.file("photo.png"));
|
||||
written(&mut s, json!({"format": "vectorcraft"}));
|
||||
// Stored brushes that cannot be read: their links cannot be checked.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert(vectorcraft_brush::DOC_KEY.into(), json!(["not a brush"]));
|
||||
refused(&mut s, "document.serialize", json!({"format": "vectorcraft"}));
|
||||
written(&mut s, json!({"format": "png"}));
|
||||
}
|
||||
|
||||
/// A confined caller's Export for Screens rows that write an artboard alone (native, `.ai` and EPS
|
||||
/// files) are checked against that artboard's document: an image linked outside the read roots
|
||||
/// on another artboard does not refuse them, and one on the artboard does.
|
||||
#[test]
|
||||
fn confined_screens_rows_check_the_artboard_each_file_holds() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("screens-board-away");
|
||||
let home = Folder::new("screens-board-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
place(&mut s, &photo);
|
||||
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2010, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
for format in ["vectorcraft", "ai", "eps"] {
|
||||
let p = |range: &str| json!({"range": range, "formats": [{"format": format}]});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("2"))).unwrap_or_else(|e| panic!("{format}: {e}"));
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{format}: {r}");
|
||||
let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("1"))).expect_err(format).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{format}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first
|
||||
/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does
|
||||
/// not refuse it, and one in the first asset does.
|
||||
#[test]
|
||||
fn confined_single_file_pdf_checks_the_document_it_carries() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("single-pdf-away");
|
||||
let home = Folder::new("single-pdf-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
let placed = place(&mut s, &photo);
|
||||
let mut assets = vec![];
|
||||
for id in [rect, placed] {
|
||||
assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap());
|
||||
}
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
|
||||
let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let reversed = [assets[1], assets[0]];
|
||||
let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
}
|
||||
|
||||
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
|
||||
/// Preserve Editing, a package's document) carry the document without the Export for Screens
|
||||
/// folder when it is outside the read roots, with the other export settings and the art; the open
|
||||
/// document keeps the folder. A folder inside the roots, and any folder without roots, stays.
|
||||
#[test]
|
||||
fn confined_native_output_leaves_out_an_export_folder_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("native-export-folder-away");
|
||||
let home = Folder::new("native-export-folder-home");
|
||||
let outside = away.0.to_string_lossy().into_owned();
|
||||
let inside = home.file("screens");
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
s.execute("file.saveAs", &json!({"path": home.file("own.vectorcraft")})).unwrap();
|
||||
let set_folder = |s: &mut Session, folder: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
|
||||
};
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let check = |d: &Document, folder: Option<&str>, what: &str| {
|
||||
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
|
||||
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
|
||||
assert!(d.node(rect).is_some(), "{what}: no art");
|
||||
};
|
||||
let package = home.file("package");
|
||||
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
|
||||
let run = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
|
||||
r.unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
};
|
||||
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
|
||||
let r = run(s, "document.serialize", json!({"format": format}));
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
check(&carried_document(format, &bytes), folder, &format!("{format} serialize"));
|
||||
}
|
||||
let pdf = home.file("direct.pdf");
|
||||
run(s, "document.exportPdf", json!({"path": pdf}));
|
||||
check(&carried_document("pdf", &std::fs::read(&pdf).unwrap()), folder, "exportPdf");
|
||||
let eps = home.file("copy.eps");
|
||||
run(s, "file.saveCopy", json!({"path": eps}));
|
||||
check(&carried_document("eps", &std::fs::read(&eps).unwrap()), folder, "eps copy");
|
||||
let _ = std::fs::remove_dir_all(&package);
|
||||
run(s, "file.package", json!({"folder": package, "report": false, "copyFonts": false}));
|
||||
let packaged = std::fs::read(Path::new(&package).join("own Folder").join("own.vectorcraft")).unwrap();
|
||||
check(&vectorcraft_format::load_file(&packaged).unwrap().doc, folder, "package");
|
||||
};
|
||||
set_folder(&mut s, &outside);
|
||||
every(&mut s, true, None);
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
|
||||
every(&mut s, false, Some(&outside));
|
||||
set_folder(&mut s, &inside);
|
||||
every(&mut s, true, Some(&inside));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
|
||||
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
|
||||
/// written. Any output that names no file is written.
|
||||
|
||||
@@ -203,6 +203,140 @@ fn unembed_of_pixels_that_cant_be_read_writes_no_file() {
|
||||
assert!(image(&s, id).link.is_none());
|
||||
}
|
||||
|
||||
/// The files of folder `dir`, sorted by name.
|
||||
fn files_in(dir: &str) -> Vec<String> {
|
||||
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
/// The path of the file `name` in folder `dir`.
|
||||
fn file_in(dir: &str, name: &str) -> String {
|
||||
std::path::Path::new(dir).join(name).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Several images unembed into one folder: each gets a new file named after it (a taken name
|
||||
/// numbered, a file already there never replaced), links to it and keeps its bounds, linked images
|
||||
/// are skipped, and one undo step makes them embedded again while the files stay.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step() {
|
||||
let dir = Folder::new("unembed-folder");
|
||||
let out = dir.file("out");
|
||||
for sub in ["a", "b", "out"] {
|
||||
std::fs::create_dir_all(dir.file(sub)).unwrap();
|
||||
}
|
||||
let (red, blue) = (png(60, 30, RED), png(40, 20, BLUE));
|
||||
write(&dir.file("a/photo.png"), &red);
|
||||
write(&dir.file("b/photo.png"), &blue);
|
||||
write(&dir.file("a/linked.png"), &red);
|
||||
let kept = b"not an image".to_vec();
|
||||
write(&file_in(&out, "photo.png"), &kept);
|
||||
let mut s = session();
|
||||
let a = place_embedded(&mut s, &dir.file("a/photo.png"));
|
||||
let b = place_embedded(&mut s, &dir.file("b/photo.png"));
|
||||
let linked = place(&mut s, &dir.file("a/linked.png"));
|
||||
let linked_path = image(&s, linked).link.unwrap().path;
|
||||
let (bounds_a, bounds_b) = (bounds(&s, a), bounds(&s, b));
|
||||
let undo_before = s.doc().unwrap().history.undo.len();
|
||||
let r = run(&mut s, "links.unembed", json!({"ids": [a.0, linked.0, b.0], "folder": out}));
|
||||
let (path_a, path_b) = (file_in(&out, "photo 2.png"), file_in(&out, "photo 3.png"));
|
||||
assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": path_a}, {"id": b.0, "path": path_b}], "skipped": [linked.0]}));
|
||||
assert_eq!(files_in(&out), ["photo 2.png", "photo 3.png", "photo.png"]);
|
||||
assert_eq!(std::fs::read(file_in(&out, "photo.png")).unwrap(), kept, "a file already there is not replaced");
|
||||
assert_eq!(std::fs::read(&path_a).unwrap(), red);
|
||||
assert_eq!(std::fs::read(&path_b).unwrap(), blue);
|
||||
assert_eq!(image(&s, a).link.unwrap().path, path_a);
|
||||
assert_eq!(image(&s, b).link.unwrap().path, path_b);
|
||||
assert_eq!(image(&s, linked).link.unwrap().path, linked_path, "a linked image is left as it is");
|
||||
assert_eq!((bounds(&s, a), bounds(&s, b)), (bounds_a, bounds_b));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "one undo step");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none(), "both embedded again");
|
||||
assert_eq!(files_in(&out).len(), 3, "undo leaves the files");
|
||||
// `ids` of one image without `folder` is `id`: the bytes, and nothing changes.
|
||||
let one = run(&mut s, "links.unembed", json!({"ids": [a.0]}));
|
||||
assert_eq!(one, run(&mut s, "links.unembed", json!({"id": a.0})));
|
||||
assert!(one["dataBase64"].is_string(), "{one}");
|
||||
assert!(image(&s, a).link.is_none());
|
||||
// With no ids, the selected embedded images.
|
||||
s.doc_mut().unwrap().selection.objects = vec![b, linked];
|
||||
let r = run(&mut s, "links.unembed", json!({"folder": out}));
|
||||
assert_eq!(r, json!({"unembedded": [{"id": b.0, "path": file_in(&out, "photo 4.png")}], "skipped": []}));
|
||||
assert_eq!(std::fs::read(file_in(&out, "photo 4.png")).unwrap(), blue);
|
||||
// `id` with `folder` is `ids` of that one image.
|
||||
let r = run(&mut s, "links.unembed", json!({"id": a.0, "folder": out}));
|
||||
assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": file_in(&out, "photo 5.png")}], "skipped": []}));
|
||||
assert_eq!(image(&s, a).link.unwrap().path, file_in(&out, "photo 5.png"));
|
||||
}
|
||||
|
||||
/// A batch that fails part way writes no file and changes nothing; requests that don't fit the
|
||||
/// command are refused before anything is written.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_that_fails_leaves_no_file_and_no_change() {
|
||||
let dir = Folder::new("unembed-folder-fail");
|
||||
let out = dir.file("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
write(&dir.file("one.png"), &png(60, 30, RED));
|
||||
write(&dir.file("two.png"), &png(60, 30, BLUE));
|
||||
let mut s = session();
|
||||
let a = place_embedded(&mut s, &dir.file("one.png"));
|
||||
let b = place_embedded(&mut s, &dir.file("two.png"));
|
||||
// The second image's pixels can't be read: the first one's file is removed again.
|
||||
let key = image(&s, b).key;
|
||||
let saved = s.doc().unwrap().doc.images.get(&key).cloned().unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key.clone(), vectorcraft_doc::ImageBlob::png(png_header(60, 30)));
|
||||
let undo_before = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("links.unembed", &json!({"ids": [a.0, b.0], "folder": out})).unwrap_err();
|
||||
assert!(e.to_string().ends_with("the image's pixels can't be read"), "{e}");
|
||||
assert!(files_in(&out).is_empty(), "no file left behind");
|
||||
assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo_before);
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key, saved);
|
||||
|
||||
let refused = |s: &mut Session, p: Value| s.execute("links.unembed", &p).unwrap_err().to_string();
|
||||
let both = "give `path` or `folder`, not both";
|
||||
assert!(refused(&mut s, json!({"ids": [a.0, a.0], "folder": out})).ends_with("`ids` names an object twice"));
|
||||
assert!(refused(&mut s, json!({"id": a.0, "path": file_in(&out, "x.png"), "folder": out})).ends_with(both));
|
||||
assert!(refused(&mut s, json!({"ids": [a.0], "path": file_in(&out, "x.png"), "folder": out})).ends_with(both));
|
||||
assert!(refused(&mut s, json!({"ids": [a.0, b.0]})).ends_with("missing `folder`"));
|
||||
assert!(refused(&mut s, json!({"ids": []})).ends_with("missing `folder`"));
|
||||
assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0], "folder": out})).ends_with("give `id` or `ids`, not both"));
|
||||
assert!(refused(&mut s, json!({"id": a.0, "ids": [b.0]})).ends_with("give `id` or `ids`, not both"));
|
||||
assert!(refused(&mut s, json!({"ids": [a.0], "folder": 5})).ends_with("`folder` must be a string"));
|
||||
assert!(refused(&mut s, json!({"ids": [], "folder": out})).ends_with("select an image"));
|
||||
let file = dir.file("one.png");
|
||||
assert!(refused(&mut s, json!({"ids": [a.0], "folder": file})).ends_with(&format!("{file} is not a folder")));
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
let rect = s.doc().unwrap().selection.objects[0];
|
||||
assert!(refused(&mut s, json!({"ids": [a.0, rect.0], "folder": out})).ends_with(&format!("object {} is not an image", rect.0)));
|
||||
assert!(files_in(&out).is_empty(), "nothing written for a refused request");
|
||||
run(&mut s, "links.unembed", json!({"ids": [a.0], "folder": out}));
|
||||
assert!(refused(&mut s, json!({"ids": [a.0], "folder": out})).ends_with(&format!("image {} is linked already", a.0)));
|
||||
assert_eq!(files_in(&out), ["one.png"]);
|
||||
}
|
||||
|
||||
/// Under automation write roots, a folder outside them takes no file.
|
||||
#[test]
|
||||
fn unembed_to_a_folder_outside_the_write_roots_is_refused() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
let dir = Folder::new("unembed-folder-roots");
|
||||
let (inside, outside) = (dir.file("inside"), dir.file("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
write(&file_in(&inside, "pic.png"), &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let id = place_embedded(&mut s, &file_in(&inside, "pic.png"));
|
||||
let roots = AutomationRoots::new(&[dir.0.as_path()], &[std::path::Path::new(&inside)]).unwrap();
|
||||
let p = json!({"ids": [id.0], "folder": outside});
|
||||
let e = confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap_err().to_string();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
assert!(files_in(&outside).is_empty());
|
||||
assert!(image(&s, id).link.is_none());
|
||||
let p = json!({"ids": [id.0], "folder": inside});
|
||||
confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap();
|
||||
assert!(image(&s, id).link.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_to_selects_the_image() {
|
||||
let dir = Folder::new("goto");
|
||||
|
||||
@@ -613,3 +613,29 @@ fn an_arrow_press_without_a_drag_keeps_mixed_radii() {
|
||||
assert_eq!(radii, before, "each corner keeps its radius");
|
||||
assert!(kinds.iter().all(|k| *k == CornerKind::InvertedRound), "{kinds:?}");
|
||||
}
|
||||
|
||||
/// A double-click on a corner widget with the Rectangle tool asks the frontend for the Transform
|
||||
/// panel, and leaves the document, its undo history, the selection and the tool as they were.
|
||||
#[test]
|
||||
fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel() {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
let (mut s, id) = session();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show");
|
||||
let at = w.visible().next().expect("a widget");
|
||||
let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len());
|
||||
let mut asked = vec![];
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap());
|
||||
}
|
||||
assert_eq!(asked, vec![UiRequest::Panel("transform".into())]);
|
||||
let st = s.doc().unwrap();
|
||||
assert!(*st.doc == *doc, "the document is unchanged");
|
||||
assert_eq!(st.selection, selection);
|
||||
assert_eq!(st.history.undo.len(), steps, "no undo step");
|
||||
assert!(st.interaction.is_none());
|
||||
assert_eq!(s.tool_id(), "rectangle");
|
||||
}
|
||||
|
||||
@@ -1557,6 +1557,28 @@ fn a_random_brush_in_the_tile_art_draws_every_tile_alike() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_set_to_random_by_its_own_brush_options_draws_every_tile_alike() {
|
||||
// The brush scatters at fixed values; the tile path's own settings (Options of Selected
|
||||
// Object) make it scatter at random, so the expanded tiles must still match the canvas.
|
||||
let mut s = session();
|
||||
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 12, "height": 12}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "paint.setFill", json!({"none": true}));
|
||||
run(&mut s, "paint.setStroke", json!({"color": "#000000"}));
|
||||
run(&mut s, "brush.apply", json!({"name": "Confetti"}));
|
||||
run(&mut s, "brush.options", json!({"name": "Confetti", "params": {"modes": ["fixed", "fixed", "fixed", "fixed"]}}));
|
||||
run(&mut s, "brush.objectOptions", json!({"ids": [tile], "params": {"modes": ["random", "random", "random", "random"]}}));
|
||||
run(&mut s, "object.pattern.make", json!({"ids": [tile], "name": "Confetti", "width": 60, "height": 60, "edit": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [tile]}));
|
||||
run(&mut s, "edit.clear", json!({}));
|
||||
run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 160, "height": 160}));
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Confetti"}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
let before = render(&s);
|
||||
expand_to_tiles(&mut s);
|
||||
assert_eq!(differing(&before, &render(&s), 64), 0, "every tile as on the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roughen_in_the_tile_art_of_a_scaled_pattern_keeps_its_detail() {
|
||||
// Roughen's detail is per inch: the canvas roughens the 10 pt square and scales the tile, so
|
||||
|
||||
@@ -405,6 +405,66 @@ fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() {
|
||||
assert_eq!(r["links"], 1, "{r}");
|
||||
}
|
||||
|
||||
/// A confined request packages no linked file it would copy as it is (a PDF with Preserve Editing,
|
||||
/// or a native document it does not rewrite) whose native document keeps an Export for Screens
|
||||
/// folder outside its read roots: the package is refused before anything is written, with an error
|
||||
/// that names no file or folder. A native document the package rewrites leaves the folder out, a
|
||||
/// folder inside the roots is packaged, and the person's package copies every file.
|
||||
#[test]
|
||||
fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root() {
|
||||
let away = Folder::new("package-folder-away");
|
||||
let home = Folder::new("package-folder-home");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned()];
|
||||
let out = home.file("out");
|
||||
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = package(s, p.clone()).expect_err("refused");
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked file's export folder is outside the read roots"), "{p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{p} names {h}: {e}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out).exists(), "{p}");
|
||||
};
|
||||
let mut part = session();
|
||||
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
|
||||
std::fs::create_dir_all(home.0.join("art")).unwrap();
|
||||
let native = home.file("art/part.vectorcraft");
|
||||
let pdf = home.file("art/part.pdf");
|
||||
let keep = |part: &mut Session, folder: &str| {
|
||||
std::sync::Arc::make_mut(&mut part.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap();
|
||||
save(part, &native);
|
||||
let r = run(part, "document.serialize", json!({"format": "pdf"}));
|
||||
write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
};
|
||||
keep(&mut part, &away.0.to_string_lossy());
|
||||
let poster = |placed: &str| {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
s
|
||||
};
|
||||
let mut s = poster(&pdf);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
let mut s = poster(&native);
|
||||
refused(&mut s, json!({"folder": out, "relink": false}));
|
||||
// Rewritten, the copy leaves the folder out.
|
||||
let r = package(&mut s, json!({"folder": out})).unwrap();
|
||||
assert_eq!(r["links"], 1, "{r}");
|
||||
let copied = std::fs::read(std::path::Path::new(&out).join("poster Folder/Links/part.vectorcraft")).unwrap();
|
||||
assert_eq!(vectorcraft_format::load_file(&copied).unwrap().doc.export_settings.get("folder"), None);
|
||||
std::fs::remove_dir_all(&out).unwrap();
|
||||
// A folder inside the read roots.
|
||||
keep(&mut part, &home.file("screens"));
|
||||
let mut s = poster(&pdf);
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
|
||||
@@ -533,6 +533,133 @@ fn offset_path_stops_after_the_first_failure() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A straight line, closed as the Shape Modes close open paths, encloses no area, so it does not
|
||||
/// change the result's shape: Unite, Minus Front, Exclude and Minus Back still give the 100 pt square's area
|
||||
/// (with a line in a group selected beside it, the group's square too), and the reply carries a
|
||||
/// warning that names Outline Stroke, as it does with the line in a compound path or in a group
|
||||
/// selected alone; where the line leaves nothing (Intersect, the backmost object in Minus Front, or
|
||||
/// the frontmost in Minus Back), the error names it, and where the other objects leave nothing
|
||||
/// anyway, a flat closed path included, it doesn't. An open evenodd square traced twice is the same. An open path
|
||||
/// that encloses an area once closed (a bow tie whose lobes cancel in signed area included), closed
|
||||
/// shapes alone, and Divide, where a line cuts, give no warning (#7849).
|
||||
#[test]
|
||||
fn shape_modes_report_lines_that_enclose_no_area() {
|
||||
use crate::cmd::SHAPE_MODE_OPEN_PATH_NO_AREA;
|
||||
fn id_of(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
fn line_of(s: &mut Session) -> NodeId {
|
||||
id_of(s.execute("shape.line", &json!({"x1": 20, "y1": 50, "x2": 80, "y2": 50})).unwrap())
|
||||
}
|
||||
fn vee_of(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([{"x": 20, "y": 50}, {"x": 50, "y": 150}, {"x": 80, "y": 50}]);
|
||||
id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap())
|
||||
}
|
||||
fn bow_tie_of(s: &mut Session) -> NodeId {
|
||||
let anchors = json!([{"x": 20, "y": 120}, {"x": 80, "y": 180}, {"x": 80, "y": 120}, {"x": 20, "y": 180}]);
|
||||
id_of(s.execute("path.create", &json!({ "anchors": anchors })).unwrap())
|
||||
}
|
||||
fn twice_around_of(s: &mut Session) -> NodeId {
|
||||
let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80";
|
||||
let id = id_of(s.execute("path.create", &json!({ "d": d })).unwrap());
|
||||
s.execute("path.setFillRule", &json!({"rule": "evenOdd"})).unwrap();
|
||||
id
|
||||
}
|
||||
fn grouped_line_of(s: &mut Session) -> NodeId {
|
||||
let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
id_of(s.execute("object.group", &json!({})).unwrap())
|
||||
}
|
||||
fn compound_line_of(s: &mut Session) -> NodeId {
|
||||
let ids = [line_of(s), rect(s, 200.0, 0.0, 100.0, 100.0)];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
id_of(s.execute("object.compoundPath.make", &json!({})).unwrap())
|
||||
}
|
||||
fn square_of(s: &mut Session) -> NodeId {
|
||||
rect(s, 50.0, 0.0, 100.0, 100.0)
|
||||
}
|
||||
type Build = fn(&mut Session) -> NodeId;
|
||||
// (case, command, the other object, whether it goes behind the 100 pt square, warned, area drawn)
|
||||
type Case = (&'static str, &'static str, Build, bool, bool, Option<f64>);
|
||||
let cases: [Case; 12] = [
|
||||
("a line", "unite", line_of, false, true, Some(10_000.0)),
|
||||
("a line in front", "minusFront", line_of, false, true, Some(10_000.0)),
|
||||
("a line", "exclude", line_of, false, true, Some(10_000.0)),
|
||||
("a line behind", "minusBack", line_of, true, true, Some(10_000.0)),
|
||||
("an open evenodd square traced twice", "unite", twice_around_of, false, true, Some(10_000.0)),
|
||||
("a group of a line and a square", "unite", grouped_line_of, false, true, Some(20_000.0)),
|
||||
("a compound path of a line and a square", "unite", compound_line_of, false, true, Some(20_000.0)),
|
||||
("an open path that encloses an area", "unite", vee_of, false, false, None),
|
||||
("an open bow tie, whose signed area is zero", "unite", bow_tie_of, false, false, None),
|
||||
("a square", "unite", square_of, false, false, Some(15_000.0)),
|
||||
("a square", "minusFront", square_of, false, false, Some(5_000.0)),
|
||||
("a line, dividing", "divide", line_of, false, false, None),
|
||||
];
|
||||
for (what, op, build, behind, warned, want) in cases {
|
||||
let mut s = session();
|
||||
let (back, front) = if behind {
|
||||
let other = build(&mut s);
|
||||
(other, rect(&mut s, 0.0, 0.0, 100.0, 100.0))
|
||||
} else {
|
||||
let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
(sq, build(&mut s))
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap();
|
||||
let r = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_or_else(|e| panic!("{what}, {op}: {e}"));
|
||||
let warning = r.get("warning").and_then(Value::as_str);
|
||||
assert_eq!(warning, warned.then_some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{what}, {op}: {r}");
|
||||
if let Some(want) = want {
|
||||
let got = area_of(&s, ids(&r)[0]);
|
||||
assert!((got - want).abs() < 1.0, "{what}, {op}: area {got}, want {want}");
|
||||
}
|
||||
}
|
||||
// A group of a line and a square selected alone: its members are the shapes, and the line warns.
|
||||
let mut s = session();
|
||||
let group = grouped_line_of(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let r = s.execute("object.pathfinder.unite", &json!({})).unwrap();
|
||||
assert_eq!(r.get("warning").and_then(Value::as_str), Some(SHAPE_MODE_OPEN_PATH_NO_AREA), "{r}");
|
||||
let got = area_of(&s, ids(&r)[0]);
|
||||
assert!((got - 10_000.0).abs() < 1.0, "a group alone: area {got}");
|
||||
// A line that leaves nothing (Intersect, the backmost object in Minus Front, or the frontmost in
|
||||
// Minus Back) gives an error that names it; two squares that don't meet give the plain one.
|
||||
// (command, the other object, whether it goes behind the square, whether the error names the line)
|
||||
let cases: [(&str, Build, bool, bool); 4] = [
|
||||
("intersect", line_of, false, true),
|
||||
("minusFront", line_of, true, true),
|
||||
("minusBack", line_of, false, true),
|
||||
("intersect", |s| rect(s, 300.0, 0.0, 50.0, 50.0), false, false),
|
||||
];
|
||||
for (op, build, behind, named) in cases {
|
||||
let mut s = session();
|
||||
let (back, front) = if behind {
|
||||
let other = build(&mut s);
|
||||
(other, rect(&mut s, 0.0, 0.0, 100.0, 100.0))
|
||||
} else {
|
||||
let sq = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
(sq, build(&mut s))
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [back.0, front.0]})).unwrap();
|
||||
let e = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("produced an empty result"), "{op}: {e}");
|
||||
assert_eq!(e.contains("Outline Stroke"), named, "{op}: {e}");
|
||||
}
|
||||
// Two squares that don't meet leave Intersect empty whatever a line beside them does.
|
||||
let mut s = session();
|
||||
let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0), line_of(&mut s)];
|
||||
s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "{e}");
|
||||
// A closed path without area (a flat one) leaves Intersect empty with or without the line, so
|
||||
// the error is the plain one.
|
||||
let mut s = session();
|
||||
let flat = id_of(s.execute("path.create", &json!({"d": "M50 0 L50 100 Z"})).unwrap());
|
||||
let objects = [rect(&mut s, 0.0, 0.0, 100.0, 100.0), flat, line_of(&mut s)];
|
||||
s.execute("select.set", &json!({"ids": objects.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("produced an empty result") && !e.contains("Outline Stroke"), "a flat closed path: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_stroke_of_line() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -447,6 +447,37 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
|
||||
assert_eq!(s.prefs.gpu_preference, "automatic");
|
||||
}
|
||||
|
||||
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
|
||||
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
|
||||
/// reset with it.
|
||||
#[test]
|
||||
fn low_latency_drawing_defaults_off_and_takes_only_a_boolean() {
|
||||
let mut s = Session::new();
|
||||
assert!(!s.prefs.low_latency_drawing);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "lowLatencyDrawing"})).unwrap(), json!(false));
|
||||
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": true})).unwrap();
|
||||
assert!(s.prefs.low_latency_drawing);
|
||||
for bad in [json!(1), json!(null), json!("on"), json!("yes"), json!([true])] {
|
||||
assert!(s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": bad})).is_err(), "{bad}");
|
||||
assert!(s.prefs.low_latency_drawing);
|
||||
}
|
||||
// Booleans may be given as "true" and "false", as for every boolean preference.
|
||||
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "false"})).unwrap();
|
||||
assert!(!s.prefs.low_latency_drawing);
|
||||
s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "true"})).unwrap();
|
||||
assert_eq!(s.prefs.to_json()["lowLatencyDrawing"], json!(true));
|
||||
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
|
||||
assert!(back.low_latency_drawing);
|
||||
let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap();
|
||||
assert!(!old.low_latency_drawing);
|
||||
let l = s.execute("prefs.list", &json!({})).unwrap();
|
||||
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "lowLatencyDrawing").unwrap().clone();
|
||||
assert_eq!(row["category"], "Performance");
|
||||
assert_eq!(row["label"], "Low-Latency Drawing");
|
||||
s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap();
|
||||
assert!(!s.prefs.low_latency_drawing);
|
||||
}
|
||||
|
||||
/// Performance › Linux Display Server (#1151): automatic by default, X11 by value or label, and
|
||||
/// anything else is an error that changes nothing.
|
||||
#[test]
|
||||
@@ -2606,6 +2637,35 @@ fn settling_typing_for_a_tool_shows_its_preview_warning() {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
}
|
||||
|
||||
/// Typing kept as its own step when a dialog or a panel begins its preview, or when the font menus
|
||||
/// end the typing session, returns its applied preview's warning for the status bar. A preview
|
||||
/// without a warning returns none, and with no typing in progress nothing is kept and no step is
|
||||
/// added.
|
||||
#[test]
|
||||
fn settling_typing_for_a_dialog_returns_its_preview_warning() {
|
||||
let warned = |w: &[String]| w.iter().any(|m| m.contains("type"));
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let mut s = deferred_bloat("Typing", true, "selection");
|
||||
let before = steps(&s);
|
||||
let w = s.begin_interaction_warned("Offset Path").unwrap();
|
||||
assert!(warned(&w), "{w:?}");
|
||||
assert_eq!(steps(&s), before + 1, "the typing is a step of its own");
|
||||
assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Offset Path"));
|
||||
|
||||
let mut s = deferred_bloat("Typing", true, "selection");
|
||||
let w = s.keep_typing().unwrap();
|
||||
assert!(warned(&w), "{w:?}");
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let w = s.keep_typing().unwrap();
|
||||
assert!(w.is_empty(), "{w:?}");
|
||||
assert_eq!(steps(&s), before + 1, "nothing in progress adds no step");
|
||||
|
||||
let mut s = deferred_bloat("Typing", false, "selection");
|
||||
let w = s.begin_interaction_warned("Offset Path").unwrap();
|
||||
assert!(w.is_empty(), "{w:?}");
|
||||
}
|
||||
|
||||
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
|
||||
/// not replace full-resolution pixels already in the document.
|
||||
#[test]
|
||||
|
||||
@@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() {
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]);
|
||||
// "keep" leaves a swatch its color, without the Global Adjust that the other colors take.
|
||||
let adjust = json!({"brightness": -50});
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
let colors: Vec<Color> = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect();
|
||||
assert_eq!(colors[0], Color::rgb8(1, 2, 3));
|
||||
assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust");
|
||||
// Past the group's swatches it adds nothing.
|
||||
run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]}));
|
||||
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone();
|
||||
assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::<Vec<_>>(), colors);
|
||||
}
|
||||
|
||||
/// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A new empty folder for test `name`.
|
||||
fn fresh_folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder
|
||||
/// `dir` there once.
|
||||
fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) {
|
||||
s.script_frames = true;
|
||||
assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true);
|
||||
for _ in 0..10_000 {
|
||||
if s.script_picker().is_some() {
|
||||
let paths = vec![dir.to_string_lossy().into_owned()];
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false }));
|
||||
return;
|
||||
}
|
||||
assert!(s.script_pump().is_none(), "the run waits at its folder dialog");
|
||||
}
|
||||
panic!("the run did not open its folder dialog");
|
||||
}
|
||||
|
||||
/// Runs `source` in the app as [`start_allowed`] starts it, to its end.
|
||||
fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result<Value> {
|
||||
start_allowed(s, dir, source);
|
||||
let r = loop {
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
s.script_frames = false;
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("batch");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let source = format!(
|
||||
@@ -257,24 +293,94 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
|
||||
{{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\
|
||||
{{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}"
|
||||
);
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
let r = run_allowed(&mut s, &dir, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "{r}");
|
||||
assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay");
|
||||
assert!(path.exists());
|
||||
assert_eq!(r["written"], json!([p]), "{r}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_that_fails_names_no_file() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg");
|
||||
let dir = fresh_folder("no-folder");
|
||||
let path = dir.join("missing").join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}");
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
let r = run_allowed(&mut s, &dir, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "{r}");
|
||||
assert!(!path.exists());
|
||||
assert_eq!(r["written"], json!([]), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The commands a script runs read and write only where its `File` and `Folder` objects may (its
|
||||
/// temporary folder and what a person allowed it, here), and the files of the open documents,
|
||||
/// also in a run the person started.
|
||||
#[test]
|
||||
fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() {
|
||||
let dir = fresh_folder("gate");
|
||||
let (inside, outside) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let call = |id: &str, path: &std::path::Path| {
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let format = if id == "document.export" { ", format: 'svg'" } else { "" };
|
||||
format!(
|
||||
"try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n"
|
||||
)
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap();
|
||||
assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}");
|
||||
assert!(!outside.join("a.svg").exists());
|
||||
let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg")));
|
||||
let r = run_allowed(&mut s, &inside, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "denied"]), "{r}");
|
||||
assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists());
|
||||
let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);")
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}");
|
||||
let own = outside.join("own.svg");
|
||||
s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap();
|
||||
std::fs::copy(&own, outside.join("copy.svg")).unwrap();
|
||||
let source = format!(
|
||||
"vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}",
|
||||
call("document.save", &own),
|
||||
call("document.open", &own),
|
||||
call("document.open", &outside.join("copy.svg")),
|
||||
call("document.save", &outside.join("other.svg"))
|
||||
);
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}");
|
||||
assert!(!outside.join("other.svg").exists());
|
||||
let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg")));
|
||||
let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}");
|
||||
std::fs::remove_file(&own).unwrap();
|
||||
let r = run(&mut s, &call("document.save", &own)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}");
|
||||
assert!(own.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A command a script runs does not save into the app's own libraries; the same command run
|
||||
/// outside a script does.
|
||||
#[test]
|
||||
fn a_scripts_commands_do_not_save_into_the_apps_libraries() {
|
||||
let dir = fresh_folder("gate-library");
|
||||
let user = dir.join("user");
|
||||
let mut s = two_docs();
|
||||
s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned()));
|
||||
let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \
|
||||
catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }";
|
||||
let r = run(&mut s, source).unwrap();
|
||||
assert_eq!(r["log"], json!(["denied"]), "{r}");
|
||||
assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder");
|
||||
s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -346,17 +452,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() {
|
||||
|
||||
#[test]
|
||||
fn an_abandoned_run_reports_the_files_it_wrote() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("abandon");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
|
||||
assert!(path.exists(), "the first slice exported");
|
||||
start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(path.exists(), "the slice after the dialog exported");
|
||||
assert!(s.script_abandon());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}");
|
||||
assert!(s.script_failure_text().unwrap().contains(&p));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -886,19 +993,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
|
||||
#[test]
|
||||
fn a_file_saved_before_a_failure_stays_written_and_is_named() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("save");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
let source =
|
||||
format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');");
|
||||
let e = run(&mut s, &source).unwrap_err().to_string();
|
||||
let e = run_allowed(&mut s, &dir, &source).unwrap_err().to_string();
|
||||
assert!(path.exists());
|
||||
assert!(e.contains(&p), "{e}");
|
||||
assert_eq!(s.script_report().unwrap()["written"], json!([p]));
|
||||
assert_eq!(state(&s), before, "the document does not keep the new path");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope
|
||||
@@ -923,16 +1030,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() {
|
||||
}
|
||||
};
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
let confined_target = outside.join("confined.svg");
|
||||
let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap();
|
||||
assert_eq!(started["running"], true);
|
||||
crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target)));
|
||||
let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}");
|
||||
assert!(!confined_target.exists());
|
||||
let user_target = outside.join("user.svg");
|
||||
let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap();
|
||||
assert_eq!(started["running"], true);
|
||||
crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target)));
|
||||
let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}");
|
||||
assert!(user_target.exists());
|
||||
|
||||
@@ -423,6 +423,71 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() {
|
||||
assert_eq!(*doc(&s), before);
|
||||
}
|
||||
|
||||
/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one)
|
||||
/// records no undo step; a new order, a new color or a new name records one.
|
||||
#[test]
|
||||
fn edit_color_group_with_its_own_colors_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true}));
|
||||
let undo = undo_len(&s);
|
||||
for p in [
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}),
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}),
|
||||
json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}),
|
||||
] {
|
||||
let r = run(&mut s, "swatch.editGroup", p.clone());
|
||||
assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}");
|
||||
assert_eq!(undo_len(&s), undo, "{p}: no undo step");
|
||||
}
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a new order is a step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"}));
|
||||
assert_eq!(undo_len(&s), undo + 2, "a new name is a step");
|
||||
}
|
||||
|
||||
/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a
|
||||
/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a
|
||||
/// value is taken as it is.
|
||||
#[test]
|
||||
fn edit_color_group_with_its_own_color_keys_keeps_the_colors() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}));
|
||||
let colors = |s: &Session| -> Vec<Color> {
|
||||
doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect()
|
||||
};
|
||||
let own = colors(&s);
|
||||
let keys: Vec<String> = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect();
|
||||
assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color");
|
||||
let undo = undo_len(&s);
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys}));
|
||||
assert_eq!(undo_len(&s), undo, "the group's own colors record no step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a new name is a step");
|
||||
assert_eq!(colors(&s), own, "the colors are kept unrounded");
|
||||
// A color given as a value, not a key, is taken exactly, also within a key's step.
|
||||
let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) };
|
||||
let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0);
|
||||
assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0]));
|
||||
let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true});
|
||||
run(&mut s, "swatch.editGroup", p);
|
||||
assert_eq!(undo_len(&s), undo + 2, "a new value is a step");
|
||||
assert_eq!(colors(&s)[0], nudged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_color_group_with_a_null_removes_that_swatch() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true}));
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]}));
|
||||
assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"]));
|
||||
assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]);
|
||||
assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step");
|
||||
run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]}));
|
||||
assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step");
|
||||
assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -300,6 +300,191 @@ fn another_documents_swatches_load_as_a_library() {
|
||||
assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err());
|
||||
}
|
||||
|
||||
/// Three pattern swatches of another document that paint one pattern, one of them turned, load as
|
||||
/// three library swatches and come into a document as three swatches of one pattern, each with its
|
||||
/// own name and placement.
|
||||
#[test]
|
||||
fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() {
|
||||
use std::sync::Arc;
|
||||
let turned = vectorcraft_geom::Affine::rotate(0.5);
|
||||
let mut s = session();
|
||||
s.edit("Pattern", |d, _| {
|
||||
let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0));
|
||||
let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art());
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) });
|
||||
let swatch = |name: &str, xf| vectorcraft_color::Swatch {
|
||||
name: name.into(),
|
||||
paint: Paint::Pattern { pattern: "Dots".into(), xf },
|
||||
global: false,
|
||||
spot: false,
|
||||
};
|
||||
d.swatches.push(swatch("Tiles", vectorcraft_geom::Affine::IDENTITY));
|
||||
d.swatches.push(swatch("More tiles", vectorcraft_geom::Affine::IDENTITY));
|
||||
d.swatches.push(swatch("Turned tiles", turned));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "More tiles", "Turned tiles"]}));
|
||||
assert_eq!(r["added"], json!(["Tiles", "More tiles", "Turned tiles"]), "{r}");
|
||||
let d = doc(&s);
|
||||
assert_eq!(d.patterns.iter().filter(|p| p.name.starts_with("Dots")).count(), 1, "one pattern");
|
||||
let xf = |name: &str| match d.swatch(name).map(|w| &w.paint) {
|
||||
Some(Paint::Pattern { pattern, xf }) if pattern == "Dots" => Some(*xf),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!((xf("Tiles"), xf("Turned tiles")), (Some(vectorcraft_geom::Affine::IDENTITY), Some(turned)));
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id}));
|
||||
assert_eq!(again["added"], json!([]), "{again}");
|
||||
}
|
||||
|
||||
/// A library swatch named after its pattern, added in one call after another swatch of that pattern
|
||||
/// with the same placement, stands for the swatch just added: it is listed as existing, not added
|
||||
/// again.
|
||||
#[test]
|
||||
fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call() {
|
||||
use std::sync::Arc;
|
||||
let mut s = session();
|
||||
s.edit("Pattern", |d, _| {
|
||||
let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0));
|
||||
let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art());
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) });
|
||||
for name in ["Tiles", "Dots"] {
|
||||
let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: name.into(), paint, global: false, spot: false });
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Dots"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles"]), &json!(["Tiles"])), "{r}");
|
||||
let d = doc(&s);
|
||||
assert_eq!(d.swatches_iter().filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Dots")).count(), 1, "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern painted with another pattern is not taken for a document pattern with the
|
||||
/// same art when the pattern its art paints with differs: it comes in as a numbered copy with its
|
||||
/// own inner pattern, and adding it again reuses that copy.
|
||||
#[test]
|
||||
fn a_pattern_painted_with_another_pattern_is_not_matched_by_the_inner_patterns_name() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
// `Inner` with a tile of `inner` points, `Dots` painted with it, and swatch `Tiles` painting `Dots`.
|
||||
let make = |d: &mut vectorcraft_doc::Document, inner: f64| {
|
||||
let dot = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 2.0, 2.0));
|
||||
let dot = vectorcraft_doc::Node::path(d.alloc_id(), dot, vectorcraft_doc::Appearance::default_art());
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, inner, inner);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Inner", vec![Arc::new(dot)]) });
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
|
||||
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(pattern_paint("Inner"), Paint::None, 0.0));
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(square)]) });
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Dots"), global: false, spot: false });
|
||||
};
|
||||
let mut s = session();
|
||||
s.edit("Pattern", |d, _| {
|
||||
make(d, 4.0);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
s.edit("Pattern", |d, _| {
|
||||
make(d, 5.0);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles 2"]), &json!([])), "{r}");
|
||||
let d = doc(&s);
|
||||
let Some(Paint::Pattern { pattern, .. }) = d.swatch("Tiles 2").map(|w| &w.paint) else { panic!("no pattern swatch Tiles 2: {r}") };
|
||||
let inner = d.pattern(pattern).and_then(|p| p.art.first()).map(|n| n.appearance.fill_paint());
|
||||
let Some(Paint::Pattern { pattern: inner, .. }) = inner else { panic!("the added pattern is not painted with a pattern: {r}") };
|
||||
assert_eq!(d.pattern(&inner).map(|p| p.tile), Some(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)), "the library's inner pattern");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles 2"])), "{again}");
|
||||
}
|
||||
|
||||
/// A global color that a library pattern's art links to, added in the same call after the pattern
|
||||
/// swatch, is the swatch the pattern brought with it: it is added once, not again as a numbered
|
||||
/// copy, and goes into the library swatch's color group.
|
||||
#[test]
|
||||
fn a_color_a_pattern_brings_is_not_added_twice_in_one_call() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#123456", "global": true}));
|
||||
s.edit("Pattern", |d, _| {
|
||||
let ink = Paint::Solid { color: Color::rgb8(0x12, 0x34, 0x56), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
|
||||
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
|
||||
// `Ink` goes into a color group of its own.
|
||||
let i = d.swatches.iter().position(|w| w.name == "Ink").unwrap();
|
||||
let ink = d.swatches.remove(i);
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Inks".into(), swatches: vec![ink] });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Inks"]}));
|
||||
let d = doc(&s);
|
||||
let inks: Vec<&str> = d.swatches_iter().filter(|w| w.name.starts_with("Ink")).map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(inks, ["Ink"], "{r}");
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink"]), &json!([])), "{r}");
|
||||
let group = d.swatch_groups.iter().find(|g| g.name == "Inks").map(|g| g.swatches.iter().map(|w| w.name.as_str()).collect::<Vec<_>>());
|
||||
assert_eq!(group, Some(vec!["Ink"]), "{r}");
|
||||
assert!(d.swatches.iter().all(|w| w.name != "Ink"), "{r}");
|
||||
}
|
||||
|
||||
/// A library pattern whose art links to a global color that the document has under the same name
|
||||
/// in another color keeps the library's color: the color comes in under a free name ("Ink 2") and
|
||||
/// the pattern links to it, as the color added in the same call does, and the document's own color
|
||||
/// is left as it was. Adding the pattern again finds it.
|
||||
#[test]
|
||||
fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_another_color() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
|
||||
s.edit("Pattern", |d, _| {
|
||||
let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
|
||||
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
|
||||
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
|
||||
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
|
||||
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink 2"]), &json!([])), "{r}");
|
||||
let d = doc(&s);
|
||||
let hex = |n: &str| d.swatch(n).and_then(|w| w.paint.color()).map(|c| c.to_hex());
|
||||
assert_eq!((hex("Ink"), hex("Ink 2")), (Some("#ff0000".to_string()), Some("#0000ff".to_string())), "{r}");
|
||||
let fill = d.pattern("Squares").unwrap().art[0].appearance.fill_paint();
|
||||
let Paint::Solid { color, swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
|
||||
assert_eq!((swatch.as_deref(), color.to_hex()), (Some("Ink 2"), "#0000ff".to_string()), "{r}");
|
||||
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
|
||||
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
|
||||
let bytes = vectorcraft_testkit::ase::sample();
|
||||
|
||||
@@ -3173,6 +3173,41 @@ fn a_previewed_transform_while_typing_keeps_the_typing() {
|
||||
assert!((left(&s, id) - 400.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// With Performance › Real-time Drawing and Editing off, the typing is applied when its session
|
||||
/// ends. Ending it for another edit applies it first, as a step of its own: a dialog or a panel
|
||||
/// beginning its preview, the font menus ([`Session::keep_typing`]), a paint for the selected
|
||||
/// characters.
|
||||
#[test]
|
||||
fn ending_deferred_typing_for_another_edit_keeps_the_typing() {
|
||||
let typed = |end: &dyn Fn(&mut Session)| {
|
||||
let mut s = session();
|
||||
s.prefs.real_time_drawing = false;
|
||||
let v = ViewInfo::default();
|
||||
let id = text(&mut s, "Hello");
|
||||
s.select_tool("type", v).unwrap();
|
||||
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
click(&mut s, b.x1 - 1.0, b.center().y);
|
||||
s.tool_text(" world", v).unwrap();
|
||||
assert_eq!(obj(&s, id).plain_text(), "Hello", "the typing waits for its session to end");
|
||||
let steps = undo_labels(&s).len();
|
||||
end(&mut s);
|
||||
assert_eq!(obj(&s, id).plain_text(), "Hello world");
|
||||
assert_eq!(undo_labels(&s)[steps], "Typing", "{:?}", undo_labels(&s));
|
||||
};
|
||||
typed(&|s| {
|
||||
assert!(s.begin_interaction_warned("Fill Color").unwrap().is_empty());
|
||||
s.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
});
|
||||
typed(&|s| {
|
||||
assert!(s.keep_typing().unwrap().is_empty());
|
||||
assert!(!s.in_interaction());
|
||||
});
|
||||
typed(&|s| {
|
||||
s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
/// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the
|
||||
/// typed text: its interaction used to join the typing session and preview from the document
|
||||
/// before the typing, so the new type came back as its placeholder text.
|
||||
|
||||
@@ -2062,8 +2062,8 @@ fn datasets_csv_export_imports_back_to_the_same_data_sets() {
|
||||
}
|
||||
|
||||
/// The export's `warning` names the variables whose column a document without the variables
|
||||
/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or
|
||||
/// false, and a header that names a variable an earlier column defined with another kind. A
|
||||
/// refuses, so it doesn't import the file: a `%` header over values, a `#` header whose values
|
||||
/// aren't true or false, and a header that names a variable an earlier column defined with another kind. A
|
||||
/// header that names such a variable with its kind is read with that kind, and is listed as one
|
||||
/// read back with another kind.
|
||||
#[test]
|
||||
@@ -2081,7 +2081,9 @@ fn datasets_csv_export_warns_of_headers_a_new_document_refuses() {
|
||||
let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}");
|
||||
let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}");
|
||||
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true));
|
||||
// A `%` header's cells are read as paths of graph data files.
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({"%Rate": "5"})), (refuses("`%Rate`"), true));
|
||||
assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (loses("`%Rate`, `Chart`"), false));
|
||||
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true));
|
||||
assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false));
|
||||
assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true));
|
||||
@@ -2109,18 +2111,190 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `%` header cell that isn't a variable's name (graph data files) is refused with its column,
|
||||
/// and the import defines nothing.
|
||||
/// The data `graph.setData` reports for the graph `g`: series, categories and rows.
|
||||
fn graph_data(s: &mut Session, g: NodeId) -> Value {
|
||||
let v = s.execute("graph.setData", &json!({"id": g.0})).unwrap();
|
||||
json!({"series": v["series"], "categories": v["categories"], "rows": v["rows"]})
|
||||
}
|
||||
|
||||
/// A `%` header defines a graph variable, and each of its cells is the path of a graph data file,
|
||||
/// as the set-up page's five-column example has them. A relative path is taken from the CSV file's
|
||||
/// folder. Selecting a data set gives the bound graph the data that Graph Data's Import Data and
|
||||
/// Apply give it for the same file: tab- or comma-separated, the first row the series labels and the
|
||||
/// first column the category labels, in UTF-16 too. An empty cell is no value.
|
||||
#[test]
|
||||
fn datasets_csv_refuses_graph_data_file_columns() {
|
||||
fn datasets_csv_reads_graph_data_files_in_percent_columns() {
|
||||
let dir = Folder::new("vars-csv-graph-files");
|
||||
let tabs: &[u8] = b"\t2024\t2025\nQ1\t3\t4\nQ2\t5\t6\n";
|
||||
let commas: &[u8] = b",North\nJan,7\nFeb,8\n";
|
||||
let utf16: Vec<u8> = [0xFF, 0xFE].into_iter().chain(",A\r\nX,9\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
write(&dir.file("graphs/bill.txt"), tabs);
|
||||
write(&dir.file("dat.csv"), commas);
|
||||
write(&dir.file("ruiz.txt"), &utf16);
|
||||
let absolute = dir.file("dat.csv");
|
||||
let csv = format!(
|
||||
"Name,Age,@Photos,%Graphs,#Visibility\nBill,36,b.jpg,graphs/bill.txt,true\nDat,53,d.jpg,{absolute},true\nMaria,26,r.jpg,ruiz.txt,false\nNone,1,n.jpg,,true\n"
|
||||
);
|
||||
let path = dir.file("data.csv");
|
||||
write(&path, csv.as_bytes());
|
||||
|
||||
let mut s = session();
|
||||
let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string();
|
||||
let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt");
|
||||
assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}");
|
||||
let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx");
|
||||
assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}");
|
||||
let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"})).unwrap();
|
||||
let g = NodeId(graph["id"].as_u64().unwrap());
|
||||
let imp = s.execute("dataset.import", &json!({"path": path})).unwrap();
|
||||
assert_eq!(imp["defined"], json!(["Name", "Age", "Photos", "Graphs", "Visibility"]));
|
||||
assert_eq!(imp["imported"], 4);
|
||||
let listed = s.execute("variable.list", &json!({})).unwrap();
|
||||
assert_eq!(listed["variables"][3], json!({"name": "Graphs", "kind": "graph", "bindings": 0}));
|
||||
s.execute("variable.bind", &json!({"variable": "Graphs", "ids": [g.0]})).unwrap();
|
||||
|
||||
// What Import Data and Apply give the graph for each file.
|
||||
let sheet = |bytes: &[u8]| {
|
||||
let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(bytes)));
|
||||
let mut probe = session();
|
||||
let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"});
|
||||
let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let mut set = data.clone();
|
||||
set["id"] = json!(id.0);
|
||||
probe.execute("graph.setData", &set).unwrap();
|
||||
graph_data(&mut probe, id)
|
||||
};
|
||||
for (set, bytes) in ["Data Set 1", "Data Set 2", "Data Set 3"].into_iter().zip([tabs, commas, utf16.as_slice()]) {
|
||||
s.execute("dataset.select", &json!({"name": set})).unwrap();
|
||||
assert_eq!(graph_data(&mut s, g), sheet(bytes), "{set}");
|
||||
}
|
||||
assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[9.0]]}));
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert!(vars.variables.is_empty() && vars.datasets.is_empty());
|
||||
assert_eq!(vars.datasets[3].values.get("Graphs"), None, "an empty cell is no value");
|
||||
|
||||
// A `%` header names a graph variable the document has, and `base` sets the folder of
|
||||
// relative paths when the CSV comes as text.
|
||||
let mut t = session();
|
||||
t.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap();
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
let imp = t.execute("dataset.import", &json!({"csv": "% Sales\ndat.csv", "base": base})).unwrap();
|
||||
assert_eq!(imp["defined"], json!([]));
|
||||
let value = t.doc().unwrap().doc.variables.datasets[0].values.get("Sales").cloned();
|
||||
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains("North") && c.contains("Feb")), "{value:?}");
|
||||
}
|
||||
|
||||
/// A graph data file whose rows hold more values than its first row has series labels gives the
|
||||
/// bound graph the series labels that Graph Data's Import Data and Apply give it: up to the last one
|
||||
/// given, with no blank label for the series after it.
|
||||
#[test]
|
||||
fn datasets_csv_graph_data_file_keeps_the_given_series_labels() {
|
||||
let dir = Folder::new("vars-csv-graph-wide");
|
||||
let wide: &[u8] = b"\tA\t\nX\t1\t2\n";
|
||||
write(&dir.file("wide.txt"), wide);
|
||||
let path = dir.file("data.csv");
|
||||
write(&path, b"Name,%Chart\na,wide.txt\n");
|
||||
|
||||
let mut s = session();
|
||||
let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"});
|
||||
let g = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("dataset.import", &json!({"path": path})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Chart", "ids": [g.0]})).unwrap();
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 1"})).unwrap();
|
||||
|
||||
let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(wide)));
|
||||
let mut probe = session();
|
||||
let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let mut set = data.clone();
|
||||
set["id"] = json!(id.0);
|
||||
probe.execute("graph.setData", &set).unwrap();
|
||||
assert_eq!(graph_data(&mut s, g), graph_data(&mut probe, id));
|
||||
assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[1.0, 2.0]]}));
|
||||
}
|
||||
|
||||
/// A `%` column's file that is missing, a folder, larger than 1 MB, or gives a graph value longer
|
||||
/// than 256 KB, a relative path with no
|
||||
/// folder to take it from, a `base` that isn't a folder path, and a `%` header whose name is a
|
||||
/// variable of another kind refuse the import with the line and column, and leave the variables and
|
||||
/// data sets as they were. A file of exactly 1 MB is read, and a file named by many cells is read
|
||||
/// once.
|
||||
#[test]
|
||||
fn datasets_csv_refuses_unreadable_graph_data_files() {
|
||||
let dir = Folder::new("vars-csv-graph-refused");
|
||||
write(&dir.file("ok.txt"), b"\tA\nX\t1\n");
|
||||
write(&dir.file("big.txt"), &vec![b'1'; crate::cmd::MAX_GRAPH_DATA_FILE + 1]);
|
||||
let at_limit = [b"\tA\nX\t2\n".as_slice(), &vec![b' '; crate::cmd::MAX_GRAPH_DATA_FILE - 7]].concat();
|
||||
write(&dir.file("limit.txt"), &at_limit);
|
||||
std::fs::create_dir_all(dir.file("folder.txt")).unwrap();
|
||||
// 10,000 categories with long labels: under 1 MB, but a graph value over 256 KB.
|
||||
let long: String = (0..10_000).map(|i| format!("category label number {i:05}\t{i}\n")).collect();
|
||||
write(&dir.file("long.txt"), format!("\tA\n{long}").as_bytes());
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
|
||||
let mut s = session();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("dataset.import", &json!({"csv": "Title\nkept"})).unwrap();
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let cases = [
|
||||
(json!({"csv": "Name,%Chart\na,ok.txt\nb,missing.txt", "base": base}), "line 3, column 2: the graph data file for `Chart` can't be read"),
|
||||
(json!({"csv": "Name,%Chart\na,folder.txt", "base": base}), "line 2, column 2: the graph data file for `Chart` can't be read"),
|
||||
(json!({"csv": "%Chart\nbig.txt", "base": base}), "line 2, column 1: the graph data file `big.txt` for `Chart` is larger than 1048576 bytes"),
|
||||
(
|
||||
json!({"csv": "Name,%Chart\na,long.txt", "base": base}),
|
||||
"line 2, column 2: the graph data file `long.txt` for `Chart` gives a graph value longer than 262144 bytes",
|
||||
),
|
||||
(json!({"csv": "%Chart\nok.txt"}), "line 2, column 1: the graph data file `ok.txt` for `Chart` is a relative path"),
|
||||
(json!({"csv": "%Chart\nok.txt", "base": ""}), "`base` is empty"),
|
||||
(json!({"csv": "%Chart\nok.txt", "base": 3}), "`base` must be a string"),
|
||||
(json!({"csv": "%Title\nok.txt", "base": base}), "column 1: `%Title` names `Title`, which is a text variable"),
|
||||
];
|
||||
for (p, want) in cases {
|
||||
let e = s.execute("dataset.import", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before, "{p}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{p}");
|
||||
}
|
||||
|
||||
let rows: String = (0..300).map(|_| "limit.txt\n").collect();
|
||||
let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{rows}"), "base": base})).unwrap();
|
||||
assert_eq!(imp["imported"], 300, "a 1 MB file named by 300 cells counts once against the import's limit");
|
||||
let value = s.doc().unwrap().doc.variables.datasets[299].values.get("Chart").cloned();
|
||||
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}");
|
||||
}
|
||||
|
||||
/// A `%` column's path is followed as an image variable's path is: a path on another computer (a
|
||||
/// UNC path or a `file:` URL with a host) or a URL other than `file:` refuses the import with the
|
||||
/// line and column and the reason, before any file is read, and leaves the variables and data sets
|
||||
/// as they were. A relative path inside the CSV's folder is still read, and so is a `file:` URL
|
||||
/// without a host when no folder is given.
|
||||
#[test]
|
||||
fn datasets_csv_refuses_graph_data_files_on_other_computers() {
|
||||
let dir = Folder::new("vars-csv-graph-network");
|
||||
write(&dir.file("sub/ok.txt"), b"\tA\nX\t1\n");
|
||||
let path = dir.file("data.csv");
|
||||
write(&path, b"Name,%Chart\na,sub/ok.txt\n");
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
|
||||
let mut s = session();
|
||||
let imp = s.execute("dataset.import", &json!({"path": path})).unwrap();
|
||||
assert_eq!(imp["imported"], 1);
|
||||
let value = s.doc().unwrap().doc.variables.datasets[0].values.get("Chart").cloned();
|
||||
assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('A')), "{value:?}");
|
||||
// A `file:` URL without a host is a path on this computer, read without a folder to take it from.
|
||||
let file = dir.file("sub/ok.txt").replace('\\', "/");
|
||||
let url = if file.starts_with('/') { format!("file://{file}") } else { format!("file:///{file}") };
|
||||
let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{url}")})).unwrap();
|
||||
assert_eq!(imp["imported"], 1, "{url}");
|
||||
let before = s.doc().unwrap().doc.variables.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (cell, reason) in [
|
||||
(r"\\server\share\ok.txt", "the path is on another computer"),
|
||||
("//server/share/ok.txt", "the path is on another computer"),
|
||||
("file://server/share/ok.txt", "the path is on another computer"),
|
||||
("https://example.com/ok.txt", "the link is not a file path"),
|
||||
] {
|
||||
let want = format!("line 3, column 2: the graph data file `{cell}` for `Chart` isn't followed: {reason}");
|
||||
let p = json!({"csv": format!("Name,%Chart\na,sub/ok.txt\nb,{cell}"), "base": base});
|
||||
let e = s.execute("dataset.import", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(&want), "{cell}: {e}");
|
||||
assert_eq!(s.doc().unwrap().doc.variables, before, "{cell}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cell}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two header cells that name one variable, by the same name or by a name and its prefix, are
|
||||
@@ -3537,12 +3711,12 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
|
||||
// A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds
|
||||
// that aren't text.
|
||||
let (o, warnings) = svg_opened(&untraited, "untraited.svg");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: Unknown (1)")), "{warnings:?}");
|
||||
assert!(o.doc().unwrap().doc.variables.variables.is_empty());
|
||||
// The values of the other kinds aren't read, so one that Load Variable Library would refuse
|
||||
// leaves the text variables and their values as they open.
|
||||
let (o, warnings) = svg_opened(&relative, "relative.svg");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}");
|
||||
assert!(warnings.contains(&json!("variables that aren't text were left out: Linked File (1)")), "{warnings:?}");
|
||||
let vars = &o.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
|
||||
assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into()));
|
||||
@@ -3555,6 +3729,42 @@ fn an_svg_without_readable_variable_data_opens_its_art() {
|
||||
assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens");
|
||||
}
|
||||
|
||||
/// The warning about an SVG's variables that aren't text names each kind once, in the order it
|
||||
/// first comes, with its count: Visibility, Linked File and Graph Data for the traits VectorCraft
|
||||
/// reads, Unknown for a variable without a `trait`, and any other `trait` as the file writes it, in
|
||||
/// backticks with each backtick in it doubled, so a `trait` that looks like a kind or a list entry
|
||||
/// stays one entry of its own.
|
||||
#[test]
|
||||
fn svg_variable_data_warning_names_each_kind_left_out() {
|
||||
let variables = [
|
||||
("V1", Some("visibility")),
|
||||
("I1", Some("fileref")),
|
||||
("V2", Some("visibility")),
|
||||
("T", Some("textcontent")),
|
||||
("G1", Some("graphdata")),
|
||||
("U1", None),
|
||||
("X1", Some("unknown")),
|
||||
("X2", Some("a`b (1), c")),
|
||||
("X3", Some("Visibility")),
|
||||
("I2", Some("fileref")),
|
||||
("U2", None),
|
||||
];
|
||||
let declared: String = variables
|
||||
.iter()
|
||||
.map(|(name, t)| match t {
|
||||
Some(t) => format!("<variable varName=\"{name}\" trait=\"{t}\"/>"),
|
||||
None => format!("<variable varName=\"{name}\"/>"),
|
||||
})
|
||||
.collect();
|
||||
let svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><variableSets><variableSet><variables>{declared}</variables></variableSet></variableSets><rect x=\"1\" y=\"1\" width=\"5\" height=\"5\"/></svg>"
|
||||
);
|
||||
let (o, warnings) = svg_opened(&svg, "kinds.svg");
|
||||
let warning = "variables that aren't text were left out: Visibility (2), Linked File (2), Graph Data (1), Unknown (2), `unknown` (1), `a``b (1), c` (1), `Visibility` (1)";
|
||||
assert!(warnings.contains(&json!(warning)), "{warnings:?}");
|
||||
assert_eq!(o.doc().unwrap().doc.variables.variables.iter().map(|v| v.name.as_str()).collect::<Vec<_>>(), ["T"]);
|
||||
}
|
||||
|
||||
/// Five variables of three kinds, defined out of every order: `beta` (text, on type named Mike),
|
||||
/// `Alpha` (visibility, on a rectangle named apple), `gamma` (image, bound to nothing), `Delta`
|
||||
/// (visibility, on two rectangles) and `Echo` (text, on type named Bravo).
|
||||
|
||||
@@ -89,6 +89,8 @@ fn with_status(mut ui: Vec<UiRequest>, warnings: Vec<String>) -> Vec<UiRequest>
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiRequest {
|
||||
Dialog(String, Value),
|
||||
/// Show and select the panel with this id where it is (Window › Transform for `transform`).
|
||||
Panel(String),
|
||||
SwitchTool(String),
|
||||
/// A message for the status bar: the `warning` of a command the tool ran (Liquify skipping
|
||||
/// type under the brush).
|
||||
@@ -120,6 +122,12 @@ impl Session {
|
||||
self.tool.id()
|
||||
}
|
||||
|
||||
/// The selection tool chosen last (Selection, Direct Selection or Group Selection), which
|
||||
/// `tool.selectLastSelection` chooses: the Selection tool until one is chosen.
|
||||
pub fn last_selection_tool(&self) -> &'static str {
|
||||
self.last_selection_tool.unwrap_or("selection")
|
||||
}
|
||||
|
||||
/// How many times switching or closing documents, or replacing the active one (File › Revert),
|
||||
/// has started the tool afresh, also inside a `command.batch` or `action.batch`. A frontend
|
||||
/// compares it before and after a command.
|
||||
@@ -145,7 +153,8 @@ impl Session {
|
||||
crate::cmd::distortcmds::silent(self, |g| g.visible = true)?;
|
||||
}
|
||||
// When the tool already active, or the tool lent a selection tool for a drag, is chosen again,
|
||||
// `select_tool` calls its [`Tool::chosen_again`] (the Blend tool finishes its blend).
|
||||
// `select_tool` calls its [`Tool::chosen_again`] (the Blend tool finishes its blend, the Pen
|
||||
// ends its path).
|
||||
let again = self.lender.as_ref().unwrap_or(&self.tool).id() == id;
|
||||
self.switch_tool(id, view)?;
|
||||
// `switch_tool` returns early for the tool already active.
|
||||
@@ -1551,7 +1560,9 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)),
|
||||
Action::Panel(panel) => ui.push(UiRequest::Panel(panel)),
|
||||
Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)),
|
||||
Action::Status(msg) => ui.push(UiRequest::Status(msg)),
|
||||
Action::Notify(what) => {
|
||||
let view = self.last_view;
|
||||
self.with_tool_cx(view, |t, cx| t.notify(cx, &what));
|
||||
|
||||
@@ -604,6 +604,17 @@ fn structured_junk() {
|
||||
("brush.options", json!({"name": "Arrow", "params": {"width": -5, "direction": "diagonal", "flip_along": "yes"}})),
|
||||
("brush.options", json!({"name": "Chain", "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "flip_across": true}})),
|
||||
("brush.options", json!({"name": "Chain", "params": {"scale": 0, "spacing": 1e308, "fit": "nope", "side": null}})),
|
||||
("brush.apply", json!({"name": "Chain", "id": 2})),
|
||||
(
|
||||
"brush.objectOptions",
|
||||
json!({"id": 2, "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "colorization": {"method": "hueShift"}}}),
|
||||
),
|
||||
("brush.objectOptions", json!({"id": 2, "params": {"scale": "x", "fit": "nope", "side": null}})),
|
||||
(
|
||||
"brush.objectOptions",
|
||||
json!({"id": 2, "params": {"colorization": {"method": "hueShift", "key": {"model": "rgb", "r": 1e308, "g": -1e308, "b": 0}}}}),
|
||||
),
|
||||
("brush.objectOptions", json!({"ids": [1e308, -1], "params": {}, "reset": true})),
|
||||
("path.curvature", json!({"points": [{"x": 0, "y": 0}]})),
|
||||
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 1000, "x": 0, "y": 0})),
|
||||
("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 0, "x": 1e308, "y": -1e308})),
|
||||
@@ -1058,6 +1069,12 @@ fn structured_junk() {
|
||||
("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})),
|
||||
("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})),
|
||||
("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})),
|
||||
// Unit Converter add-on.
|
||||
("addon.units.convert", json!({"value": f64::MAX, "unit": "yards"})),
|
||||
("addon.units.convert", json!({"value": "1e308m*1e308", "unit": "q"})),
|
||||
("addon.units.convert", json!({"value": "-2p6/0", "unit": ["mm"]})),
|
||||
("addon.units.convert", json!({"value": [1], "unit": 5})),
|
||||
("addon.units.selectionSize", json!({"ids": [u64::MAX]})),
|
||||
// Cutting Tools add-on: Stencil Bridges.
|
||||
("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})),
|
||||
("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user