Merge main into feat/brushes-bristle-library

This commit is contained in:
dotCooCoo committed 2026-11-12 00:40:51 -08:00
commit aba45b7249
212 files changed
+10820 -804

No files matched your search

+2
View File
@@ -126,6 +126,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
@@ -137,6 +138,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn.
+1 -1
View File
@@ -7,7 +7,7 @@
//! Differences from the desktop app:
//! - no TCP control server (browsers can't listen on sockets);
//! - File → Open uses the browser file picker; bytes arrive asynchronously through
//! `Services::inbox`;
//! `Services::picked_inbox`;
//! - Save / Export trigger a browser download;
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
+28 -13
View File
@@ -17,7 +17,7 @@ use vectorcraft_ui_egui::i18n;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
use vectorcraft_ui_egui::stylus::StylusFeed;
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp};
use wasm_bindgen::JsCast as _;
use crate::locks::WebLocks;
@@ -25,6 +25,18 @@ use crate::pencil::SharedPointers;
pub(crate) type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and
/// `page_inbox`).
#[derive(Clone, Default)]
struct OpenInboxes {
/// Dropped on the page.
dropped: Inbox,
/// The open picker's answers.
picked: PickedInbox,
/// Handed over by the page's script (`window.vectorcraft.openFile`).
page: Inbox,
}
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
/// whether Shift was held: where dropped files land.
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
@@ -48,7 +60,7 @@ const MAX_RESTARTS: u32 = 3;
#[derive(Clone)]
struct Host {
runner: eframe::WebRunner,
inbox: Inbox,
inbox: OpenInboxes,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
drag: DragPos,
@@ -77,7 +89,7 @@ pub fn start() {
crate::fonts::load_startup_fonts().await;
let host = Host {
runner: eframe::WebRunner::new(),
inbox: Arc::default(),
inbox: OpenInboxes::default(),
place_inbox: Arc::default(),
script_inbox: Arc::default(),
drag: DragPos::default(),
@@ -132,13 +144,13 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
// The old services asked the old context for frames.
app.services = services;
app.status("The graphics were lost and have been restarted");
crate::api::connect(None, host.inbox.clone(), ctx.clone());
crate::api::connect(None, host.inbox.page.clone(), ctx.clone());
app
}
None => {
// `window.vectorcraft`: the page's control channel (crate::api).
let (control_tx, control_rx) = std::sync::mpsc::channel();
crate::api::connect(Some(control_tx), host.inbox.clone(), ctx.clone());
crate::api::connect(Some(control_tx), host.inbox.page.clone(), ctx.clone());
if let Err(e) = crate::api::install() {
log::error!("vectorcraft-web: couldn't install window.vectorcraft: {}", js_err(e));
}
@@ -409,7 +421,7 @@ impl eframe::App for WebShell {
for f in dropped {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
let target = app.drop_target(&name, pos, shift);
let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
wasm_bindgen_futures::spawn_local(async move {
match f.bytes_async().await {
Ok(bytes) => {
@@ -432,14 +444,14 @@ impl eframe::App for WebShell {
}
fn services(
inbox: Inbox,
inbox: OpenInboxes,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
ctx: egui::Context,
locks: Option<WebLocks>,
stylus: StylusFeed,
) -> Services {
let open_inbox = inbox.clone();
let open_inbox = inbox.picked.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
let screen_color = eye_dropper(ctx.clone());
@@ -488,11 +500,12 @@ fn services(
let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| {
d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
});
let Some(file) = dialog.pick_file().await else {
return;
// A canceled pick answers `None`.
let answer = match dialog.pick_file().await {
Some(file) => Some((file.file_name(), file.read().await)),
None => None,
};
let bytes = file.read().await;
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer);
ctx.request_repaint();
});
})),
@@ -500,7 +513,9 @@ fn services(
screen_color,
// A download that couldn't be started fails the save or export it is for (#1693).
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
inbox: Some(inbox),
inbox: Some(inbox.dropped),
picked_inbox: Some(inbox.picked),
page_inbox: Some(inbox.page),
recovery_store: Some(Arc::new(BrowserStore { locks })),
// File → Print: the browser's print dialog.
print: Some(Box::new(BrowserPrint)),
+41 -1
View File
@@ -9,6 +9,7 @@ use super::{App, VectorcraftApp, file_access, window};
#[cfg(target_os = "macos")]
use super::{mac_menu, mac_window, open_documents};
use vectorcraft_ui_egui::dialogs::safe_mode;
use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage};
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
@@ -34,12 +35,16 @@ impl eframe::App for App {
// control channel asks for, and the frames carrying input it injected, to the automation roots
// (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
let _timed = BEACON.enter_timed(Stage::Logic);
file_access::unconfined(|| self.logic_frame(ctx, frame));
self.app.finish_ime_logic(ctx);
BEACON.enter(Stage::Idle);
}
/// 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) {
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,
// restore, …): take it off again before the frame is laid out (#1758).
if let Some(window_frame) = self.window_frame.as_mut() {
@@ -60,9 +65,10 @@ impl eframe::App for App {
// that no mouse button is down.
#[cfg(target_os = "macos")]
self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0);
BEACON.enter(Stage::Idle);
}
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let _timed = BEACON.enter_timed(Stage::Interface);
#[cfg(target_os = "macos")]
{
let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT;
@@ -89,8 +95,13 @@ impl eframe::App for App {
if !self.app.file_dialog_open() && self.app.take_ime_discard() {
discard_marked_text();
}
self.end_frame(ui.ctx(), frame);
}
fn on_exit(&mut self) {
// The window is closing: saving and teardown are not timed for the hang report, and a report
// of a stall the interface came back from is removed.
let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled());
super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON);
file_access::unconfined(|| save_prefs(&self.app));
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
@@ -102,6 +113,35 @@ impl eframe::App for App {
}
impl App {
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
/// focused, shown window whose windows had input waits for the renderer and the next frame,
/// which the input asks for at once; any other frame leaves the interface thread idle
/// (`hang_watch`).
fn end_frame(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
// A pass egui discards and runs again is not the frame's end: the pass after it is.
if ctx.will_discard() {
return;
}
if let Some(start) = self.frame_start.take() {
let work_ms = start.elapsed().as_secs_f32() * 1000.0;
let previous_total_ms = frame.info().cpu_usage.map(|s| s * 1000.0);
BEACON.frame(FrameTime { work_ms, previous_total_ms }, self.app.session.documents().len());
}
// Hide on macOS hides the window at once, before the window reports losing focus.
let main_shown = ctx.input(|i| i.focused && i.viewport().minimized != Some(true))
&& self.winit_window.as_ref().is_none_or(|w| w.is_visible() != Some(false));
// A floating panel or document window with the focus counts as well, with the commands it
// was sent after its pass, and those its pass sent (`hang_beacon::watch_input`).
let shown = ctx.input(|i| hang_beacon::shown_window(main_shown, &i.raw.viewports));
let handed_off = BEACON.take_handed_off();
let input = BEACON.take_input();
let stage = match shown {
Some(id) => ctx.viewport_for(id, |vp| hang_beacon::after_frame(input && !handed_off.contains(&id), true, &vp.commands)),
None => hang_beacon::after_frame(input, false, &[]),
};
BEACON.enter(stage);
}
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) {
+445
View File
@@ -0,0 +1,445 @@
//! The hang report. A thread reads the interface thread's marks
//! ([`vectorcraft_ui_egui::hang_beacon`]) every [`POLL`]. When the interface thread has made no
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
//! graphics processor and the present mode the app asked for, and how long the session has run with
//! how many documents open. The process holds a lock on the file until the interface thread answers
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
//! moves the newest abandoned file to `hang-report.1.txt` and removes the others, says so in the
//! status bar, and Help › Copy Troubleshooting Info copies the reports. Where the file system has no
//! file locks, the file is written and taken without one.
//!
//! No native stack is recorded: the marks are what the report has. The report holds command ids and
//! counts, never document contents or file paths. [`STALL`] is VectorCraft's own value.
//!
//! A stall in the renderer is timed only after a frame that had input in any window: input asks for
//! the next frame at once, so a frame that does not start then is late. After a frame without
//! input, the window waiting for input looks the same as one stuck drawing, so that time is not
//! timed. Nor is the time after a frame that minimizes or hides the main window or hands it to the
//! system to move or resize. A window the system stops redrawing while it is hidden can still look
//! like a stall after a frame with input; the report's stage says so. A system file dialog shown in
//! line (on Windows and Linux) and an open menu of the macOS menu bar wait for the user and are not
//! timed.
use std::fs::File;
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime};
#[cfg(target_os = "macos")]
use vectorcraft_ui_egui::hang_beacon::Activity;
use vectorcraft_ui_egui::hang_beacon::{BEACON, Beacon, FrameTime, Sample, Stage};
use super::logging::timestamp;
/// How long the interface thread may stay in one stage before the report is written.
pub const STALL: Duration = Duration::from_secs(3);
/// How often the watching thread reads the marks.
pub const POLL: Duration = Duration::from_millis(500);
/// The report of a stall that has not ended, in the log folder: this, the process id, `.txt`.
pub const REPORT_PREFIX: &str = "hang-report-";
/// At most this many report files are taken when a launch looks for abandoned ones; older abandoned
/// ones are removed.
const MAX_REPORT_FILES: usize = 16;
/// At most this many entries of the log folder are looked at for report files.
const MAX_SCANNED_ENTRIES: usize = 1024;
/// The report the last session left, moved here at launch.
pub const PREVIOUS_FILE: &str = "hang-report.1.txt";
/// A report file larger than this is not read.
pub const MAX_REPORT_BYTES: u64 = 64 * 1024;
/// Environment values in the report are cut to this many characters.
const MAX_VALUE_CHARS: usize = 64;
/// What [`Watch::check`] found.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Event {
/// The interface thread has been in the sample's stage, without a mark, for this long.
Stalled(Duration),
/// The interface thread made a mark again after a [`Event::Stalled`], about this long after
/// the stall began.
Answered(Duration),
}
/// Decides from successive samples when the interface thread has stalled and when it answers
/// again. Time comes from the caller, so tests drive it without waiting.
#[derive(Debug)]
pub struct Watch {
stall: Duration,
/// The step seen in a busy stage and when it was first seen.
seen: Option<(u64, Duration)>,
reported: bool,
}
impl Watch {
pub fn new(stall: Duration) -> Watch {
Watch { stall, seen: None, reported: false }
}
/// The marks read at `now` (any monotonic clock that started before the first call).
pub fn check(&mut self, now: Duration, sample: Sample) -> Option<Event> {
let same = self.seen.is_some_and(|(step, _)| step == sample.step);
if same && sample.busy() {
let since = self.seen.map_or(now, |(_, since)| since);
let stalled = now.saturating_sub(since);
if !self.reported && stalled >= self.stall {
self.reported = true;
return Some(Event::Stalled(stalled));
}
return None;
}
let answered = match (self.reported, self.seen) {
(true, Some((_, since))) => Some(Event::Answered(now.saturating_sub(since))),
_ => None,
};
self.reported = false;
self.seen = sample.busy().then_some((sample.step, now));
answered
}
}
/// What the report says about the platform.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Facts {
/// The window system the window opened on: Wayland, X11, AppKit, Win32, other or unknown.
pub window_system: String,
/// `XDG_CURRENT_DESKTOP`.
pub desktop: Option<String>,
/// `XDG_SESSION_TYPE`.
pub session_type: Option<String>,
/// Running in a Flatpak sandbox.
pub flatpak: bool,
/// The graphics processor the window draws with.
pub graphics: Option<String>,
/// The present mode and frame queue the app asked the window surface for.
pub surface: String,
}
impl Facts {
/// The facts from the environment (`env`, `flatpak_info`: whether `/.flatpak-info` exists) and
/// what the app knows.
pub fn new(env: impl Fn(&str) -> Option<String>, flatpak_info: bool, window_system: &str, graphics: Option<String>, surface: String) -> Facts {
let value = |name: &str| env(name).map(|v| clean(&v)).filter(|v| !v.is_empty());
Facts {
window_system: window_system.to_string(),
desktop: value("XDG_CURRENT_DESKTOP"),
session_type: value("XDG_SESSION_TYPE"),
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
graphics,
surface,
}
}
/// The facts as report lines.
pub fn lines(&self) -> String {
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
format!(
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH,
self.window_system,
or_unknown(&self.desktop),
or_unknown(&self.session_type),
if self.flatpak { "yes" } else { "no" },
or_unknown(&self.graphics),
self.surface,
)
}
}
/// `v` with control characters removed, cut to [`MAX_VALUE_CHARS`] characters.
fn clean(v: &str) -> String {
v.chars().filter(|c| !c.is_control()).take(MAX_VALUE_CHARS).collect::<String>().trim().to_string()
}
/// The marks other than the stage: the last commands, the last frames and the session.
fn activity_lines(beacon: &Beacon, uptime: Duration) -> String {
let commands = match beacon.recent_commands() {
Some(c) if c.is_empty() => "none".to_string(),
Some(c) => c.join(", "),
None => "unavailable (being written)".to_string(),
};
let (work, total) = match beacon.recent_frames() {
Some(frames) => {
let list = |f: &dyn Fn(&FrameTime) -> Option<f32>| {
let times: Vec<String> = frames.iter().filter_map(f).map(|ms| format!("{ms:.1}")).collect();
if times.is_empty() { "none".to_string() } else { times.join(", ") }
};
(list(&|t| Some(t.work_ms)), list(&|t| t.previous_total_ms))
}
None => ("unavailable (being written)".to_string(), "unavailable (being written)".to_string()),
};
format!(
"Recent commands, oldest first: {commands}\nApp work per frame (ms), oldest first: {work}\nWork and drawing per frame, without waiting for the display (ms), oldest first: {total}\nSession: running for {} s, {} documents open\n",
uptime.as_secs(),
beacon.documents(),
)
}
/// The report of a stall that has lasted `stalled` in `sample`'s stage, written at `at`.
pub fn report(at: SystemTime, stalled: Duration, sample: Sample, beacon: &Beacon, uptime: Duration, facts: &Facts) -> String {
let waiting = sample.activity.describe().map(|a| format!("Waiting on: {a}\n")).unwrap_or_default();
format!(
"VectorCraft hang report, {}\nThe interface thread has not moved on for {:.1} s.\nStage: {}\n{waiting}{}{}No native stack is recorded: the stage and the activity are what the app marks.\n",
timestamp(at),
stalled.as_secs_f64(),
sample.stage.describe(),
activity_lines(beacon, uptime),
facts.lines(),
)
}
/// What the watching thread and Help › Copy Troubleshooting Info share.
pub struct Shared {
pub facts: Facts,
pub started: Instant,
/// This session's last report.
pub last: Mutex<Option<String>>,
/// The report the last session left ([`take_previous`]).
pub previous: Option<String>,
}
/// The text Help › Copy Troubleshooting Info copies.
pub fn troubleshooting(shared: &Shared, beacon: &Beacon, at: SystemTime) -> String {
let last = shared.last.lock().unwrap_or_else(PoisonError::into_inner).clone();
format!(
"VectorCraft troubleshooting info, {}\n{}{}\nThis session's last hang report:\n{}\nThe hang report the last session left (it was closed while it did not answer):\n{}\n",
timestamp(at),
shared.facts.lines(),
activity_lines(beacon, shared.started.elapsed()),
last.as_deref().unwrap_or("none\n"),
shared.previous.as_deref().unwrap_or("none\n"),
)
}
/// The report file of this process in `dir`.
fn report_path(dir: &Path) -> PathBuf {
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
}
/// A report file this process wrote and holds locked until the interface answers again.
#[derive(Debug)]
pub struct Held {
path: PathBuf,
_file: File,
}
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
/// file locks, the file is written unlocked and the log says so.
fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
std::fs::create_dir_all(dir)?;
let path = report_path(dir);
let mut file = File::create(&path)?;
if let Err(e) = file.lock() {
log::warn!("the hang report file is written without a lock: {e}");
}
file.write_all(text.as_bytes())?;
Ok(Held { path, _file: file })
}
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
/// system without file locks answers [`std::io::ErrorKind::Unsupported`], and its files count as
/// abandoned; any other error leaves the file alone.
fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
match locked {
Ok(()) => true,
Err(std::fs::TryLockError::Error(e)) => e.kind() == std::io::ErrorKind::Unsupported,
Err(std::fs::TryLockError::WouldBlock) => false,
}
}
/// The report file at `path`, opened and locked, with its length, when it was abandoned
/// ([`abandoned`]) and is not empty (an empty one may be being written).
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
let file = File::options().read(true).write(true).open(path).ok()?;
if !abandoned(file.try_lock()) {
return None;
}
let len = file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((file, len))
}
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
/// when there are none. The newest file is moved to [`PREVIOUS_FILE`] and the others are removed
/// once read. Of more than [`MAX_REPORT_FILES`], the newest are taken and the older ones removed
/// unread; the first [`MAX_SCANNED_ENTRIES`] entries of `dir` are looked at. A report file another
/// process holds locked, or one still empty, is left alone. A file over [`MAX_REPORT_BYTES`] is
/// taken without being read. A file that can't be moved is removed, so no later launch offers it
/// again: the caller writes the reports to the log. Each file is opened once.
pub fn take_previous(dir: &Path) -> Option<String> {
let mut found: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir)
.ok()?
.take(MAX_SCANNED_ENTRIES)
.filter_map(Result::ok)
.filter(|e| {
e.file_name()
.to_str()
.and_then(|n| n.strip_prefix(REPORT_PREFIX)?.strip_suffix(".txt"))
.is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()))
})
.map(|e| (e.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH), e.path()))
.collect();
found.sort();
// Newest first: only abandoned reports count toward the limit.
let mut texts = Vec::new();
for (_, path) in found.into_iter().rev() {
let Some((file, len)) = open_abandoned(&path) else { continue };
if texts.len() == MAX_REPORT_FILES {
drop(file);
remove_quietly(&path);
continue;
}
let mut bytes = Vec::new();
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
String::from_utf8_lossy(&bytes).into_owned()
} else {
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
};
// Closed (and unlocked) before it is moved: Windows moves no open file.
drop(file);
if !texts.is_empty() {
remove_quietly(&path);
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
log::warn!("couldn't move the hang report file to {PREVIOUS_FILE}: {e}");
remove_quietly(&path);
}
texts.push(text);
}
texts.reverse();
(!texts.is_empty()).then(|| texts.join("\n"))
}
/// Remove the report file at `path`; a failure goes to the log.
fn remove_quietly(path: &Path) {
if let Err(e) = std::fs::remove_file(path) {
log::warn!("couldn't remove the hang report file: {e}");
}
}
/// Set when the app closes normally ([`closing`]): the watching thread writes no report file after it.
pub static CLOSING: AtomicBool = AtomicBool::new(false);
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
fn remove(held: Held) -> Option<String> {
let Held { path, _file: file } = held;
drop(file);
match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
_ => None,
}
}
/// Act on what [`Watch::check`] found: write (and hold) or remove this process's report file in
/// `dir`, then log it. The file comes first: logging can wait on what the interface thread waits on.
#[allow(clippy::too_many_arguments)]
pub fn record(
event: Event,
sample: Sample,
beacon: &Beacon,
shared: &Shared,
dir: Option<&Path>,
held: &mut Option<Held>,
closing: &AtomicBool,
at: SystemTime,
) {
match event {
Event::Stalled(stalled) => {
let text = report(at, stalled, sample, beacon, shared.started.elapsed(), &shared.facts);
let mut failed = None;
if let Some(dir) = dir.filter(|_| !closing.load(Ordering::Acquire)) {
match write_report(dir, &text) {
Ok(file) => *held = Some(file),
Err(e) => failed = Some(e.to_string()),
}
// The app began to close while the file was written: it is not a report to leave.
if closing.load(Ordering::Acquire) {
failed = held.take().and_then(remove).or(failed);
}
}
*shared.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(text.clone());
log::warn!("the interface stopped answering:\n{}", text.trim_end());
if let Some(e) = failed {
log::warn!("couldn't write or remove the hang report file: {e}");
}
}
Event::Answered(after) => {
let failed = held.take().and_then(remove);
log::warn!("the interface answered again about {:.1} s after it stopped", after.as_secs_f64());
if let Some(e) = failed {
log::warn!("couldn't remove the hang report file: {e}");
}
}
}
}
/// The app is closing normally: mark the interface thread idle on `beacon` (saving and teardown are
/// not timed), remove this process's report file in `dir` and have the watching thread write no
/// more. It does not wait for the watching thread. The file can be removed while that thread holds
/// it open and locked: the standard library opens files with `FILE_SHARE_DELETE` on Windows, and a
/// byte-range lock does not prevent deletion. Where Windows deletes a file only once its last
/// handle closes, the name goes when the process ends.
pub fn closing(dir: Option<&Path>, closing: &AtomicBool, beacon: &Beacon) {
beacon.enter(Stage::Idle);
closing.store(true, Ordering::Release);
if let Some(dir) = dir {
match std::fs::remove_file(report_path(dir)) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => log::warn!("couldn't remove the hang report file: {e}"),
_ => {}
}
}
}
/// The window system `window` opened on, for [`Facts::window_system`].
pub fn window_system(window: Option<&winit::window::Window>) -> &'static str {
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
match window.and_then(|w| w.window_handle().ok()).map(|h| h.as_raw()) {
Some(RawWindowHandle::Wayland(_)) => "Wayland",
Some(RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) => "X11",
Some(RawWindowHandle::AppKit(_)) => "AppKit",
Some(RawWindowHandle::Win32(_)) => "Win32",
Some(_) => "other",
None => "unknown",
}
}
/// The present mode and frame queue the app asked the window surface for, for [`Facts::surface`];
/// `None` when the window has no wgpu renderer.
pub fn surface(config: Option<(String, Option<u32>)>) -> String {
match config {
Some((mode, Some(frames))) => format!("requested present mode {mode}, frame latency {frames}"),
Some((mode, None)) => format!("requested present mode {mode}"),
None => "no wgpu renderer".to_string(),
}
}
/// Start the watching thread; the report file goes in `dir` (none: the log only).
pub fn start(dir: Option<PathBuf>, shared: Arc<Shared>) {
let spawned = std::thread::Builder::new().name("hang-watch".into()).spawn(move || {
let mut watch = Watch::new(STALL);
let mut held = None;
loop {
std::thread::sleep(POLL);
#[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
let mut sample = BEACON.sample();
// An open menu of the menu bar waits for the user.
#[cfg(target_os = "macos")]
if super::mac_menu::is_tracking() {
sample.activity = Activity::Menu;
}
if let Some(event) = watch.check(shared.started.elapsed(), sample) {
record(event, sample, &BEACON, &shared, dir.as_deref(), &mut held, &CLOSING, SystemTime::now());
}
}
});
if let Err(e) = spawned {
log::warn!("no hang report this session: the watching thread didn't start: {e}");
}
}
#[cfg(test)]
mod tests;
+270
View File
@@ -0,0 +1,270 @@
use super::*;
use std::time::UNIX_EPOCH;
use vectorcraft_ui_egui::hang_beacon::{Activity, Stage};
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
fn sample(step: u64, stage: Stage) -> Sample {
Sample { step, stage, activity: Activity::None }
}
fn facts() -> Facts {
let env = |name: &str| match name {
"XDG_CURRENT_DESKTOP" => Some("KDE".to_string()),
"XDG_SESSION_TYPE" => Some("wayland\u{7}".to_string()),
_ => None,
};
Facts::new(env, true, "Wayland", Some("Test GPU (Vulkan, DiscreteGpu)".to_string()), surface(Some(("AutoVsync".to_string(), Some(1)))))
}
fn shared(previous: Option<String>) -> Shared {
Shared { facts: facts(), started: Instant::now(), last: Mutex::new(None), previous }
}
#[test]
fn a_stage_held_for_the_stall_time_is_reported_once_and_its_end_after_it() {
let mut w = Watch::new(STALL);
assert_eq!(w.check(ms(0), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(2_999), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(3_000), sample(5, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
assert_eq!(w.check(ms(9_000), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(9_500), sample(6, Stage::Idle)), Some(Event::Answered(ms(9_500))));
assert_eq!(w.check(ms(20_000), sample(6, Stage::Idle)), None);
}
#[test]
fn frames_that_keep_moving_and_an_idle_window_are_never_reported() {
let mut w = Watch::new(STALL);
// A long animation: the step changes at every read.
for n in 0..100 {
assert_eq!(w.check(ms(n * 500), sample(n, Stage::Drawing)), None);
}
// A window waiting for input for a minute.
for n in 0..120 {
assert_eq!(w.check(ms(50_000 + n * 500), sample(1_000, Stage::Idle)), None);
}
}
#[test]
fn a_file_dialog_shown_in_line_is_waiting_for_the_user_not_stalled() {
let mut w = Watch::new(STALL);
let dialog = Sample { step: 7, stage: Stage::Interface, activity: Activity::Dialog };
for n in 0..60 {
assert_eq!(w.check(ms(n * 500), dialog), None);
}
// Back from the dialog, the command goes on and is timed again.
assert_eq!(w.check(ms(30_000), sample(8, Stage::Interface)), None);
assert_eq!(w.check(ms(33_000), sample(8, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
}
#[test]
fn an_open_menu_bar_menu_is_waiting_for_the_user_not_stalled() {
let mut w = Watch::new(STALL);
let menu = Sample { step: 3, stage: Stage::Drawing, activity: Activity::Menu };
for n in 0..60 {
assert_eq!(w.check(ms(n * 500), menu), None);
}
}
#[test]
fn a_new_busy_step_starts_the_time_again() {
let mut w = Watch::new(STALL);
assert_eq!(w.check(ms(0), sample(1, Stage::Logic)), None);
assert_eq!(w.check(ms(2_500), sample(2, Stage::Interface)), None);
assert_eq!(w.check(ms(5_000), sample(2, Stage::Interface)), None);
assert_eq!(w.check(ms(5_500), sample(2, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
// A mark inside the stall (a clipboard read ending) is an answer.
assert_eq!(w.check(ms(6_000), sample(3, Stage::Interface)), Some(Event::Answered(ms(3_500))));
}
#[test]
fn the_report_names_the_stage_the_activity_the_commands_and_the_platform() {
let beacon = Beacon::new();
beacon.command("edit.copy");
beacon.command("edit.paste");
beacon.frame(FrameTime { work_ms: 1.24, previous_total_ms: Some(3.5) }, 2);
let s = Sample { step: 9, stage: Stage::Interface, activity: Activity::ClipboardRead };
let text = report(UNIX_EPOCH + Duration::from_secs(1_794_385_145), ms(3_240), s, &beacon, Duration::from_secs(754), &facts());
for want in [
"VectorCraft hang report, 2026-11-11T08:19:05.000Z",
"has not moved on for 3.2 s",
"Stage: running the interface",
"Waiting on: reading the system clipboard",
"Recent commands, oldest first: edit.copy, edit.paste",
"App work per frame (ms), oldest first: 1.2",
"without waiting for the display (ms), oldest first: 3.5",
"Session: running for 754 s, 2 documents open",
"Window system: Wayland; desktop: KDE; session type: wayland; Flatpak: yes",
"Graphics: Test GPU (Vulkan, DiscreteGpu); requested present mode AutoVsync, frame latency 1",
] {
assert!(text.contains(want), "{want:?} missing from:\n{text}");
}
}
#[test]
fn environment_values_lose_control_characters_and_are_cut_short() {
let long = "x".repeat(500);
let env = |name: &str| (name == "XDG_CURRENT_DESKTOP").then(|| format!("A\nB{long}"));
let f = Facts::new(env, false, "X11", None, String::new());
assert_eq!(f.desktop.as_deref().map(str::len), Some(MAX_VALUE_CHARS));
assert!(f.desktop.as_deref().is_some_and(|d| d.starts_with("ABx")));
assert!(!f.flatpak);
assert!(f.lines().contains("Graphics: unknown"));
}
#[test]
fn a_stall_writes_the_report_file_and_its_end_removes_it() {
let dir = tempfile::tempdir().unwrap();
let shared = shared(None);
let beacon = Beacon::new();
let s = sample(4, Stage::Drawing);
let (mut held, open) = (None, AtomicBool::new(false));
record(Event::Stalled(ms(3_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH);
let path = report_path(dir.path());
// Windows refuses reads through another handle while the file is locked: the length is read.
let last = shared.last.lock().unwrap().clone().unwrap_or_default();
assert!(last.contains("Stage: after a frame with input went to the renderer"));
assert_eq!(std::fs::metadata(&path).unwrap().len(), last.len() as u64);
// While the stall lasts, a launch of another instance leaves the file alone.
assert_eq!(take_previous(dir.path()), None);
assert!(path.exists());
record(Event::Answered(ms(4_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH);
assert!(!path.exists());
// This session's report stays for Copy Troubleshooting Info.
assert!(shared.last.lock().unwrap().is_some());
}
#[test]
fn closing_normally_removes_the_report_and_writes_no_more() {
let dir = tempfile::tempdir().unwrap();
let shared = shared(None);
let beacon = Beacon::new();
let (mut held, flag) = (None, AtomicBool::new(false));
record(Event::Stalled(ms(3_000)), sample(4, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
let path = report_path(dir.path());
assert!(path.exists());
// The interface answered after a frame with input, and the app quit before the watching thread
// looked again: saving and teardown are not timed.
beacon.enter(Stage::Drawing);
closing(Some(dir.path()), &flag, &beacon);
assert_eq!(beacon.sample().stage, Stage::Idle);
assert!(!path.exists());
assert_eq!(take_previous(dir.path()), None);
// The watching thread then sees the answer.
record(Event::Answered(ms(3_500)), sample(5, Stage::Idle), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
assert!(held.is_none());
// A stall the watching thread finds while the app closes goes to the log only.
record(Event::Stalled(ms(3_000)), sample(9, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
assert!(!path.exists());
assert!(held.is_none());
}
#[test]
fn the_next_launch_takes_a_left_report_once_and_keeps_a_copy() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(take_previous(dir.path()), None);
let left = dir.path().join(format!("{REPORT_PREFIX}4242.txt"));
std::fs::write(&left, "VectorCraft hang report, then\n").unwrap();
// Other files in the log folder are not reports.
std::fs::write(dir.path().join(format!("{REPORT_PREFIX}notes.txt")), "x").unwrap();
std::fs::write(dir.path().join(format!("{REPORT_PREFIX}17.txt")), "").unwrap();
assert_eq!(take_previous(dir.path()).as_deref(), Some("VectorCraft hang report, then\n"));
assert!(!left.exists());
assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "VectorCraft hang report, then\n");
assert_eq!(take_previous(dir.path()), None);
// An empty file may be one being written: it stays.
assert!(dir.path().join(format!("{REPORT_PREFIX}17.txt")).exists());
}
#[test]
fn of_several_left_reports_the_newest_is_kept_and_all_are_offered_oldest_first() {
let dir = tempfile::tempdir().unwrap();
for (pid, text, secs) in [(9, "newer\n", 2_000), (10, "older\n", 1_000)] {
let path = dir.path().join(format!("{REPORT_PREFIX}{pid}.txt"));
std::fs::write(&path, text).unwrap();
let file = std::fs::File::options().write(true).open(&path).unwrap();
file.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap();
}
assert_eq!(take_previous(dir.path()).as_deref(), Some("older\n\nnewer\n"));
assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "newer\n");
}
#[test]
fn a_report_that_cannot_be_moved_is_offered_once() {
let dir = tempfile::tempdir().unwrap();
// Something that is not a file is in the way.
std::fs::create_dir_all(dir.path().join(PREVIOUS_FILE).join("x")).unwrap();
let left = dir.path().join(format!("{REPORT_PREFIX}5.txt"));
std::fs::write(&left, "kept\n").unwrap();
assert_eq!(take_previous(dir.path()).as_deref(), Some("kept\n"));
assert!(!left.exists());
assert_eq!(take_previous(dir.path()), None);
}
#[test]
fn reports_beyond_the_newest_are_removed_not_left_for_a_later_launch() {
let dir = tempfile::tempdir().unwrap();
let count = MAX_REPORT_FILES + 3;
for n in 0..count {
let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n));
std::fs::write(&path, format!("report {n}\n")).unwrap();
let file = std::fs::File::options().write(true).open(&path).unwrap();
file.set_modified(UNIX_EPOCH + Duration::from_secs(1_000 + n as u64)).unwrap();
}
let text = take_previous(dir.path()).unwrap();
assert!(text.starts_with("report 3\n"), "{text}");
assert!(text.ends_with(&format!("report {}\n", count - 1)), "{text}");
assert!(!text.contains("report 2\n"));
assert_eq!(take_previous(dir.path()), None);
let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect();
assert_eq!(left, vec![std::ffi::OsString::from(PREVIOUS_FILE)]);
}
#[test]
fn newer_empty_files_do_not_push_out_an_abandoned_report() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join(format!("{REPORT_PREFIX}1.txt"));
std::fs::write(&old, "old\n").unwrap();
std::fs::File::options().write(true).open(&old).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(1_000)).unwrap();
for n in 0..MAX_REPORT_FILES + 1 {
let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n));
std::fs::write(&path, "").unwrap();
std::fs::File::options().write(true).open(&path).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(2_000)).unwrap();
}
assert_eq!(take_previous(dir.path()).as_deref(), Some("old\n"));
}
#[test]
fn a_file_system_without_locks_does_not_hide_a_report() {
use std::io::{Error, ErrorKind};
assert!(abandoned(Ok(())));
assert!(!abandoned(Err(std::fs::TryLockError::WouldBlock)));
assert!(abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::Unsupported)))));
// Any other error may hide a live session's lock: the file is left alone.
assert!(!abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::PermissionDenied)))));
}
#[test]
fn an_oversized_report_file_is_not_read() {
let dir = tempfile::tempdir().unwrap();
let big = vec![b'x'; usize::try_from(MAX_REPORT_BYTES).unwrap() + 1];
let left = dir.path().join(format!("{REPORT_PREFIX}7.txt"));
std::fs::write(&left, big).unwrap();
let text = take_previous(dir.path()).unwrap();
assert!(text.starts_with("The report was larger than"));
assert!(!left.exists());
}
#[test]
fn troubleshooting_info_holds_both_sessions_reports() {
let shared = shared(Some("VectorCraft hang report, last session\n".to_string()));
*shared.last.lock().unwrap() = Some("VectorCraft hang report, this session\n".to_string());
let beacon = Beacon::new();
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
assert!(text.starts_with("VectorCraft troubleshooting info, 1970-01-01T00:00:00.000Z\n"));
assert!(text.contains("This session's last hang report:\nVectorCraft hang report, this session\n"));
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
assert!(text.contains("Recent commands, oldest first: none"));
}
+27 -3
View File
@@ -120,7 +120,6 @@ fn make_folder(request: &PickRequest) {
#[cfg(not(target_os = "macos"))]
#[cfg_attr(windows, allow(unused_variables))]
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec<String> {
make_folder(request);
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
if let PickRequest::Save(pick) = request
&& let Some(answer) = portal_save::pick(pick, parent.as_deref())
@@ -139,7 +138,30 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
/// Show the dialog for `request` over `parent` now → the paths picked.
#[cfg(not(target_os = "macos"))]
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<String> {
show_dialog(file_dialog(&request, parent), &request, parent)
let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON;
marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent))
}
/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the
/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare`
/// is still timed.
#[cfg(not(target_os = "macos"))]
fn marked_dialog<T>(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T {
prepare();
let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog);
show()
}
#[cfg(all(test, not(target_os = "macos")))]
#[test]
fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() {
use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon};
let beacon = Beacon::new();
let mut preparing = None;
let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity);
assert_eq!(preparing, Some(Activity::None), "making the folder is timed");
assert_eq!(showing, Activity::Dialog, "the dialog is not");
assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog");
}
/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an
@@ -239,6 +261,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
std::thread::Builder::new()
.name("file-dialog".into())
.spawn(move || {
make_folder(&request);
// The app gone meanwhile has no use for the answer.
let _ = tx.send(show_dialog(dialog, &request, &parent));
ui.request_repaint();
@@ -363,7 +386,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
})),
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
system_clipboard: Some(clipboard::system_clipboard(clip)),
// Its calls are marked for the hang report (`hang_watch`).
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
// clipboard holds and macOS asks the pasteboard server, so they check in line.
+42
View File
@@ -30,6 +30,7 @@ mod control_server;
mod cursor_theme;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
#[cfg(target_os = "linux")]
mod linux_stylus;
mod logging;
@@ -123,6 +124,8 @@ struct App {
held_files: Vec<String>,
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
monitors_listed: Option<(f64, f32)>,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
}
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
@@ -293,6 +296,11 @@ fn main() -> std::process::ExitCode {
None => logger.no_file(),
}
}
// The report a session left when it was closed while it did not answer (`hang_watch`).
let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir));
if let Some(report) = &previous_hang {
log::warn!("the last session was closed while it did not answer; its report:\n{}", report.trim_end());
}
// The roots confine the control channel: a bad one keeps the app from starting rather than
// leaving agents unconfined. Without a control port there is nothing to confine.
let roots = if control_port.is_none() {
@@ -437,6 +445,9 @@ fn main() -> std::process::ExitCode {
open_documents::install();
#[cfg(feature = "wgpu")]
let created = startup.clone();
// For the hang report (`hang_watch`).
#[cfg(feature = "wgpu")]
let requested_surface = options.wgpu_options.surface;
// 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")]
@@ -537,6 +548,36 @@ fn main() -> std::process::ExitCode {
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
}
// The hang report and Help › Copy Troubleshooting Info (`hang_watch`).
// The surface settings the options asked for; the driver resolves the present mode.
#[cfg(feature = "wgpu")]
let surface = cc
.wgpu_render_state
.as_ref()
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
#[cfg(not(feature = "wgpu"))]
let surface = None;
let hang = std::sync::Arc::new(hang_watch::Shared {
facts: hang_watch::Facts::new(
|name| std::env::var(name).ok(),
std::path::Path::new("/.flatpak-info").exists(),
hang_watch::window_system(winit_window.as_deref()),
app.graphics_adapter.clone(),
hang_watch::surface(surface),
),
started: std::time::Instant::now(),
last: std::sync::Mutex::new(None),
previous: previous_hang.clone(),
});
vectorcraft_ui_egui::hang_beacon::watch_input(&vectorcraft_ui_egui::hang_beacon::BEACON, &cc.egui_ctx);
hang_watch::start(log_dir().filter(|_| prefs_enabled()), hang.clone());
app.services.troubleshooting = Some(Box::new(move || {
hang_watch::troubleshooting(&hang, &vectorcraft_ui_egui::hang_beacon::BEACON, std::time::SystemTime::now())
}));
// A message about the graphics processor, or a stopped plug-in, comes first.
if previous_hang.is_some() && app.ui.status.is_empty() {
vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app);
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.desktop_frame = !custom_titlebar;
@@ -583,6 +624,7 @@ fn main() -> std::process::ExitCode {
maximize_tries: 8,
held_files,
monitors_listed: None,
frame_start: None,
}))
}),
)
+12 -1
View File
@@ -281,6 +281,10 @@ pub struct DxfOptions {
pub scale_lineweights: bool,
pub colors: ColorDepth,
pub raster: RasterFormat,
/// Placed images are written as IMAGE entities with their files (else left out, undecoded).
pub include_images: bool,
/// Filled areas get a solid HATCH after their outlines (else the outlines alone).
pub include_hatches: bool,
pub preserve: Preserve,
/// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`]
/// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have
@@ -303,6 +307,8 @@ impl Default for DxfOptions {
scale_lineweights: false,
colors: ColorDepth::default(),
raster: RasterFormat::default(),
include_images: true,
include_hatches: true,
preserve: Preserve::default(),
alter_paths: false,
outline_text: false,
@@ -322,7 +328,8 @@ pub enum DxfPreset {
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
/// and placed images as PNG.
/// and placed images and fill hatches left out (fills are their outlines), with PNG as the
/// format images take when they are put back in.
Cnc,
}
@@ -360,6 +367,8 @@ impl DxfPreset {
scale_lineweights: false,
colors: ColorDepth::Aci256,
raster: RasterFormat::Png,
include_images: false,
include_hatches: false,
preserve: Preserve::Editability,
alter_paths: false,
outline_text: true,
@@ -377,6 +386,8 @@ impl DxfPreset {
&& o.scale_lineweights == c.scale_lineweights
&& o.colors == c.colors
&& o.raster == c.raster
&& o.include_images == c.include_images
&& o.include_hatches == c.include_hatches
&& o.preserve == c.preserve
&& o.alter_paths == c.alter_paths
&& o.outline_text == c.outline_text;
+44 -5
View File
@@ -1,5 +1,6 @@
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with
//! hatches left out), placed images are linked image files unless left out, strokes
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
//! filled outlines where the look needs them.
@@ -28,6 +29,8 @@ const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are wr
const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque";
const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines";
const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out";
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
const WIDE_LINES: &str =
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
@@ -339,6 +342,32 @@ fn subpaths(bp: &BezPath) -> Vec<Sub> {
out
}
/// `bp` with each open subpath that can enclose an area closed, as a fill closes it: two or more
/// segments, or one curve. A single straight segment stays open.
fn closed_fill(bp: &BezPath) -> BezPath {
let mut out = BezPath::new();
let (mut segs, mut curved) = (0usize, false);
let close = |out: &mut BezPath, segs: usize, curved: bool| {
if segs >= 2 || (segs == 1 && curved) {
out.close_path();
}
};
for el in bp.elements() {
match *el {
PathEl::MoveTo(_) => {
close(&mut out, segs, curved);
(segs, curved) = (0, false);
}
PathEl::ClosePath => (segs, curved) = (0, false),
PathEl::LineTo(_) => segs += 1,
PathEl::QuadTo(..) | PathEl::CurveTo(..) => (segs, curved) = (segs + 1, true),
}
out.push(*el);
}
close(&mut out, segs, curved);
out
}
/// The most pixels of an image written (it is held decoded, as RGBA and encoded at once).
const MAX_IMAGE_PIXELS: u64 = 64 << 20;
@@ -878,13 +907,13 @@ impl<'a> Scene<'a> {
Some(vectorcraft_brush::stroke_pieces(doc, b, bp, st))
}
/// A filled area as its outlines followed by a solid hatch (R12: the outlines alone). Laser
/// and cutter software reads the outlines and skips hatches. `clean`: the path has no
/// A filled area as its outlines followed by a solid hatch (R12, or with hatches left out: the
/// outlines alone). Laser and cutter software reads the outlines and skips hatches. `clean`: the path has no
/// overlaps, so the hatch's even-odd rule reads it as it is.
fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) {
if !self.o.version.handles() {
self.warn(NO_FILLS);
self.lines(bp, style, 0.0);
self.lines(&closed_fill(bp), style, 0.0);
return;
}
let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1;
@@ -893,11 +922,17 @@ impl<'a> Scene<'a> {
.flatten()
.map(|p| p.to_bezpath());
let outline = normalized.as_ref().unwrap_or(bp);
// A fill with no loop of three points or more encloses no area: no outline and no hatch.
let loops: Vec<Vec<Point>> = polygons(outline).into_iter().filter(|p| p.len() >= 3).collect();
if loops.is_empty() {
return;
}
self.lines(outline, style, 0.0);
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
self.lines(&closed_fill(outline), style, 0.0);
if !self.o.include_hatches {
self.warn(HATCHES_OFF);
return;
}
let h = self.handle();
let layer = self.layer.clone();
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
@@ -1285,6 +1320,10 @@ impl<'a> Scene<'a> {
self.warn(NO_IMAGES);
return;
}
if !self.o.include_images {
self.warn(IMAGES_OFF);
return;
}
let Some(i) = self.image_def(im) else { return };
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
+141
View File
@@ -843,10 +843,151 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
assert!(out.images.is_empty());
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
assert_eq!(DxfPreset::of(&DxfOptions { include_images: true, ..o.clone() }), DxfPreset::Custom);
assert_eq!(DxfPreset::of(&DxfOptions { include_hatches: true, ..o.clone() }), DxfPreset::Custom);
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
}
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
/// `fill`'s rectangle.
fn image_and_fill_doc(fill: Paint) -> Document {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
vec![
path(d, shapes::rectangle(Rect::new(50.0, 10.0, 150.0, 60.0)), fill, Paint::None, 0.0),
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d
}
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
#[test]
fn fills_without_hatches_keep_their_outlines() {
let d = shapes_doc();
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
assert_eq!(out.warnings, [HATCHES_OFF]);
let e = entities(&out);
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
// Hatches stay by default, with no note.
let on = export(&d, &opts(&d)).unwrap();
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
let compound = doc_with(|d| {
let mut bp = shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 60.0)).to_bezpath();
bp.extend(shapes::rectangle(Rect::new(40.0, 40.0, 90.0, 90.0)).to_bezpath().elements().iter().copied());
let p = PathData::from_bezpath(&bp);
vec![
path(d, p, Paint::solid(Color::BLACK), Paint::None, 0.0),
path(d, shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 70.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
path(d, shapes::line(Point::new(100.0, 10.0), Point::new(150.0, 60.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
]
});
let without_hatches = |o: &DxfOutput| {
let mut e = entities(o);
e.retain(|x| kind(x) != "HATCH");
e.into_iter().map(|x| x.into_iter().filter(|p| p.0 != 5).collect::<Pairs>()).collect::<Vec<_>>()
};
let (c_on, c_off) =
(export(&compound, &opts(&compound)).unwrap(), export(&compound, &DxfOptions { include_hatches: false, ..opts(&compound) }).unwrap());
assert_eq!(kinds(&c_on), ["LWPOLYLINE", "HATCH"], "one merged outline");
assert_eq!(without_hatches(&c_off), without_hatches(&c_on));
assert_eq!(without_hatches(&out), without_hatches(&on));
// Strokes outlined for their look are areas too: their outlines stay.
let altered =
export(&d, &DxfOptions { include_hatches: false, alter_paths: true, preserve: Preserve::Editability, version: DxfVersion::R14, ..opts(&d) })
.unwrap();
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
// Nothing filled: no note.
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
// R12 has no hatches anyway: the same outlines, and its own note alone.
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
let (off, on) = (r12(false), r12(true));
assert_eq!(off.bytes, on.bytes);
assert_eq!(off.warnings, on.warnings);
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
}
#[test]
fn an_open_path_s_fill_outline_keeps_its_closing_edge() {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((10.0, 10.0));
bp.line_to((90.0, 10.0));
bp.line_to((50.0, 80.0));
let open = PathData::from_bezpath(&bp);
let d = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)]);
let closed = |e: &Pairs| get(e, 70).and_then(|v| v.trim().parse::<i64>().ok()).is_some_and(|v| v & 1 == 1);
for include_hatches in [false, true] {
let out = export(&d, &DxfOptions { include_hatches, ..opts(&d) }).unwrap();
let e: Vec<Pairs> = entities(&out).into_iter().filter(|x| kind(x) == "LWPOLYLINE").collect();
assert_eq!(e.len(), 2, "the fill's outline and the stroke: {:?}", kinds(&out));
assert!(closed(&e[0]), "the fill's outline closes as the fill does (hatches {include_hatches})");
assert!(!closed(&e[1]), "the stroke stays open (hatches {include_hatches})");
}
// R12 writes the outline alone, closed too.
let fill_only = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::None, 0.0)]);
let r12 = export(&fill_only, &DxfOptions { version: DxfVersion::R12, ..opts(&fill_only) }).unwrap();
let e = entities(&r12);
assert_eq!(kind(&e[0]), "POLYLINE", "{:?}", kinds(&r12));
assert!(closed(&e[0]), "R12's outline closes as the fill does");
}
#[test]
fn images_can_be_left_out_with_their_files() {
let d = image_and_fill_doc(Paint::None);
let out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
assert!(entities(&out).is_empty() && out.images.is_empty(), "{:?}", kinds(&out));
let p = pairs(&out.bytes);
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
assert_eq!(out.warnings, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
// R12 has no images anyway: its own note alone.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
}
#[test]
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let run = |o: DxfOptions| export(&d, &DxfOptions { region: d.artboards[0].rect, ..o }).unwrap();
let both = run(DxfOptions::default());
assert_eq!(kinds(&both), ["LWPOLYLINE", "HATCH", "IMAGE"]);
assert_eq!(both.images.len(), 1);
let no_images = run(DxfOptions { include_images: false, ..DxfOptions::default() });
assert_eq!((kinds(&no_images), no_images.images.len()), (vec!["LWPOLYLINE".to_string(), "HATCH".into()], 0));
let no_hatches = run(DxfOptions { include_hatches: false, ..DxfOptions::default() });
assert_eq!((kinds(&no_hatches), no_hatches.images.len()), (vec!["LWPOLYLINE".to_string(), "IMAGE".into()], 1));
// CNC / CAM: the cutting path alone, with no image file and both notes.
let cnc = run(DxfPreset::Cnc.options());
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
assert!(cnc.images.is_empty());
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
let custom = DxfPreset::Custom.options();
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
}
#[test]
fn layers_become_dxf_layers() {
let mut d = shapes_doc();
+184 -1
View File
@@ -9,7 +9,7 @@ use std::sync::{Arc, OnceLock};
use serde::{Deserialize, Serialize};
use crate::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup};
use crate::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup};
/// A library: its name, its ungrouped swatches and its colour groups.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -72,6 +72,7 @@ pub const GRADIENT_LIBRARIES: &[BuiltinLibrary] = &[
lib!("spectrum-gradients", "Spectrum Gradients", spectrum_gradients),
lib!("sky-gradients", "Sky Gradients", sky_gradients),
lib!("neutral-gradients", "Neutral Gradients", neutral_gradients),
lib!("organic-fades", "Organic Fades", organic_fades),
lib!("duotone-gradients", "Duotone Gradients", duotone_gradients),
lib!("radial-glows", "Radial Glows", radial_glows),
];
@@ -179,6 +180,14 @@ pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32
Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false }
}
/// A gradient swatch mixed by `method` through `stops` of (offset, color, opacity, midpoint).
fn gradient_with(name: &str, kind: GradientKind, method: GradientMethod, stops: &[(f32, Color, f32, f32)]) -> Swatch {
let stops =
stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect();
let gradient = Gradient { method, ..Gradient::new(kind, stops) };
Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(gradient))), global: false, spot: false }
}
/// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1),
/// named "`name` 1"…
fn ramp(name: &str, n: usize, (l0, l1): (f64, f64), c: impl Fn(f64) -> f64, h: impl Fn(f64) -> f64) -> SwatchGroup {
@@ -387,6 +396,141 @@ fn radial_glows() -> (Vec<Swatch>, Vec<SwatchGroup>) {
(s, vec![])
}
/// A stop of [`organic_fades`]: offset, OKLCH `(l, c, h°)`, opacity and midpoint.
type FadeStop = (f32, (f64, f64, f64), f32, f32);
/// Soft fades through a few unevenly spaced stops with off-center midpoints, mixed perceptually,
/// that thin out to transparent: at the end of the linear ones and at the edge of the radial ones.
fn organic_fades() -> (Vec<Swatch>, Vec<SwatchGroup>) {
use GradientKind::{Linear, Radial};
let fades: [(&str, GradientKind, &[FadeStop]); 15] = [
(
"Mist",
Linear,
&[
(0.0, (0.94, 0.012, 240.0), 1.0, 0.38),
(0.35, (0.86, 0.03, 235.0), 0.85, 0.62),
(0.7, (0.8, 0.035, 230.0), 0.4, 0.45),
(1.0, (0.78, 0.035, 230.0), 0.0, 0.5),
],
),
(
"Petal",
Linear,
&[
(0.0, (0.82, 0.09, 350.0), 1.0, 0.42),
(0.28, (0.88, 0.07, 10.0), 0.9, 0.66),
(0.64, (0.93, 0.04, 30.0), 0.45, 0.35),
(1.0, (0.95, 0.03, 40.0), 0.0, 0.5),
],
),
("Fern", Linear, &[(0.0, (0.52, 0.1, 145.0), 1.0, 0.6), (0.4, (0.68, 0.11, 135.0), 0.75, 0.4), (1.0, (0.85, 0.08, 120.0), 0.0, 0.5)]),
(
"Smoke",
Linear,
&[
(0.0, (0.35, 0.01, 260.0), 1.0, 0.3),
(0.22, (0.48, 0.012, 255.0), 0.8, 0.58),
(0.58, (0.62, 0.01, 250.0), 0.35, 0.7),
(1.0, (0.72, 0.008, 250.0), 0.0, 0.5),
],
),
(
"Honey",
Linear,
&[
(0.0, (0.72, 0.15, 70.0), 1.0, 0.55),
(0.3, (0.8, 0.14, 80.0), 0.9, 0.35),
(0.75, (0.9, 0.09, 90.0), 0.3, 0.6),
(1.0, (0.95, 0.05, 95.0), 0.0, 0.5),
],
),
("Seafoam", Linear, &[(0.0, (0.7, 0.09, 175.0), 1.0, 0.45), (0.45, (0.84, 0.07, 170.0), 0.6, 0.65), (1.0, (0.95, 0.03, 165.0), 0.0, 0.5)]),
(
"Lavender",
Linear,
&[
(0.0, (0.62, 0.12, 300.0), 1.0, 0.36),
(0.3, (0.72, 0.1, 295.0), 0.85, 0.55),
(0.55, (0.82, 0.07, 290.0), 0.5, 0.68),
(0.82, (0.9, 0.04, 285.0), 0.15, 0.4),
(1.0, (0.93, 0.03, 285.0), 0.0, 0.5),
],
),
("Driftwood", Linear, &[(0.0, (0.55, 0.04, 60.0), 1.0, 0.64), (0.38, (0.68, 0.035, 70.0), 0.7, 0.42), (1.0, (0.84, 0.025, 80.0), 0.0, 0.5)]),
(
"Ink Wash",
Linear,
&[
(0.0, (0.25, 0.05, 265.0), 1.0, 0.28),
(0.18, (0.35, 0.06, 262.0), 0.9, 0.6),
(0.5, (0.5, 0.05, 258.0), 0.45, 0.72),
(1.0, (0.65, 0.04, 255.0), 0.0, 0.5),
],
),
(
"Tide",
Linear,
&[
(0.0, (0.45, 0.1, 230.0), 1.0, 0.4),
(0.26, (0.6, 0.1, 215.0), 0.8, 0.62),
(0.72, (0.76, 0.08, 200.0), 0.35, 0.44),
(1.0, (0.88, 0.05, 195.0), 0.0, 0.5),
],
),
(
"Bloom",
Radial,
&[
(0.0, (0.92, 0.05, 40.0), 1.0, 0.4),
(0.22, (0.8, 0.12, 20.0), 0.95, 0.6),
(0.6, (0.7, 0.14, 355.0), 0.4, 0.35),
(1.0, (0.66, 0.13, 345.0), 0.0, 0.5),
],
),
("Dew", Radial, &[(0.0, (0.97, 0.01, 200.0), 1.0, 0.3), (0.3, (0.88, 0.05, 195.0), 0.7, 0.58), (1.0, (0.8, 0.06, 190.0), 0.0, 0.5)]),
(
"Pollen",
Radial,
&[
(0.0, (0.96, 0.08, 100.0), 1.0, 0.45),
(0.18, (0.9, 0.15, 95.0), 1.0, 0.65),
(0.55, (0.82, 0.16, 85.0), 0.5, 0.4),
(1.0, (0.76, 0.15, 75.0), 0.0, 0.5),
],
),
// A ring: clear at the center, then a band that fades out to the edge.
(
"Halo",
Radial,
&[
(0.0, (0.98, 0.005, 90.0), 0.0, 0.6),
(0.42, (0.95, 0.02, 85.0), 0.0, 0.35),
(0.62, (0.92, 0.04, 80.0), 1.0, 0.55),
(1.0, (0.88, 0.05, 75.0), 0.0, 0.5),
],
),
(
"Lichen",
Radial,
&[
(0.0, (0.8, 0.07, 120.0), 1.0, 0.58),
(0.35, (0.7, 0.08, 130.0), 0.75, 0.4),
(0.74, (0.6, 0.07, 140.0), 0.25, 0.62),
(1.0, (0.55, 0.06, 145.0), 0.0, 0.5),
],
),
];
let s = fades
.iter()
.map(|&(name, kind, stops)| {
let stops: Vec<(f32, Color, f32, f32)> = stops.iter().map(|&(at, (l, c, h), opacity, mid)| (at, oklch(l, c, h), opacity, mid)).collect();
gradient_with(name, kind, GradientMethod::Perceptual, &stops)
})
.collect();
(s, vec![])
}
/// The sequential scales of [`perceptual`]: name and anchors of rising lightness.
const SEQUENTIAL: [(&str, Anchors); 5] = [
("Ember", &[(0.22, 0.10, 300.0), (0.55, 0.18, 30.0), (0.93, 0.15, 100.0)]),
@@ -532,6 +676,45 @@ mod tests {
let st = &g.gradient.stops;
assert!(st.len() >= 2 && st.windows(2).all(|w| w[0].offset <= w[1].offset), "{}", s.name);
assert!(st.iter().all(|s| (0.0..=1.0).contains(&s.offset) && (0.0..=1.0).contains(&s.opacity)));
assert!(st.iter().all(|s| (0.01..=0.99).contains(&s.midpoint)), "{}: a midpoint out of range", s.name);
}
}
}
}
#[test]
fn organic_fades_are_perceptual_multi_stop_fades_to_transparent() {
let lib = builtin_library("organic-fades").unwrap();
assert_eq!(GRADIENT_LIBRARIES.iter().map(|b| b.name).position(|n| n == "Organic Fades"), Some(3), "after Neutral Gradients");
assert!(lib.groups.is_empty() && (12..=16).contains(&lib.len()), "{} swatches", lib.len());
let radial = lib.iter().filter(|s| matches!(&s.paint, Paint::Gradient(g) if g.gradient.kind == GradientKind::Radial)).count();
assert!(radial >= 3 && radial * 2 <= lib.len(), "{radial} radial of {}", lib.len());
for s in lib.iter() {
let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) };
let (g, n) = (&g.gradient, &s.name);
assert_eq!(g.method, GradientMethod::Perceptual, "{n}");
assert!((3..=5).contains(&g.stops.len()), "{n}: {} stops", g.stops.len());
assert!(g.stops.windows(2).all(|w| w[0].offset < w[1].offset), "{n}: rising offsets");
assert_eq!((g.stops[0].offset, g.stops[g.stops.len() - 1].offset), (0.0, 1.0), "{n}");
// Unevenly spaced: some gap differs from an even step.
let even = 1.0 / (g.stops.len() - 1) as f32;
assert!(g.stops.windows(2).any(|w| (w[1].offset - w[0].offset - even).abs() > 0.02), "{n}: uneven stops");
// Every segment's midpoint is off center and within the Gradient panel's 13 to 87%.
let segments = &g.stops[..g.stops.len() - 1];
assert!(segments.iter().all(|st| (st.midpoint - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&st.midpoint)), "{n}: midpoints");
// Fully opaque somewhere, and clear at the end (the edge of a radial one).
assert!(g.stops.iter().any(|st| st.opacity == 1.0), "{n}: an opaque stop");
assert_eq!(g.stops[g.stops.len() - 1].opacity, 0.0, "{n}: clear at the end");
}
}
#[test]
fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() {
for b in builtins().filter(|b| b.id != "organic-fades") {
for s in builtin_library(b.id).unwrap().iter() {
if let Paint::Gradient(g) = &s.paint {
assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name);
assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name);
}
}
}
+24 -6
View File
@@ -1052,11 +1052,27 @@ fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option<Vec<usize>> {
/// its handles) moved onto the key's centre, so moving a key moves its end of the spine;
/// - a spine from Replace Spine: its first subpath, `None` for the anchors (the keys spread
/// evenly along it by arc length).
///
/// `None` for a blend made without a spine ([`BlendSpec::no_spine`]).
pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Option<Vec<usize>>)> {
if spec.no_spine {
return None;
}
layout_spine(keys, spec)
}
/// The spine `spec` stores, unless the blend was made without one.
fn stored_spine(spec: &BlendSpec) -> Option<&PathData> {
spec.spine.as_ref().filter(|_| !spec.no_spine)
}
/// [`blend_spine`] for placing the steps: a blend made without a spine still places them on the
/// straight lines between its key centers.
fn layout_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Option<Vec<usize>>)> {
if keys.len() < 2 {
return None;
}
let Some(stored) = &spec.spine else {
let Some(stored) = stored_spine(spec) else {
let centers: Vec<Point> = keys.iter().map(|k| center_of(k)).collect();
return Some((PathData::single(SubPath::polyline(&centers, false)), Some((0..keys.len()).collect())));
};
@@ -1127,10 +1143,10 @@ impl Rail {
/// `None` when nothing moves: no stored spine and the steps keep the page's orientation.
fn new(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Self> {
let rotate = spec.orientation == BlendOrientation::AlignToPath;
if spec.spine.is_none() && !rotate {
if stored_spine(spec).is_none() && !rotate {
return None;
}
let (path, anchors) = blend_spine(keys, spec)?;
let (path, anchors) = layout_spine(keys, spec)?;
let spine = Spine::new(&path)?;
let total = spine.length();
let k = keys.len();
@@ -1192,10 +1208,10 @@ impl Rail {
/// spine it is moved to, and so does its own centre, which it turns about. `None` when nothing
/// moves.
pub(crate) fn rail_reach(keys: &[Arc<Node>], spec: &BlendSpec, symbols: Option<&crate::SymbolBoxes>) -> Option<Rect> {
if spec.spine.is_none() && spec.orientation != BlendOrientation::AlignToPath {
if stored_spine(spec).is_none() && spec.orientation != BlendOrientation::AlignToPath {
return None;
}
let spine = blend_spine(keys, spec)?.0.bounds()?;
let spine = layout_spine(keys, spec)?.0.bounds()?;
let radius = keys
.iter()
.filter_map(|k| {
@@ -1404,7 +1420,9 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
for j in 1..=n {
// Even position of the step, then where the easing puts its shape and its colours.
let u = j as f64 / (n + 1) as f64;
let (t, tc) = (if rail.is_some() { spec.ease.apply(u) } else { u }, spec.color_position(u));
// Easing needs a spine: a blend made without one keeps its steps evenly spaced.
let eased = rail.is_some() && !spec.no_spine;
let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u));
let mut s = lerp.at_eased(t, tc);
if let Some(r) = &rail {
r.place(&mut s, i, t);
+13
View File
@@ -503,6 +503,19 @@ impl Document {
id
}
/// [`Document::next_artboard_id`] when `top` is the highest id the artboards have (`None`: there
/// are none). It reads no artboard unless that id is `u32::MAX`, so a caller that adds many
/// artboards and keeps `top` up to date gets each id in constant time.
pub fn next_artboard_id_above(&self, top: Option<u32>) -> u32 {
match top.unwrap_or(0).max(self.retired_artboard_id.get()).checked_add(1) {
Some(id) => {
self.retired_artboard_id.raise(id);
id
}
None => self.next_artboard_id(),
}
}
/// Record that the artboard with `id` was deleted: no later artboard takes its id.
pub fn retire_artboard_id(&self, id: u32) {
self.retired_artboard_id.raise(id);
+1 -1
View File
@@ -49,7 +49,7 @@ mod expand;
mod mesh;
mod warp;
pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec};
pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec, BlendSpineMode};
#[cfg(test)]
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
+63
View File
@@ -107,6 +107,11 @@ pub struct BlendSpec {
/// on anchor points); `None`: chosen so closed shapes don't twist.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub starts: Vec<Option<u32>>,
/// The blend was made without a spine (Create Spine › Never): it has no spine to show, edit,
/// reverse or release, and no easing. Its steps still sit on the straight lines between the
/// key centers. Replace Spine gives it one.
#[serde(default, rename = "noSpine", skip_serializing_if = "is_false", deserialize_with = "lenient_bool")]
pub no_spine: bool,
}
impl BlendSpec {
@@ -116,6 +121,41 @@ impl BlendSpec {
}
}
/// The Blend panel's Create Spine setting: whether a new blend gets a spine.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BlendSpineMode {
/// The usual rule: every new blend gets a spine, the straight lines between its key centers.
#[default]
Auto,
/// Every new blend gets a spine, whatever its key objects are.
Always,
/// New blends get no spine.
Never,
}
impl BlendSpineMode {
/// Every mode, in the order the Blend panel lists them.
pub const ALL: [Self; 3] = [Self::Auto, Self::Always, Self::Never];
pub fn id(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Always => "always",
Self::Never => "never",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.id() == id)
}
/// Whether a new blend made with this mode gets a spine.
pub fn creates_spine(self) -> bool {
self != Self::Never
}
}
/// Blend Options set with no blend selected: what new blends start with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BlendDefaults {
@@ -123,6 +163,29 @@ pub struct BlendDefaults {
pub spacing: BlendSpacing,
#[serde(default)]
pub orientation: BlendOrientation,
/// Create Spine (`object.blend.createSpine`).
#[serde(default, rename = "createSpine", skip_serializing_if = "is_auto", deserialize_with = "spine_mode")]
pub create_spine: BlendSpineMode,
}
fn is_false(v: &bool) -> bool {
!*v
}
fn is_auto(v: &BlendSpineMode) -> bool {
*v == BlendSpineMode::Auto
}
/// Reading a native file never fails over a `noSpine` that is not a boolean: the blend keeps its
/// spine.
fn lenient_bool<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
Ok(serde_json::Value::deserialize(d)?.as_bool().unwrap_or(false))
}
/// Reading the preferences never fails over an unknown Create Spine value: it becomes Auto.
fn spine_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BlendSpineMode, D::Error> {
let v = serde_json::Value::deserialize(d)?;
Ok(v.as_str().and_then(BlendSpineMode::from_id).unwrap_or_default())
}
/// Reading a native file never fails over one bad blend number: out-of-range values clamp,
+84
View File
@@ -156,6 +156,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "outlines-rules", name: "Outlines and Rules", make: outlines_rules },
BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn },
BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures },
BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched },
BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes },
BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects },
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
@@ -323,6 +324,59 @@ fn hand_drawn() -> Vec<GraphicStyle> {
]
}
/// Painted and Sketched: one catalog paint or sketch effect over the whole appearance, so it
/// repaints the fill and the stroke together (watercolor, dry brush, pastels, charcoal and ink).
fn painted_sketched() -> Vec<GraphicStyle> {
vec![
style(
"Washed Blue",
vec![F(fill("#8ab9c9"))],
vec![fx("artistic.watercolor", json!({"brushDetail": 8.0, "shadowIntensity": 2.0, "texture": 2.0}))],
),
style(
"Bristle Ochre",
vec![F(fill("#c4975a")), S(stroke("#76533d", 1.0))],
vec![fx("artistic.dryBrush", json!({"brushSize": 4.0, "brushDetail": 7.0, "texture": 2.0}))],
),
style(
"Pastel Heather",
vec![F(fill("#a78ca5"))],
vec![fx(
"artistic.roughPastels",
json!({
"strokeLength": 8.0,
"strokeDetail": 9.0,
"texture": "canvas",
"scaling": 100.0,
"relief": 5.0,
"lightDirection": "topLeft",
"invert": false
}),
)],
),
style(
"Charcoal Shade",
vec![F(fill("#666666"))],
vec![fx("sketch.charcoal", json!({"thickness": 3.0, "detail": 3.0, "lightDarkBalance": 55.0}))],
),
style(
"Ink Contour",
vec![F(fill("#d9e2df")), S(stroke("#26323b", 1.0))],
vec![fx("brushStrokes.inkOutlines", json!({"strokeLength": 6.0, "darkIntensity": 24.0, "lightIntensity": 8.0}))],
),
style(
"Wet Ink",
vec![F(fill("#637b85"))],
vec![fx("brushStrokes.sumiE", json!({"strokeWidth": 7.0, "strokePressure": 5.0, "contrast": 20.0}))],
),
style(
"Fine Pen",
vec![F(fill("#d8d4c6"))],
vec![fx("sketch.graphicPen", json!({"strokeLength": 6.0, "lightDarkBalance": 55.0, "strokeDirection": "rightDiagonal"}))],
),
]
}
/// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and
/// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper).
fn textures() -> Vec<GraphicStyle> {
@@ -603,6 +657,36 @@ mod tests {
assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn");
}
#[test]
fn painted_and_sketched_follows_textures_with_one_effect_per_style() {
let ids: Vec<&str> = STYLE_LIBRARIES.iter().map(|b| b.id).collect();
let at = ids.iter().position(|&id| id == "painted-sketched").expect("listed");
assert_eq!(ids[at - 1], "textures");
let lib = builtin_style_library("painted-sketched").unwrap();
assert_eq!(lib.name, "Painted and Sketched");
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Washed Blue", "Bristle Ochre", "Pastel Heather", "Charcoal Shade", "Ink Contour", "Wet Ink", "Fine Pen"]);
let effects: Vec<&str> = lib.styles.iter().flat_map(|g| g.appearance.effects.iter().map(|e| e.id.as_str())).collect();
assert_eq!(
effects,
[
"artistic.watercolor",
"artistic.dryBrush",
"artistic.roughPastels",
"sketch.charcoal",
"brushStrokes.inkOutlines",
"brushStrokes.sumiE",
"sketch.graphicPen"
]
);
assert!(lib.styles.iter().all(|g| g.appearance.items.iter().all(|i| i.effects().is_empty())), "no effects on a fill or stroke");
// No other built-in library holds a style of the same name.
for b in STYLE_LIBRARIES.iter().filter(|b| b.id != "painted-sketched") {
let other = builtin_style_library(b.id).unwrap();
assert!(other.styles.iter().all(|g| !names.contains(&g.name.as_str())), "{}", b.id);
}
}
#[test]
fn vcstyles_round_trip() {
let mut lib = (*builtin_style_library("gradient-finishes").unwrap()).clone();
+9
View File
@@ -28,6 +28,15 @@ pub struct TabStop {
pub align_on: char,
}
impl TabStop {
/// The largest stop position `text.tabs.set` and a paragraph style take, in points.
pub const MAX_POSITION: f64 = 100_000.0;
/// The most leader characters a stop repeats.
pub const MAX_LEADER: usize = 8;
/// The most stops `text.tabs.set` and a paragraph style take in one list.
pub const MAX_STOPS: usize = 256;
}
fn default_align_on() -> char {
'.'
}
+17
View File
@@ -507,6 +507,23 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
}
}
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
/// for a command that looks its objects up itself, outside the document's layers too.
pub(crate) fn given_object_ids(p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
return ids_param(p, "ids", command);
}
match p.get("id").filter(|v| !v.is_null()) {
None => Ok(None),
Some(Value::String(r)) if r.starts_with('$') => {
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
Some(v) => {
let id = v.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {v}: expected a non-negative integer")))?;
Ok(Some(vec![id]))
}
}
}
/// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list.
pub(crate) fn index(v: u64) -> usize {
usize::try_from(v).unwrap_or(usize::MAX)
+16 -10
View File
@@ -520,7 +520,7 @@ pub(crate) fn levels(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4], setting
/// the tolerance plus the softness on, and in proportion between them.
fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 {
let Settings { tolerance, softness, measure, .. } = *settings;
let d = refs.iter().map(|r| apart(c, *r, measure)).fold(f64::INFINITY, f64::min);
let d = percent(refs.iter().map(|r| gap(c, *r, measure)).fold(f64::INFINITY, f64::min), measure);
if d <= tolerance {
0
} else if d >= tolerance + softness {
@@ -530,16 +530,22 @@ fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 {
}
}
/// How far apart `a` and `b` are, as a percentage, measured as `measure` says: the RGB distance of
/// the largest one (black to white), or the largest difference on one channel of the channel's range.
/// A difference of `k` 8-bit steps on one channel is exactly `k / 255 × 100` with channels.
fn apart(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 {
/// How far apart `a` and `b` are, measured as `measure` says, before `percent` converts it: the
/// squared RGB distance, or the largest difference on one channel.
fn gap(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 {
match measure {
Match::Distance => {
let sq: f64 = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum();
sq.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0
}
Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)) / 65_535.0 * 100.0,
Match::Distance => a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum(),
Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)),
}
}
/// A `gap` as a percentage: of the largest RGB distance (black to white) with distance, or of the
/// channel's range with channels. A difference of `k` 8-bit steps on one channel is exactly
/// `k / 255 × 100` with channels.
fn percent(gap: f64, measure: Match) -> f64 {
match measure {
Match::Distance => gap.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0,
Match::Channels => gap / 65_535.0 * 100.0,
}
}
+11 -2
View File
@@ -33,8 +33,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_remove,
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_options, brush_place_art,
brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush,
};
pub(crate) use dynamic::{edit_part, part_only, selected_part};
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
@@ -67,6 +67,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
brush_selection_art
),
cmd!(
"brush.placeArt",
"Place Brush Art",
[],
None,
"{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}",
has_doc,
brush_place_art
),
cmd!(
"brush.apply",
"Apply Brush",
+87
View File
@@ -483,6 +483,93 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "name": out }))
}
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
/// places them.
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
/// The space between the pattern brush tiles `brush.placeArt` places, in points.
const TILE_GAP: f64 = 10.0;
/// The message for a brush that is not made of art.
fn no_art(name: &str) -> String {
format!("`{name}` has no art (only scatter, art and pattern brushes do)")
}
/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art.
fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> {
match i {
0 => Some((&p.side, p.side_frame)),
1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)),
2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)),
3 => p.start.as_ref().map(|n| (n, p.start_frame)),
_ => p.end.as_ref().map(|n| (n, p.end_frame)),
}
}
/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art
/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile
/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame
/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are
/// measured by their symbols' art in `symbols`.
fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> {
match &b.kind {
BrushKind::Scatter(sc) => Some(sc.art.clone()),
BrushKind::Art(a) => Some(a.art.clone()),
BrushKind::Pattern(pb) => {
let mut tiles = vec![];
let mut x = 0.0;
for (i, tile_name) in TILE_NAMES.iter().enumerate() {
let Some((art, frame)) = tile(pb, i) else { continue };
let mut children = vec![];
if let Some(f) = frame {
let marker = Node::path(
NodeId(0),
vectorcraft_geom::shapes::rectangle(f),
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0),
);
children.push(Arc::new(marker));
}
children.push(Arc::new(art.clone()));
let mut g = Node::group(NodeId(0), children);
g.name = Some((*tile_name).to_string());
let Some(r) = g.geometric_bounds_with(symbols) else { continue };
// Each tile sits right of the one before it, centered on the line y = 0.
g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false);
x += r.width() + TILE_GAP;
tiles.push(Arc::new(g));
}
Some(Node::group(NodeId(0), tiles))
}
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None,
}
}
/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the
/// center of the first artboard) in the layer new art goes into, and selected, as one undo step.
/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]).
pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "brush.placeArt";
let name = name_param(p, C)?.to_string();
let d = &s.doc()?.doc;
let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO);
let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?);
let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
let symbols = d.symbol_boxes();
let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?;
if let Some(r) = art.geometric_bounds_with(&symbols) {
art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false);
}
let parent = s.doc()?.target_parent()?;
let id = s.edit("Place Brush Art", |d, sel| {
let art = d.reid(&art);
let id = art.id;
d.insert(parent, usize::MAX, art)?;
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect();
+1 -1
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket",
[],
None,
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
has_doc,
lp_fill
),
+56 -1
View File
@@ -272,6 +272,35 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
let values = input
.as_array()
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
let points: Vec<_> = values
.iter()
.map(|point| {
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
let point = Point::new(x, y);
if !finite(point) {
return Err(bad(C, "points must be finite canvas points"));
}
Ok(point)
})
.collect::<Result<_>>()?;
if points.first() != Some(&start) {
return Err(bad(C, "path chunks must share their boundary point"));
}
Ok(points)
};
let points = p.get("points");
let continuation = match p.get("continuation") {
None => &[][..],
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
Some(_) => return Err(bad(C, "continuation requires points")),
};
crate::cmd::paint::check_keep_model(p, C)?;
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = id_param(p, "group");
@@ -302,7 +331,33 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(|n| b::visible_face_at(n, pt))
.map(|f| f.id)
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone());
let mut targets = std::collections::BTreeSet::from([fid]);
if let Some(points) = points {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
// between pointer events is filled. Reversing matches visible_face_at's front first.
let faces: Vec<_> = b::faces(n).into_iter().rev().filter(|f| f.visible).collect();
let mut face_ids = vec![];
let mut regions = vec![];
for f in faces {
if let Some(path) = f.path_data()
&& let Some(bounds) = path.bounds()
{
face_ids.push(f.id);
regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds));
}
}
let map = b::BuilderMap { regions, ..Default::default() };
let mut last = pt;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?;
s.remember_paint(&paint);
+17 -4
View File
@@ -1,7 +1,7 @@
//! Document Info panel data, its categories and the text report (Document Info › Save…, File →
//! Package), and Object → Make Pixel Perfect.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
@@ -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, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), 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), 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, 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}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; 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)}",
"{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, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), 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), 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, 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}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; 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",
has_doc,
info
),
@@ -358,6 +358,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let mut fonts = BTreeSet::new();
let mut images: BTreeMap<String, Value> = BTreeMap::new();
let mut image_rows: Vec<ImageRow> = vec![];
// Whether the request being served may read each linked file (a relative path read from the
// document's folder), checked once per file.
let mut readable: HashMap<String, bool> = HashMap::new();
let link_doc = super::links::LinkBase::of(st).doc;
let mut may_read = |stored: &str| {
*readable.entry(stored.to_string()).or_insert_with(|| {
let resolved = super::fileio::document_path(stored, link_doc).ok();
crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok()
})
};
let mut patterns = BTreeSet::new();
let mut symbols = BTreeSet::new();
let mut spot = BTreeSet::new();
@@ -411,12 +421,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
Some("textObjects")
}
NodeKind::Image(im) => {
// A linked file outside a confined request's read roots: `link` is null, and the row
// names the file alone.
let link = im.link.as_ref().map(|l| (l, may_read(&l.path)));
images.insert(
im.key.clone(),
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }),
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
);
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone())));
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
Some("images")
}
NodeKind::SymbolInstance { symbol, .. } => {
+27 -7
View File
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Refresh Deferred Effects",
["Effect"],
None,
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
"{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
has_deferred,
refresh_deferred
),
@@ -150,16 +150,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) ->
None => rest.push(object),
}
}
if rest.is_empty() {
for (id, n) in definition_objects(d, &rest) {
out.entry(id).or_insert((n, false));
}
out
}
/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its
/// symbols, patterns and brushes, and opacity masks (in that art or in the layers).
fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> {
let mut out = std::collections::HashMap::new();
if ids.is_empty() {
return out;
}
let ids: std::collections::HashSet<u64> = ids.iter().copied().collect();
let brushes = vectorcraft_brush::library(d);
let symbols = d.symbols.iter().map(|s| &*s.art);
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
let layers = d.layers.iter().map(|a| &**a);
let mut look = |n: &Node| {
if rest.contains(&n.id.0) {
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
if ids.contains(&n.id.0) {
out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone()));
}
};
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
@@ -231,10 +242,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
let ids = super::named_ids(p)?;
let objects = prune(&doc, &fx);
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
return Err(EngineError::NoNode(*id));
// An object of the art drawn outside the layers is valid whether or not it has a stage.
let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect();
let found = definition_objects(&doc, &elsewhere);
if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) {
return Err(EngineError::NoNode(NodeId(*id)));
}
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
// Only the objects with a stage have anything to refresh.
let ids: Option<Vec<u64>> = ids.map(|ids| {
let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect();
ids.sort_unstable();
ids.dedup();
ids
});
let counts = fx.refresh(ids.as_deref(), |targets| {
let mut renderer = vectorcraft_render::Renderer::new();
let mut whole = Vec::new();
+6 -4
View File
@@ -90,9 +90,9 @@ pub use pdfimport::{LoadOptions, page_document};
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
templates_folder,
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, leave_out_unreadable_save_paths,
reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates,
template_filters, templates_dialog_folder, templates_folder,
};
pub(crate) use screens::{
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
@@ -124,7 +124,9 @@ pub(crate) use access::list_dir;
pub use access::write_file_with;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::{Placed, copy_new, file_metadata};
pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file};
pub(crate) use access::{
absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file,
};
#[cfg(all(test, windows))]
pub(crate) use access::{document_path_on, document_path_with};
#[cfg(test)]
+23
View File
@@ -42,6 +42,29 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
(out, seen)
}
/// May a reply to the request being served name `path`, a file or folder the client did not give?
/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]).
pub(crate) fn shown(path: &str) -> bool {
crate::file_access::check_read(path).is_ok()
}
/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name,
/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such
/// as `..` or a folder ending in a separator).
pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> {
shown_link(path, None)
}
/// A link's `stored` path as a reply to the request being served names it: whole when the file it
/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it.
pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> {
if shown(resolved.unwrap_or(stored)) {
return std::borrow::Cow::Borrowed(stored);
}
let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default();
std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name })
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
+4 -4
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
has_doc,
screens::export_for_screens
),
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Presets",
[],
None,
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones; any name works as document.exportForScreens' exportPreset",
"{} → {presets: [{name, builtIn, settings}]} the built-in batch export presets (Logo Package, Print-Ready PDF), then the saved ones (a folder outside the automation read roots is left out of settings); any name works as document.exportForScreens' exportPreset",
always,
screens::presets_list
),
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Export Presets",
[],
None,
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
"{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON; a folder outside the automation read roots is left out); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}",
always,
screens::presets_export
),
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens Settings",
[],
None,
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them)",
"{} → {settings}: the document.exportForScreens params the document last exported with ({} when never; saved with the document, the dialog reopens on them; a folder outside the automation read roots is left out)",
has_doc,
screens::export_settings
),
+18 -2
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export DXF",
[],
None,
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
has_doc,
export_dxf
)]
@@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "dxfPreset",
ty: "string",
default: "\"custom\"",
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it",
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it",
},
FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" },
FormatOption {
@@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
default: "\"png\"",
description: "png or jpeg: the files placed images are written to, next to the drawing",
},
FormatOption {
name: "includeImages",
ty: "boolean",
default: "true",
description: "placed images are written, linked to their files; false leaves them and their files out",
},
FormatOption {
name: "includeHatches",
ty: "boolean",
default: "true",
description: "filled areas get a solid hatch after their outlines; false writes the outlines alone",
},
FormatOption {
name: "preserve",
ty: "string",
@@ -133,6 +145,8 @@ struct Params {
scale_lineweights: Option<bool>,
colors: Option<Value>,
raster_format: Option<String>,
include_images: Option<bool>,
include_hatches: Option<bool>,
preserve: Option<String>,
alter_paths: Option<bool>,
outline_text: Option<bool>,
@@ -176,6 +190,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
include_images: q.include_images.unwrap_or(d.include_images),
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
outline_text: q.outline_text.unwrap_or(d.outline_text),
+32 -20
View File
@@ -48,7 +48,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "useArtboards",
ty: "boolean",
default: "null",
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (none when no art shows); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named",
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (when no art shows, Export writes none and Save writes it on the first artboard); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named (Save: the first artboard when no art shows)",
},
FormatOption { name: "level", ty: "integer", default: "3", description: "PostScript language level, 2 or 3" },
FormatOption {
@@ -203,10 +203,15 @@ fn expanded(cmd: &str, p: &Value, saved: &[super::super::FlattenerPreset]) -> Re
}
}
/// One file to write: its artboard, region and origin.
type Page = (Option<usize>, Rect, Point);
/// The files to write: `(artboard, region, origin)` each — every chosen artboard with its corner
/// as the origin, or the visible art's bounds with the first artboard's corner. With two or more
/// chosen artboards, a central file of the visible art comes first (none when no art shows).
fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Point)>> {
/// `saving`: Save always writes the file it names, so with no visible art that file's region is
/// the first artboard, and the second value is true.
fn pages(doc: &Document, set: &Settings, saving: bool) -> Result<(Vec<Page>, bool)> {
let n = doc.artboards.len();
let named = set.boards.resolve(n).map_err(|e| bad(C, e))?;
let boards = match (set.use_artboards, named) {
@@ -217,17 +222,25 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi
};
let corner = |r: Rect| Point::new(r.x0, r.y1);
let art = |art: Rect| (None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect)));
// The visible art's bounds; for Save with no visible art, the first artboard (true).
let visible = || match vectorcraft_render::encode::art_bounds(doc) {
Some(bounds) => Some((bounds, false)),
None if saving => doc.artboards.first().map(|a| (a.rect, true)),
None => None,
};
match boards {
Some(boards) => {
let central = (boards.len() > 1).then(|| vectorcraft_render::encode::art_bounds(doc).map(art)).flatten();
let central = (boards.len() > 1).then(visible).flatten();
let each = boards
.into_iter()
.map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))));
central.map(Ok).into_iter().chain(each).collect()
let pages = central.map(|(bounds, _)| Ok(art(bounds))).into_iter().chain(each).collect::<Result<_>>()?;
Ok((pages, central.is_some_and(|(_, blank)| blank)))
}
None => {
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
Ok(vec![art(bounds)])
let missing = if saving { "the document has no artboard" } else { "nothing to export: the document has no visible art" };
let (bounds, blank) = visible().ok_or_else(|| bad(C, missing))?;
Ok((vec![art(bounds)], blank))
}
}
}
@@ -293,16 +306,17 @@ pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> {
encode_document(doc, p, false)
}
/// Save keeps a single page's original frame and all native editing data, unlike Export's
/// optional art-bound crop or separate file per artboard. Existing EPS loss warnings still apply.
/// Save writes the pages Export does (the visible art's bounds, or with Use Artboards the chosen
/// artboards), with a smaller preview. A single file, the one the document becomes, carries all
/// the native editing data; with no visible art its page is the first artboard.
pub(super) fn encode_save(doc: &Document, p: &Value) -> Result<Encoded> {
encode_document(doc, p, true)
}
fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
let set = parse(p)?;
if saving && (set.use_artboards == Some(false) || bool_or(p, "selectedOnly", false)) {
return Err(bad(C, "EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS"));
if saving && bool_or(p, "selectedOnly", false) {
return Err(bad(C, "EPS Save writes all artwork: use document.export for selected-only EPS"));
}
let original = doc;
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
@@ -315,18 +329,16 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
} else {
Cow::Borrowed(original)
};
let pages = if saving {
let board = set.boards.one(doc.artboards.len()).map_err(|e| bad(C, e))?;
let rect = doc.artboards.get(board).ok_or_else(|| bad(C, "the document has no artboard"))?.rect;
vec![(Some(board), rect, Point::new(rect.x0, rect.y1))]
} else {
pages(doc, &set)?
};
let (pages, blank) = pages(doc, &set, saving)?;
if pages.is_empty() {
return Err(bad(C, "the document has no artboard"));
}
// The artboards' background colors, behind the art (the editing data keeps them as colors).
let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?;
// The file Save writes alone becomes the document's own, so it carries every artboard.
let whole = saving && pages.len() == 1;
// The artboards' background colors, behind the art (the editing data keeps them as colors);
// a page on the first artboard because no art shows has that artboard's color.
let fills = pages.iter().filter_map(|(b, ..)| *b).chain(blank.then_some(0));
let filled = super::export::with_artboard_fills(doc, p, fills).map_err(|e| bad(C, e))?;
let doc = &*filled;
let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect();
let expanded = expand_transparent_tile_images(doc, &set.flatten)?;
@@ -360,7 +372,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
origin,
title: doc.title.clone(),
created,
native: Some(native(&editing, if saving { None } else { board }, set.include_linked)),
native: Some(native(&editing, if whole { None } else { board }, set.include_linked)),
..set.eps.clone()
};
let out = vectorcraft_eps::export(drawn, &o, preview.as_ref(), thumbnail.as_ref()).map_err(|e| bad(C, e))?;
+62 -5
View File
@@ -870,8 +870,10 @@ impl SaveJob {
_ => encode_all(doc, f.id, &self.params),
}
.map_err(|e| named_for_save(cmd, e))?;
// A legacy .ai file per artboard.
let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?;
// A legacy .ai file per artboard, or the files the EPS encoder writes: one, or with Use
// Artboards and two or more artboards the central file at the path and a file per
// artboard beside it.
let per_artboard = f.id == "eps" || (f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?);
if enc.files.len() != 1 && !per_artboard {
return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export"));
}
@@ -1032,11 +1034,47 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value>
let plan = save_plan(s, mode, p)?;
let job = save_job(s, plan)?;
let uid = s.doc()?.uid;
let out = job.write_streamed(&mut super::write_file_with)?;
let mut out = job.write_streamed(&mut super::write_file_with)?;
job.complete(s, uid);
leave_out_unreadable_save_paths(&mut out, str_param(p, "path"));
Ok(out)
}
/// The reply `out` of a save with the `path` param `given`, as the request being served may see it
/// ([`super::access::shown`]). A save without a path writes the document's own file: its `path` is
/// left out, and the `files` and `linked` written beside it are named by their file names, when they
/// are outside the read roots. The suggested `folder` of a reply without a path is left out when it
/// is outside them. Without roots in force `out` is unchanged.
pub fn leave_out_unreadable_save_paths(out: &mut Value, given: Option<&str>) {
use super::access::{shown, shown_path};
if crate::file_access::current().is_none() {
return;
}
let Some(o) = out.as_object_mut() else { return };
if o.get("folder").and_then(Value::as_str).is_some_and(|f| !shown(f)) {
o.remove("folder");
}
// Every path the reply names then is the one the client gave, or beside it.
if given.is_some_and(|g| !g.is_empty()) {
return;
}
if o.get("path").and_then(Value::as_str).is_some_and(|p| !shown(p)) {
o.remove("path");
}
for key in ["files", "linked"] {
if let Some(Value::Array(rows)) = o.get_mut(key) {
for row in rows {
if let Value::String(p) = row
&& !shown(p)
{
*row = json!(shown_path(p));
}
}
}
}
}
fn can_revert(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
match (&st.path, st.is_dirty()) {
@@ -1092,6 +1130,25 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// An EPS save that named artboards without Use Artboards, or with it on, had it on (the
// encoder reads them so): it shows on, with those artboards as the range.
if f.id == "eps"
&& let Some(m) = &saved
&& m.get("useArtboards").and_then(Value::as_bool) != Some(false)
{
let range = m.get("range").and_then(Value::as_str).filter(|r| !r.trim().is_empty());
let boards = m
.get("artboards")
.and_then(|a| serde_json::from_value::<Vec<usize>>(a.clone()).ok())
.or_else(|| m.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).map(|i| vec![i]))
.filter(|b| !b.is_empty());
if range.is_some() || boards.is_some() {
v["options"]["useArtboards"]["value"] = json!(true);
if let (None, Some(boards)) = (range, boards) {
v["options"]["range"]["value"] = json!(range_text(&boards));
}
}
}
v["saveFormats"] =
SAVE_FORMATS.iter().filter_map(|id| format(id)).map(|f| json!({"id": f.id, "label": f.label, "extensions": f.extensions})).collect();
Ok(v)
@@ -1104,7 +1161,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
@@ -1158,7 +1215,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Format Options",
[],
None,
"{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default",
"{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default (EPS: useArtboards is true when the last save named artboards without it, and range then names them)",
always,
format_options
),
+105 -4
View File
@@ -644,12 +644,86 @@ impl Output {
/// File → Export for Screens: [`export`] (over the settings of `exportPreset`, when given), with
/// the params remembered in the document (`document.exportSettings`).
pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
// A folder the client gave, as against the one its `exportPreset` keeps.
let given = p.get("folder").is_some();
let p = with_preset(s, p)?;
let r = export(s, &p)?;
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
let mut r = export(s, &p).map_err(|e| match hidden {
Some(folder) => leave_out_folder_from_error(e, folder),
None => e,
})?;
remember(s, &p);
if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) {
leave_out_unreadable_folder(&mut r, folder);
}
Ok(r)
}
/// An error of an export into `folder`, a folder outside the read roots that the client did not
/// give: `folder` as the path the error is about names it by its own name
/// ([`super::access::shown_path`]), and the rest of the message stays.
fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError {
let name = super::access::shown_path(folder);
match e {
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)),
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) },
e => e,
}
}
/// `msg` with `folder` given as `name` where it begins a path the message is about: at the start
/// of `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or
/// after `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message
/// names stays whole, even one inside `folder`.
fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String {
const BEFORE: [&str; 2] = [": ", "cannot resolve "];
let mut out = String::with_capacity(msg.len());
let mut rest = msg;
loop {
if let Some(after) = rest.strip_prefix(folder)
&& after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' '))
{
out.push_str(name);
rest = after;
}
let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break };
out.push_str(&rest[..i + len]);
rest = &rest[i + len..];
}
out.push_str(rest);
out
}
/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being
/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's
/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`),
/// as the reply of an export to a ZIP names them.
fn leave_out_unreadable_folder(r: &mut Value, folder: &str) {
if super::access::shown(folder) {
return;
}
let Some(o) = r.as_object_mut() else { return };
o.remove("path");
let inside = format!("{folder}/");
if let Some(Value::Array(files)) = o.get_mut("files") {
for file in files {
// A ZIP's files are named relative to it already.
if let Some(name) = file.as_str().and_then(|path| path.strip_prefix(&inside)) {
*file = json!(name);
}
}
}
}
/// Export settings kept in the document or a preset, as the request being served may see them: a
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
settings.remove("folder");
}
settings
}
// ---------- export presets ----------
/// A saved batch export: what to write and how to name and sort it, to use again
@@ -727,7 +801,13 @@ pub fn preset_list(saved: &[ScreenExportPreset]) -> Value {
}
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) }))
let saved: Vec<ScreenExportPreset> = s
.prefs
.screen_export_presets
.iter()
.map(|p| ScreenExportPreset { name: p.name.clone(), settings: leave_out_unreadable_settings_folder(p.settings.clone()) })
.collect();
Ok(json!({ "presets": preset_list(&saved) }))
}
/// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would
@@ -831,6 +911,8 @@ pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(too_many());
}
let count = presets.len();
let presets: Vec<ScreenExportPreset> =
presets.into_iter().map(|p| ScreenExportPreset { settings: leave_out_unreadable_settings_folder(p.settings), ..p }).collect();
let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?;
if text.len() > MAX_PRESET_FILE_BYTES {
return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
@@ -1388,12 +1470,31 @@ pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>)
/// `document.exportSettings`: the Export for Screens settings the document last exported with.
pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "settings": s.doc()?.doc.export_settings }))
Ok(json!({ "settings": leave_out_unreadable_settings_folder(s.doc()?.doc.export_settings.clone()) }))
}
#[cfg(test)]
mod tests {
use super::{Output, ScreenSize, safe_file_name};
use super::{Output, ScreenSize, leave_out_folder_from_message, safe_file_name};
/// A hidden export folder is named by its name where a message is about it, and a root that
/// starts with the same text, or a longer path, stays whole.
#[test]
fn a_hidden_folder_is_named_by_its_name_in_a_message() {
let f = "/work/out";
let cases = [
(
"automation path rejected: outside the write root /work/out/in: /work/out",
"automation path rejected: outside the write root /work/out/in: out",
),
("automation path rejected: cannot resolve /work/out: denied", "automation path rejected: cannot resolve out: denied"),
("/work/out/2x/a.png: disk full", "out/2x/a.png: disk full"),
("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"),
];
for (msg, want) in cases {
assert_eq!(leave_out_folder_from_message(msg, f, "out"), want, "{msg}");
}
}
/// Files given one name are numbered in turn, each numbering going on from the last one (so
/// thousands of them don't each try every number used before), and a file asking again for
+13
View File
@@ -48,6 +48,19 @@ fn image_of(s: &Session) -> vectorcraft_doc::ImageObject {
}
}
/// A path outside a confined request's read roots shows as its file name, after the last `/` or `\`
/// on every platform; one that ends in no name shows as nothing. Without roots it shows whole.
#[test]
fn a_hidden_path_shows_as_its_file_name_on_every_platform() {
let windows = "C:\\Users\\someone\\art\\red.png";
crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || {
for (path, name) in [("/home/someone/art/red.png", "red.png"), (windows, "red.png"), ("/home/someone/..", ""), ("C:\\Users\\someone\\", "")] {
assert_eq!(shown_path(path), name, "{path}");
}
});
assert_eq!(shown_path(windows), windows);
}
#[test]
fn opens_every_readable_format() {
let mut s = session(200.0, 100.0, 1);
@@ -109,23 +109,25 @@ fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() {
}
}
/// Does PostScript `t` paint the only red the document has, the first artboard's color? RGB, or
/// CMYK PostScript's (its values depend on the color conversion the platform offers, so only its
/// hue is checked).
fn red(t: &str) -> bool {
t.lines().any(|l| {
let mut w: Vec<&str> = l.split_whitespace().collect();
let Some(op) = w.pop() else { return false };
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
match (op, v.as_slice()) {
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
_ => false,
}
})
}
#[test]
fn eps_and_postscript_print_draw_the_color() {
let mut s = session();
// The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its
// values depend on the color conversion the platform offers, so only its hue is checked).
let red = |t: &str| {
t.lines().any(|l| {
let mut w: Vec<&str> = l.split_whitespace().collect();
let Some(op) = w.pop() else { return false };
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
match (op, v.as_slice()) {
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
_ => false,
}
})
};
let eps = |s: &mut Session, more: Value| {
String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned()
};
@@ -138,6 +140,22 @@ fn eps_and_postscript_print_draw_the_color() {
assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it");
}
/// EPS Save draws the color on an artboard's page: with Use Artboards, or on the first artboard
/// when no art shows. The box of the visible art, as Export's, has none.
#[test]
fn eps_save_draws_the_color_on_an_artboard_page() {
let mut s = session();
let save = |s: &mut Session, more: Value| {
let options = with(json!({"previewFormat": "none", "thumbnails": false}), &more);
String::from_utf8_lossy(&b64(&s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap())).into_owned()
};
assert!(!red(&save(&mut s, json!({}))), "the art's box");
assert!(red(&save(&mut s, json!({"useArtboards": true, "range": "1"}))), "the artboard's page");
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
assert!(red(&save(&mut s, json!({}))), "the first artboard when no art shows");
}
#[test]
fn export_for_screens_includes_the_fill_unless_unchecked() {
let mut s = session();
+47
View File
@@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() {
true
)
);
assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches");
let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap();
assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it");
let custom = dxf::options(&json!({})).unwrap();
assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both");
assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default");
let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string();
assert!(e.contains("custom or cnc"), "{e}");
@@ -151,6 +156,44 @@ fn placed_images_come_back_as_linked_files() {
let _ = std::fs::remove_dir_all(dir);
}
/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill
/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves
/// out both, and the options given override it.
#[test]
fn placed_images_and_fill_hatches_can_be_left_out() {
let mut s = super::tests_svg::image_session();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
let counts = |r: &Value| {
let e = entities(&text(r));
let n = |k: &str| e.iter().filter(|x| *x == k).count();
(n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len))
};
let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w)));
let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap();
assert_eq!(counts(&all), (1, 1, 1, 1));
let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap();
assert_eq!(counts(&r), (1, 1, 0, 0));
assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}");
let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap();
assert_eq!(counts(&r), (1, 0, 1, 1));
assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}");
let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0, 0));
let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap();
assert_eq!(counts(&r), (1, 0, 1, 1));
// With a path, no image file is written next to the drawing.
let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("cut.dxf").to_string_lossy().to_string();
let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap();
assert!(r.get("linked").is_none(), "{r}");
let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect();
assert_eq!(files, ["cut.dxf"]);
let _ = std::fs::remove_dir_all(dir);
}
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
/// image's key.
@@ -181,6 +224,8 @@ fn bad_dxf_options_are_refused() {
json!({"rasterFormat": "gif"}),
json!({"preserve": "both"}),
json!({"alterPaths": "yes"}),
json!({"includeImages": "no"}),
json!({"includeHatches": 0}),
] {
let e = s.execute("document.exportDxf", &p).unwrap_err().to_string();
assert!(e.contains("DXF"), "{p}: {e}");
@@ -203,6 +248,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
"scaleLineweights",
"colors",
"rasterFormat",
"includeImages",
"includeHatches",
"preserve",
"alterPaths",
"outlineText",
@@ -667,6 +667,118 @@ fn a_numbered_file_is_written_into_the_first_rows_folder() {
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder");
}
/// An export into the folder an export preset keeps, for a client whose read roots don't hold that
/// folder: the reply leaves out the ZIP's path and names the files relative to the folder. A folder
/// inside the read roots, and one the client gives, stay whole.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_presets_folder_outside_the_read_root_is_left_out_of_the_reply() {
use crate::file_access::{AutomationRoots, confine};
let mut s = session(1);
let tmp = Folder::new("preset-roots");
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
for f in [&inside, &out] {
std::fs::create_dir_all(f).unwrap();
}
let folder = out.to_string_lossy().replace('\\', "/");
let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder});
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap();
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap();
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| confine(roots.as_ref(), || export(s, p));
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept"}));
assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}");
assert!(out.join("1x/Artboard-1.png").is_file());
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true}));
assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}");
assert!(!r.to_string().contains(&folder), "{r}");
// Inside the read roots, or given by the client: whole.
assert_eq!(run(&mut s, &both, json!({"exportPreset": "Kept"}))["files"], json!([format!("{folder}/1x/Artboard-1.png")]));
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true}));
assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}");
}
/// An export into the folder an export preset keeps, refused because that folder is outside the
/// client's read and write roots: the error names the folder by its name only. A folder the client
/// gives stays whole in the error.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_name() {
use crate::file_access::{AutomationRoots, confine};
let mut s = session(1);
let tmp = Folder::new("preset-refused");
let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out"));
for f in [&inside, &out] {
std::fs::create_dir_all(f).unwrap();
}
let folder = out.to_string_lossy().replace('\\', "/");
let settings = json!({"formats": [{"format": "png"}], "folder": folder});
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
let mut run = |p: Value| confine(confined.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap_err().to_string();
let e = run(json!({"exportPreset": "Kept"}));
assert!(e.contains("outside the write root") && e.contains("kept-out") && !e.contains(&folder), "{e}");
let e = run(json!({"exportPreset": "Kept", "folder": folder}));
assert!(e.contains(&folder), "{e}");
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written");
// A preset folder that holds the write root: the root stays whole in the error.
let parent = tmp.0.to_string_lossy().replace('\\', "/");
let settings = json!({"formats": [{"format": "png"}], "folder": parent});
s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap();
let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string();
let root = inside.display().to_string();
let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned();
assert!(e.contains(&format!("root {root}: {name}")), "{e}");
}
/// The export settings the document keeps and the saved presets, read by a client whose read roots
/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and
/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest.
/// Inside the read roots the folder stays.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn kept_settings_leave_out_a_folder_outside_the_read_root() {
use crate::file_access::{AutomationRoots, confine};
let mut s = session(1);
let tmp = Folder::new("settings-roots");
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
for f in [&inside, &out] {
std::fs::create_dir_all(f).unwrap();
}
let folder = out.to_string_lossy().replace('\\', "/");
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
export(&mut s, json!({"exportPreset": "Kept"}));
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[inside.as_path()]).unwrap();
let ask = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, cmd: &str, p: Value| {
confine(roots.as_ref(), || s.execute(cmd, &p).unwrap())
};
let saved = |list: &Value| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Kept").unwrap()["settings"].clone();
let r = ask(&mut s, &confined, "document.exportSettings", json!({}));
assert_eq!((r["settings"].get("folder"), &r["settings"]["formats"]), (None, &json!([{"format": "svg"}])), "{r}");
let r = ask(&mut s, &confined, "document.exportPresets.list", json!({}));
assert_eq!(saved(&r), json!({"formats": [{"format": "svg"}]}), "{r}");
let r = ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"]}));
let data = r["data"].as_str().unwrap();
assert!(!data.contains(&folder) && data.contains("svg"), "{data}");
let file = inside.join("kept.vcexportpresets");
let path = file.to_string_lossy().replace('\\', "/");
ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"], "path": path}));
assert!(!std::fs::read_to_string(&file).unwrap().contains(&folder));
// Inside the read roots: whole.
assert_eq!(ask(&mut s, &both, "document.exportSettings", json!({}))["settings"]["folder"], json!(folder));
assert_eq!(saved(&ask(&mut s, &both, "document.exportPresets.list", json!({})))["folder"], json!(folder));
assert!(ask(&mut s, &both, "document.exportPresets.export", json!({"names": ["Kept"]}))["data"].as_str().unwrap().contains(&folder));
}
#[test]
fn format_settings_apply_to_their_rows_and_rows_win() {
let mut s = session(1);
+34
View File
@@ -109,6 +109,40 @@ fn unlinked(g: &Gradient) -> Gradient {
g
}
/// Give each saved preset in `saved` a name no built-in preset or earlier saved one has (any case):
/// a clash becomes the first free "<name> N", N from 2. Returns the renames as (old, new).
pub(crate) fn rename_clashing_presets(saved: &mut [GradientPreset]) -> Vec<(String, String)> {
if saved.is_empty() {
return vec![];
}
let builtin: std::collections::HashSet<String> = builtin_presets().map(|e| e.name.to_ascii_lowercase()).collect();
let mut taken: std::collections::HashSet<String> =
builtin.iter().cloned().chain(saved.iter().map(|p| p.name.trim().to_ascii_lowercase())).collect();
let mut kept = std::collections::HashSet::new();
// The next suffix to try for each name, so many presets with one name take linear time.
let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
let mut renamed = vec![];
for p in saved {
let key = p.name.trim().to_ascii_lowercase();
if !builtin.contains(&key) && kept.insert(key.clone()) {
continue;
}
let base = p.name.trim();
let n = next.entry(key).or_insert(2);
let name = loop {
let candidate = format!("{base} {n}");
*n += 1;
if !taken.contains(&candidate.to_ascii_lowercase()) {
break candidate;
}
};
taken.insert(name.to_ascii_lowercase());
kept.insert(name.to_ascii_lowercase());
renamed.push((std::mem::replace(&mut p.name, name.clone()), name));
}
renamed
}
impl Session {
/// The Gradient panel's presets: the built-in ones by library, then the saved ones.
pub fn gradient_presets(&self) -> Vec<GradientPresetEntry> {
+56 -7
View File
@@ -1,5 +1,7 @@
use std::collections::BTreeSet;
use vectorcraft_doc::live::BlendSpineMode;
use super::common::{
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
spacing_param, starts_param, wrap,
@@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k
spec.spine = Some(path);
}
/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine.
fn gives_easing(p: &Value) -> bool {
["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null()))
}
/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null.
fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> {
match p.get(key).filter(|v| !v.is_null()) {
None => Ok(current),
Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))),
}
}
pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.make";
let roots = roots_param(s, p)?;
@@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
}
let starts = starts_param(p, &roots)?;
let base = first_blend(&s.doc()?.doc, &roots);
let defaults = s.prefs.blend_options.unwrap_or_default();
// Create Spine applies to a new blend; one taking more keys keeps whether it has a spine.
let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?;
let cur = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation },
_ => s.prefs.blend_options.unwrap_or_default(),
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults },
_ => defaults,
};
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let (ease0, color0) = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift),
_ => Default::default(),
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
};
if no_spine && gives_easing(p) {
return Err(bad(C, "the blend has no spine"));
}
let ease = ease_param(p, C, ease0)?;
let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?;
let id = s.edit("Make Blend", |d, sel| {
@@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
n.knockout = vectorcraft_doc::Knockout::On;
n
});
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() };
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() };
if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind {
extend_spine(&mut spec, old, old_spec, &children);
}
@@ -346,9 +367,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
// Nothing to set them on: the options new blends start with (easing is per blend).
let d = s.prefs.blend_options.unwrap_or_default();
let spacing = spacing_param(p, C, d.spacing)?;
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) });
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
return Ok(json!({ "defaults": true }));
};
if gives_easing(p) && any_without_spine(s) {
return Err(bad(C, "the blend has no spine"));
}
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let ease = ease_param(p, C, cur.ease)?;
@@ -384,6 +408,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
v["colorShift"] = json!(spec.color_shift);
v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>());
v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>());
v["hasSpine"] = json!(!spec.no_spine);
if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind)
&& let Some((path, anchors)) = live::blend_spine(children, &spec)
&& let Some(sp) = path.subpaths.first()
@@ -403,6 +428,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
})
}
/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads
/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs.
pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.createSpine";
let mut d = s.prefs.blend_options.unwrap_or_default();
let mode = spine_mode_param(p, C, "mode", d.create_spine)?;
if mode != d.create_spine {
d.create_spine = mode;
s.prefs.blend_options = Some(d);
}
Ok(json!({ "mode": mode.id() }))
}
pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> {
let blends = selected_of(s, is_blend);
let ids = s.edit("Expand Blend", |d, sel| {
@@ -507,6 +545,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?;
d.remove(path)?;
if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) {
// A blend made without a spine gets this one.
spec.no_spine = false;
spec.spine = Some(spine);
spec.key_anchors.clear();
keys_to_spine(children, spec);
@@ -517,7 +557,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// Is any selected blend one made without a spine?
fn any_without_spine(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
}
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
if any_without_spine(s) {
return Err(bad("object.blend.reverseSpine", "the blend has no spine"));
}
edit_blends(s, "Reverse Spine", |children, spec| {
if spec.spine.is_some() && pin(children, spec) {
// The keys keep their anchors, which now count from the other end.
+16 -7
View File
@@ -1,6 +1,6 @@
use super::blend::{
blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack,
spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine,
blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
};
use super::common::{has_blend, has_envelope, has_mesh};
use super::envelope::{
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Blend"],
Some("Cmd+Alt+B"),
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}",
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
has_doc,
blend_make
),
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Release",
["Object", "Blend"],
Some("Cmd+Alt+Shift+B"),
"{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
"{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
has_blend,
blend_release
),
@@ -40,6 +40,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
blend_options
),
cmd!(
"object.blend.createSpine",
"Create Spine",
[],
None,
"{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}",
always,
blend_create_spine
),
cmd!(
"object.blend.expand",
"Expand",
@@ -54,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Spine",
["Object", "Blend"],
None,
"{} use the selected path as the spine of the selected blend (the path is consumed)",
"{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one",
has_blend,
blend_replace_spine
),
@@ -63,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reverse Spine",
["Object", "Blend"],
None,
"{} reverse the order of the key objects along the spine",
"{} reverse the order of the key objects along the spine; an error when a selected blend has no spine",
has_blend,
blend_reverse_spine
),
@@ -72,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Info",
[],
None,
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
always,
blend_info
),
+5 -2
View File
@@ -1306,13 +1306,16 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
let symbols = d.symbol_boxes();
let boxes: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, d.node(*id)?.geometric_bounds_with(&symbols)?))).collect();
let mut converted = vec![];
// The highest artboard id the document has, kept up to date as artboards are added.
let mut top = d.artboards.iter().map(|a| a.id).max();
for (id, b) in boxes {
if b.width() <= 0.0 || b.height() <= 0.0 {
continue;
}
// Named one past the highest artboard id the document has, whatever id it is given.
let number = d.artboards.iter().map(|a| a.id).max().map_or(1, |m| m.saturating_add(1));
let aid = d.next_artboard_id();
let number = top.map_or(1, |m| m.saturating_add(1));
let aid = d.next_artboard_id_above(top);
top = top.max(Some(aid));
d.artboards.push(vectorcraft_doc::Artboard {
id: aid,
name: format!("Artboard {number}"),
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reflect…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection,
reflect
),
+23 -16
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::{Document, LinkInfo};
use serde_json::{Value, json};
use super::fileio::{create_dir, write_file};
use super::fileio::{create_dir, document_path, shown_link, shown_path, write_file};
use super::links::LinkBase;
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name};
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
has_doc,
package
)]
@@ -178,8 +178,10 @@ impl<'a> Collector<'a> {
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
/// copy of `source` finds it only by its name, beside it.
/// `path` is the link's path as the warning names it.
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
if Path::new(copy).file_name().and_then(std::ffi::OsStr::to_str) != Some(name) {
let source = shown_path(source);
let message = format!(
"{path}: copied as {copy}; the copy of {source} looks for it as {name} and shows the file of that name, if any, else its preview"
);
@@ -207,11 +209,13 @@ impl<'a> Collector<'a> {
let section = self.sections.len();
self.sections.push(vec![]);
let mut lines = vec![];
// The packaged document's sections read as before; a placed document's name its file.
// The packaged document's sections read as before; a placed document's name its file. The
// report and the warnings name a file outside a confined request's read roots by its name.
let shown_source = shown_path(source);
let heading = |lines: &mut Vec<String>, title: &str| {
lines.push(title.into());
if depth > 0 {
lines.push(format!("Document: {source}"));
lines.push(format!("Document: {shown_source}"));
}
};
// A file's saved path is only meaningful inside its own document.
@@ -243,17 +247,21 @@ impl<'a> Collector<'a> {
heading(&mut lines, "LINKED FILES");
for file in linked_files(doc) {
let found_path = file.found_path.as_deref().unwrap_or(&file.path);
// The stored path, whole when the place it names (read from this document's folder) is
// inside the read roots. A file found elsewhere does not show a stored path outside them.
let resolved = document_path(&file.path, Some(source)).ok();
let shown = shown_link(&file.path, resolved.as_deref()).into_owned();
if let Some(ancestor) = self.visiting.get(found_path).cloned() {
// The ancestor is already included (possibly the root document). A
// cyclic reference cannot have a final content hash until both files
// have been written, so leave its size/hash unspecified, not stale.
self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path));
self.warn(&mut lines, format!("{shown}: circular placed-document link to {ancestor}; stopped following the cycle"));
local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None });
continue;
}
if let Some(existing) = self.copies.get(found_path).cloned() {
if by_name {
self.renamed(&mut lines, source, &file.path, &file.name, &existing.name);
self.renamed(&mut lines, source, &shown, &file.name, &existing.name);
}
// Another document may place other pages of a PDF copied already.
if self.opts.copy_fonts
@@ -265,8 +273,8 @@ impl<'a> Collector<'a> {
continue;
}
let Some(mut bytes) = file.bytes else {
lines.push(format!("{}: not found ({}), not copied", file.name, file.path));
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) });
lines.push(format!("{}: not found ({shown}), not copied", file.name));
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({shown_source})", file.name) });
continue;
};
if self.copies.len() >= 10_000 {
@@ -277,7 +285,7 @@ impl<'a> Collector<'a> {
let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken });
let destination_file = format!("{dir}{unique}");
if by_name {
self.renamed(&mut lines, source, &file.path, &file.name, &destination_file);
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
}
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
// read from its editing data links are copied beside it.
@@ -285,7 +293,7 @@ impl<'a> Collector<'a> {
let placed_file = pages.is_some();
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
} else {
self.collect(&mut art, found_path, &destination_file, depth + 1, true, None)?;
}
@@ -296,7 +304,7 @@ impl<'a> Collector<'a> {
}
if placed_file && super::place::document::is_native(&file.name, &bytes) {
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
} else {
match vectorcraft_format::load_file(&bytes) {
Ok(saved) => {
@@ -320,8 +328,7 @@ impl<'a> Collector<'a> {
Err(e) => self.warn(
&mut lines,
format!(
"{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked",
file.path
"{shown}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked"
),
),
}
@@ -329,7 +336,7 @@ impl<'a> Collector<'a> {
}
Err(e) => self.warn(
&mut lines,
format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path),
format!("{shown}: unreadable linked document ({e}); copied unchanged, its own links were not collected"),
),
}
}
@@ -337,7 +344,7 @@ impl<'a> Collector<'a> {
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);
lines.push(format!("{} → {destination_file}", file.path));
lines.push(format!("{shown} → {destination_file}"));
self.entries.push((destination_file, bytes));
}
lines.push(String::new());
@@ -518,7 +525,7 @@ fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Res
// The report.
if let Some(info) = info {
let report_name = free_name(&format!("{stem} Report.txt"), &mut taken);
let mut text = format!("Package: {doc_name}\nFrom: {doc_path}\n\n");
let mut text = format!("Package: {doc_name}\nFrom: {}\n\n", shown_path(&doc_path));
lines.iter().for_each(|l| text.push_str(&format!("{l}\n")));
text.push_str(&info);
entries.push((report_name, text.into_bytes()));
+160 -2
View File
@@ -23,8 +23,10 @@ pub struct BuiltinPatternLibrary {
}
/// The built-in pattern libraries (Window → Swatch Libraries → Patterns), in menu order.
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] =
&[BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }];
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[
BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns },
BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures },
];
/// The library category of the built-in pattern libraries.
pub const CATEGORY: &str = "patterns";
@@ -154,6 +156,106 @@ fn geometric_patterns(d: &mut Document) {
add(d, "Zigzag", 10.0, 8.0, TileType::Grid, vec![polygon(&[(0.0, 5.0), (5.0, 1.0), (10.0, 5.0), (10.0, 7.0), (5.0, 3.0), (0.0, 7.0)])]);
}
/// SplitMix64, a small generator with a fixed seed per pattern, so a grit pattern draws the same
/// marks every time it is made.
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// A number from `lo` up to, but not including, `hi`.
fn range(&mut self, lo: f64, hi: f64) -> f64 {
lo + (self.next() >> 11) as f64 / (1u64 << 53) as f64 * (hi - lo)
}
}
/// A round dot of radius `r` at (`x`, `y`).
fn dot(x: f64, y: f64, r: f64) -> PathData {
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r))
}
/// An irregular fleck of four to seven corners about (`x`, `y`), at most `r` from it.
fn fleck(rng: &mut SplitMix64, x: f64, y: f64, r: f64) -> PathData {
use std::f64::consts::TAU;
let n = 4 + (rng.next() % 4) as usize;
let turn = rng.range(0.0, TAU);
let points: Vec<(f64, f64)> = (0..n)
.map(|k| {
let a = turn + TAU * (k as f64 + rng.range(-0.3, 0.3)) / n as f64;
let reach = r * rng.range(0.55, 1.0);
(x + reach * a.cos(), y + reach * a.sin())
})
.collect();
polygon(&points)
}
/// A thin straight scratch `len` long and `width` wide, centered on (`x`, `y`) at a random angle.
fn scratch(rng: &mut SplitMix64, x: f64, y: f64, len: f64, width: f64) -> PathData {
let (s, c) = rng.range(0.0, std::f64::consts::PI).sin_cos();
let (hx, hy, wx, wy) = (c * len / 2.0, s * len / 2.0, -s * width / 2.0, c * width / 2.0);
polygon(&[(x - hx - wx, y - hy - wy), (x + hx - wx, y + hy - wy), (x + hx + wx, y + hy + wy), (x - hx + wx, y - hy + wy)])
}
/// A grit pattern of `count` marks scattered over a square grid tile of side `size`, drawn from
/// `seed` (`mark` draws one at a point). A mark that reaches past an edge is kept whole: the tiling
/// draws the part outside the tile on the next tile, so the tiles join without a seam.
fn grit(d: &mut Document, name: &str, size: f64, seed: u64, count: usize, mark: impl Fn(&mut SplitMix64, f64, f64) -> PathData) {
let mut rng = SplitMix64(seed);
let marks = (0..count)
.map(|_| {
let (x, y) = (rng.range(0.0, size), rng.range(0.0, size));
mark(&mut rng, x, y)
})
.collect();
add(d, name, size, size, TileType::Grid, marks);
}
/// Grit Textures: seamless black grain, grit, sand, speckle, stipple, scratch and fleck textures on
/// a clear background, each drawn from its own fixed seed.
fn grit_textures(d: &mut Document) {
grit(d, "Fine Grain", 24.0, 1, 320, |rng, x, y| dot(x, y, rng.range(0.15, 0.35)));
grit(d, "Coarse Grit", 30.0, 2, 150, |rng, x, y| {
let r = rng.range(0.45, 1.1);
fleck(rng, x, y, r)
});
grit(d, "Sand", 24.0, 3, 280, |rng, x, y| {
let r = rng.range(0.2, 0.45);
fleck(rng, x, y, r)
});
grit(d, "Speckle", 30.0, 4, 90, |rng, x, y| dot(x, y, rng.range(0.3, 0.9)));
// Stipple: one dot in each cell of a 12 × 12 grid, moved a little off the cell's center.
let mut rng = SplitMix64(5);
let (size, cells) = (24.0, 12);
let step = size / f64::from(cells);
let dots = (0..cells)
.flat_map(|row| (0..cells).map(move |col| (col, row)))
.map(|(col, row)| {
let x = (f64::from(col) + 0.5) * step + rng.range(-0.3, 0.3) * step;
let y = (f64::from(row) + 0.5) * step + rng.range(-0.3, 0.3) * step;
dot(x, y, rng.range(0.3, 0.45))
})
.collect();
add(d, "Stipple", size, size, TileType::Grid, dots);
grit(d, "Scratches", 36.0, 6, 45, |rng, x, y| {
let (len, width) = (rng.range(2.0, 7.0), rng.range(0.15, 0.35));
scratch(rng, x, y, len, width)
});
grit(d, "Sparse Flecks", 36.0, 7, 32, |rng, x, y| {
let r = rng.range(0.35, 0.8);
fleck(rng, x, y, r)
});
grit(d, "Dense Flecks", 18.0, 8, 220, |rng, x, y| {
let r = rng.range(0.2, 0.5);
fleck(rng, x, y, r)
});
}
#[cfg(test)]
mod tests {
use super::*;
@@ -168,4 +270,60 @@ mod tests {
assert_eq!(existing_pattern(&d, &lib, "Dots").as_deref(), expected, "{other}");
}
}
fn grit_doc() -> Document {
let mut d = Document::new(100.0, 100.0);
grit_textures(&mut d);
d
}
#[test]
fn grit_textures_draw_the_same_marks_every_time() {
let (a, b) = (grit_doc(), grit_doc());
assert_eq!(a.patterns.len(), 8);
assert_eq!(a.patterns, b.patterns);
}
/// Every grit tile is 18 to 36 pt with at most 600 marks, each with an area, touching the tile
/// and near it. Marks reach past the edges, and the tiling draws a tile's art on the next tile
/// across each edge a mark crosses. No mark is another mark moved by a whole tile, which the tiling would draw
/// twice in one place.
#[test]
fn grit_tiles_join_without_a_seam() {
let mut crossing = 0;
for p in &grit_doc().patterns {
let (w, h) = (p.width(), p.height());
assert!((18.0..=36.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name);
assert!(!p.art.is_empty() && p.art.len() <= 600, "{}: {} marks", p.name, p.art.len());
let bounds: Vec<Rect> = p
.art
.iter()
.map(|n| match &n.kind {
vectorcraft_doc::NodeKind::Path { path, .. } => path.bounds().unwrap_or_else(|| panic!("{}: an empty mark", p.name)),
_ => panic!("{}: a mark that is not a path", p.name),
})
.collect();
let near = |a: &Rect, b: Rect| {
(a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9
};
let band = p.tile.inflate(w / 4.0, h / 4.0);
for b in &bounds {
assert!(b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name);
assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name);
assert!(b.x0 >= band.x0 && b.y0 >= band.y0 && b.x1 <= band.x1 && b.y1 <= band.y1, "{}: {b:?} is too far out", p.name);
// The tile past each edge the mark crosses draws this tile's art.
let (dx, dy) = (f64::from(i8::from(b.x1 > w) - i8::from(b.x0 < 0.0)), f64::from(i8::from(b.y1 > h) - i8::from(b.y0 < 0.0)));
for (x, y) in [(dx, 0.0), (0.0, dy), (dx, dy)] {
let next = p.tile + kurbo::Vec2::new(x * w, y * h);
assert!(p.offsets_covering(next).contains(&kurbo::Vec2::ZERO), "{}: {b:?} is cut off at {next:?}", p.name);
}
crossing += usize::from(dx != 0.0 || dy != 0.0);
for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] {
let moved = *b + kurbo::Vec2::new(dx, dy);
assert!(!bounds.iter().any(|o| near(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name);
}
}
}
assert!(crossing > 0, "no mark reaches past an edge");
}
}
+6 -4
View File
@@ -760,14 +760,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
// When the write failed, the old stored module stays in the folder and needs its grant at
// the next launch. A grant that can't be removed still approves the old bytes, so the store
// gets the module it held back. When that module can't be read or written back, or there
// was none, no module goes with the grant, and the grant stops counting for this session. A
// grants file that is too large or doesn't hold a list approves nothing, and the new module
// stays; one that can't be opened or read may approve the old bytes once it reads again.
// was none, no module goes with the grant, and the grant stops counting for every session in
// the process attached to the folder. A grants file that is too large or doesn't hold a list
// approves nothing, and the new module stays; one that can't be opened or read may approve
// the old bytes once it reads again.
let writes = s.grant_writes();
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
stored = !back && holds_new(s);
if !back || matches!(previous, Ok(None)) {
s.ignore_stored_grant(&m.id);
s.ignore_stored_grant(&m.id, writes);
}
}
}
@@ -108,6 +108,7 @@ pub(super) const ALLOWED: &[&str] = &[
"brush.move",
"brush.new",
"brush.options",
"brush.placeArt",
"brush.remove",
"brush.selectionArt",
"brush.setCurrent",
@@ -676,6 +677,7 @@ pub(super) const DENIED: &[&str] = &[
"addon.pen.nextSegment",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.createSpine",
"object.blend.options",
"object.liquify",
"object.pathfinder.options",
+44 -6
View File
@@ -687,6 +687,10 @@ impl Session {
for e in self.prefs.keep_folders(&mut p) {
log::warn!("{e}");
}
// Saved gradient presets get names no built-in preset or other saved one has.
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
}
// The edit the active tool computes on another thread is applied first (the Preferences
// dialog applies its settings here, outside a command). A failure to apply it was the
// edit's own, and the preferences apply all the same.
@@ -765,7 +769,7 @@ impl Session {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get),
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get),
cmd!(
query "prefs.set",
"Set Preference",
@@ -776,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> {
set
),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
cmd!(
query "prefs.export",
"Export Preferences",
@@ -882,8 +886,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "imported": values.len() }))
}
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
/// left out. An empty value (the default folder) and a scratch
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
fn shown_prefs(prefs: &Prefs) -> Value {
let mut all = prefs.to_json();
if crate::file_access::current().is_none() {
return all;
}
// The app trims a folder before it uses it.
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
for key in PATH_PREFS {
let Some(path) = all[key].as_str() else { continue };
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
all[key] = Value::Null;
}
}
if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) {
for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) {
if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) {
settings.remove("folder");
}
}
}
all
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
match str_param(p, "key") {
Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()),
Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))),
@@ -911,7 +949,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
if document_units && values.contains_key("unitsGeneral") && s.active().is_some() {
s.set_document_units(s.default_units())?;
}
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect()))
}
@@ -925,11 +963,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
let mut next = s.prefs.clone();
next.reset(cat);
s.apply_prefs(next);
Ok(json!({ "prefs": s.prefs.to_json() }))
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
Ok(Value::Array(
PREF_SPECS
.iter()
+234 -31
View File
@@ -17,7 +17,9 @@
//! store can, an announcement that lasts as long as the app ([`RecoveryStore::announce`]: the
//! browser's Web Locks). Only areas nobody holds any more (their app is gone) are offered, and
//! while their copies are restored or discarded the area is held, so two apps launched together
//! never both take it.
//! never both take it. An area's lock file or folder can be removed while its app runs, so each
//! recovery save and heartbeat checks that the lock still holds the area, and locks it again or
//! takes a new area.
//!
//! A heartbeat alone can't tell a gone app from one whose timers stopped (a background tab), so
//! when unsure an area counts as held, and its app repairs what another app did meanwhile: each
@@ -100,6 +102,12 @@ pub trait RecoveryStore: Send + Sync {
fn lock(&self, _area: &str) -> std::result::Result<Lock, String> {
Ok(Lock::Unsupported)
}
/// Does `hold`, which [`RecoveryStore::lock`] gave for area `area`, still hold it? A lock on a
/// file or folder that was removed or replaced since holds nothing; when that can't be told now,
/// it does (default: it does).
fn still_held(&self, _area: &str, _hold: &(dyn std::any::Any + Send + Sync)) -> bool {
true
}
/// Stores without locks: also hold area `area` in a way other apps can see that lasts exactly as
/// long as this app runs, if the store has one (the browser's Web Locks) → it, until dropped.
fn announce(&self, _area: &str) -> Option<Hold> {
@@ -266,7 +274,60 @@ impl FolderStore {
builder.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(dir).map_err(|e| format!("{}: {e}", dir.display()))
builder.create(dir).map_err(|e| Self::folder_error(dir, &e, true))
}
/// The first folder on the way to `dir` (`dir` included), from the top down, that is not a
/// folder (`true`) or is missing (`false`). None when every one of them is a folder or one of
/// them can't be checked.
fn in_the_way(dir: &std::path::Path) -> Option<(&std::path::Path, bool)> {
let mut way: Vec<&std::path::Path> = dir.ancestors().filter(|p| !p.as_os_str().is_empty()).collect();
way.reverse();
for p in way {
match std::fs::metadata(p) {
Ok(m) if m.is_dir() => {}
Ok(_) => return Some((p, true)),
Err(m) if m.kind() == std::io::ErrorKind::NotFound => return Some((p, false)),
Err(_) => return None,
}
}
None
}
/// The message for error `e` on folder `dir`, which was being made (`making`) or read. It
/// names the first folder on the way to `dir` that is not a folder, or is missing (when
/// `making`, the one that couldn't be made), and otherwise `dir`.
fn folder_error(dir: &std::path::Path, e: &std::io::Error, making: bool) -> String {
match Self::in_the_way(dir) {
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
Some((p, false)) if making => format!("couldn't make {}: {e}", p.display()),
Some((p, false)) if p != dir => format!("{} is missing", p.display()),
_ => format!("{}: {e}", dir.display()),
}
}
/// The message for error `e` on file `f`. It names the first folder on the way to `f` that is
/// not a folder or is missing, and otherwise `f`.
fn file_error(f: &std::path::Path, e: &std::io::Error) -> String {
match f.parent().and_then(Self::in_the_way) {
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
Some((p, false)) => format!("{} is missing", p.display()),
None => format!("{}: {e}", f.display()),
}
}
/// The outcome `r` of removing file `f`. A file that is not there counts as removed, unless a
/// file is on the way to it: Windows reports that as a missing file, and it is named as for a
/// listing.
pub(crate) fn removed(f: &std::path::Path, r: std::io::Result<()>) -> std::result::Result<(), String> {
match r {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => match f.parent().and_then(Self::in_the_way) {
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
_ => Ok(()),
},
Err(e) => Err(Self::file_error(f, &e)),
Ok(()) => Ok(()),
}
}
/// Refuse area folder `dir` unless it is a folder itself, not a link to one, and (on Unix)
@@ -274,7 +335,7 @@ impl FolderStore {
/// linked to a folder of its own in a shared recovery folder looked free, and claiming it
/// wrote the copies through the link.
fn own_area(dir: &std::path::Path) -> std::result::Result<(), String> {
let m = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let m = std::fs::symlink_metadata(dir).map_err(|e| Self::folder_error(dir, &e, false))?;
if !m.file_type().is_dir() {
return Err(format!("{}: not a folder of its own", dir.display()));
}
@@ -286,11 +347,17 @@ impl FolderStore {
}
/// The plain names of the files (or, `dirs`, folders) in `dir`; none when it doesn't exist.
/// A file on the way to `dir` is an error: Windows reports such a folder as missing.
fn names(dir: &std::path::Path, dirs: bool) -> std::result::Result<Vec<String>, String> {
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
Err(e) => return Err(format!("{}: {e}", dir.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return match Self::in_the_way(dir) {
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
_ => Ok(vec![]),
};
}
Err(e) => return Err(Self::folder_error(dir, &e, false)),
};
Ok(entries
.filter_map(|e| e.ok())
@@ -325,7 +392,7 @@ impl FolderStore {
match e.kind() {
std::io::ErrorKind::NotFound => Ok(Lock::Busy),
std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy),
_ => Err(format!("{}: {e}", path.display())),
_ => Err(Self::file_error(path, &e)),
}
}
@@ -337,7 +404,7 @@ impl FolderStore {
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
// The lock file was removed meanwhile, and locking it failed instead.
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
Err(std::fs::TryLockError::Error(e)) => Err(Self::file_error(path, &e)),
}
}
@@ -385,10 +452,10 @@ impl RecoveryStore for FolderStore {
if let Some(dir) = f.parent() {
Self::own_area(dir)?;
}
if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() {
if !std::fs::symlink_metadata(&f).map_err(|e| Self::file_error(&f, &e))?.file_type().is_file() {
return Err(format!("{}: not a plain file", f.display()));
}
std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display()))
std::fs::read(&f).map_err(|e| Self::file_error(&f, &e))
}
fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> {
let f = self.file(name)?;
@@ -396,14 +463,11 @@ impl RecoveryStore for FolderStore {
Self::create_area(dir)?;
Self::own_area(dir)?;
}
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| format!("{}: {e}", f.display()))
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
}
fn remove(&self, name: &str) -> std::result::Result<(), String> {
let f = self.file(name)?;
match std::fs::remove_file(&f) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", f.display())),
_ => Ok(()),
}
Self::removed(&f, std::fs::remove_file(&f))
}
fn location(&self) -> String {
self.0.to_string_lossy().into_owned()
@@ -416,6 +480,16 @@ impl RecoveryStore for FolderStore {
Self::create_area(&dir)?;
Self::lock_area(&dir)
}
fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool {
let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true };
let path = dir.join(LOCK_FILE);
// Only a lock file or folder that is gone, or another one in its place, ends the hold. One
// that can't be read now (a network folder that doesn't answer) still counts as held.
match std::fs::symlink_metadata(&path) {
Ok(_) => Self::own_area(&dir).is_ok() && Self::still_named(file, &path),
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
}
}
fn remove_area(&self, area: &str) {
// Best effort: whatever is left is tidied at a later launch. A folder that isn't empty
// (copies came back meanwhile) stays. The caller still holds the lock here.
@@ -457,6 +531,10 @@ pub struct Recovery {
/// heartbeat it wrote there: that one doesn't make them look running, a newer one does (their
/// app was only paused and came back).
adopted: BTreeMap<String, i64>,
/// Copies in an area this session had to leave (`keep_hold`), by document uid, with their
/// store: each stays until its document has a copy in the new area, or needs none. They are
/// still this session's: never offered or discarded as a crash's here.
left: BTreeMap<u64, (Arc<dyn RecoveryStore>, String)>,
}
impl Recovery {
@@ -526,14 +604,81 @@ fn beating(store: &dyn RecoveryStore, area: &str, stale: i64, mine: Option<i64>)
/// Refresh this session's hold on its area (the app does this every [`HEARTBEAT_EVERY`] seconds,
/// so also on its first frame after its timers were paused): its heartbeat in a store without
/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now).
/// Best effort: a missed beat only lets another app offer the copies once three intervals have
/// passed.
/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now),
/// and those whose only copy is in an area the session left (`keep_hold`). Best effort: a missed
/// beat only lets another app offer the copies once three intervals have passed.
pub fn heartbeat(s: &mut Session) -> Vec<u64> {
let mut lost = keep_hold(s);
if let Some(own) = s.recovery.own.as_ref().filter(|o| o.beats) {
let _ = beat(own.store.as_ref(), &own.area);
}
repair(s)
// A copy that was being written when the session left its area finished there. A document
// that gets no copy now (a complex one) keeps the copy it has.
lost.extend(
s.recovery
.left
.keys()
.filter(|&&uid| s.documents().iter().any(|d| d.uid == uid && d.recovery.is_none() && skip_reason(s, d).is_none()))
.copied(),
);
lost.extend(repair(s));
lost.sort_unstable();
lost.dedup();
lost
}
/// Check that this session's lock still holds its area (stores with locks). The area's lock file,
/// or the whole area, can be removed while the app runs (by the user, a cleaner, another program),
/// and then another app can lock the area and offer or delete this session's copies as a crash's.
/// The area is locked again, made again first if it went (its copies are then written again).
/// When another app holds it now, the session takes a new area, and each copy left in the old one
/// stays until its document has a copy in the new one. → the documents whose copies must be
/// written again.
fn keep_hold(s: &mut Session) -> Vec<u64> {
drop_left_done(s);
let Some(own) = &mut s.recovery.own else { return vec![] };
if own.beats || own.hold.as_deref().is_none_or(|h| own.store.still_held(&own.area, h)) {
return vec![];
}
let (store, area) = (own.store.clone(), own.area.clone());
// The lock held is on a file the area no longer has, so it holds nothing: it goes first (a
// removed file this app still has open can keep a new lock file from being made).
own.hold = None;
if let Ok(Lock::Held(h)) = store.lock(&area) {
own.hold = Some(h);
return repair(s);
}
let mut lost = vec![];
for st in &mut s.docs {
if let Some(c) = st.recovery.take() {
s.recovery.left.insert(st.uid, (store.clone(), c.file));
lost.push(st.uid);
}
}
s.recovery.own = None;
// Best effort: when no area can be taken now, the next recovery save says why.
let _ = claim(s, &store);
lost
}
/// The copies left in an area this session left whose documents were saved, reverted or closed
/// since go.
fn drop_left_done(s: &mut Session) {
let done: Vec<u64> = s.recovery.left.keys().filter(|&&uid| !s.documents().iter().any(|d| d.uid == uid && d.is_dirty())).copied().collect();
for uid in done {
drop_left(s, uid);
}
}
/// Document `uid`'s copy in an area this session left goes. A copy that can't be removed now stays
/// this session's, and a later heartbeat removes it.
fn drop_left(s: &mut Session, uid: u64) {
let Some((store, file)) = s.recovery.left.get(&uid) else { return };
let doc = store.remove(&format!("{file}{DOC_EXT}"));
let meta = store.remove(&format!("{file}{META_EXT}"));
if doc.is_ok() && meta.is_ok() {
s.recovery.left.remove(&uid);
}
}
/// Forget this session's copies that are missing from its area, so the next recovery save writes
@@ -555,10 +700,13 @@ pub fn repair(s: &mut Session) -> Vec<u64> {
/// This session's area in `store`, taken now if it has none there yet: a fresh area, held for the
/// session's lifetime (locked, or with a heartbeat and an announcement where the store has them).
pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> {
if let Some(own) = &s.recovery.own {
if own.store.location() == store.location() {
if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) {
// Documents whose copies went are left without one, so the caller writes them again.
keep_hold(s);
if let Some(own) = &s.recovery.own {
return Ok(own.area.clone());
}
} else if s.recovery.own.is_some() {
// The store moved (the preference names another folder): copies start again there.
release(s);
}
@@ -588,6 +736,11 @@ pub fn release(s: &mut Session) {
for st in &mut s.docs {
st.recovery = None;
}
// Copies left in an area this session had to leave go too.
let left: Vec<u64> = s.recovery.left.keys().copied().collect();
for uid in left {
drop_left(s, uid);
}
let Some(Own { store, area, hold, .. }) = s.recovery.own.take() else { return };
let mine = |n: &String| n.split_once('/').is_some_and(|(a, _)| a == area);
for name in store.list().unwrap_or_default().iter().filter(|n| mine(n)) {
@@ -750,12 +903,16 @@ pub struct RecoveryJob {
pub title: String,
meta: Meta,
save: SaveJob,
/// The store the copy goes to (the preference can name another folder before it is finished).
store: Arc<dyn RecoveryStore>,
}
impl RecoveryJob {
/// Encode the snapshot and store it with its details and the images the area doesn't have
/// yet → `{file, title, bytes (the document's), imageBytes (images written now)}`.
pub fn write(&self, store: &dyn RecoveryStore) -> std::result::Result<Value, String> {
/// yet, in the store the job was made for → `{file, title, bytes (the document's), imageBytes
/// (images written now)}`.
pub fn write(&self) -> std::result::Result<Value, String> {
let store = self.store.as_ref();
let doc = self.save.doc();
// A linked image keeps its preview, as a save writes it.
let linked = doc.linked_only_images();
@@ -808,13 +965,35 @@ impl RecoveryJob {
/// Once stored: the document (if still open) remembers the copy, so it isn't written again
/// while unchanged and goes when the document is saved or closed. A document saved or closed
/// meanwhile has nothing left to recover: its copy goes at once.
/// meanwhile has nothing left to recover: its copy goes at once. So does a copy written in an
/// area the session left meanwhile (`keep_hold`), and its document gets a new one.
pub fn finish(self, s: &mut Session) {
let snapshot = self.save.snapshot().clone();
let copy = RecoveryCopy { file: self.file.clone(), doc: snapshot };
let area = self.file.split_once('/').map(|(a, _)| a);
let current = s.recovery.own.as_ref().is_some_and(|o| o.store.location() == self.store.location() && Some(o.area.as_str()) == area);
match s.document_mut(self.uid).filter(|st| st.is_dirty()) {
Some(st) => st.recovery = Some(copy),
None => remove_copy(s, &self.file),
Some(st) if current => {
st.recovery = Some(copy);
drop_left(s, self.uid);
}
// Written in an area left meanwhile: kept, in place of the copy left there before,
// until the document has a copy in the new area.
Some(st) if st.recovery.is_none() => {
let before = s.recovery.left.insert(self.uid, (self.store.clone(), self.file.clone()));
// The copy left there before, unless this one was written over it. Best effort,
// as in `remove_copy`.
if let Some((store, file)) = before.filter(|(old, f)| old.location() != self.store.location() || *f != self.file) {
let _ = store.remove(&format!("{file}{DOC_EXT}"));
let _ = store.remove(&format!("{file}{META_EXT}"));
}
}
// Best effort, as in `remove_copy`.
_ => {
let _ = self.store.remove(&format!("{}{DOC_EXT}", self.file));
let _ = self.store.remove(&format!("{}{META_EXT}", self.file));
drop_left(s, self.uid);
}
}
}
}
@@ -867,6 +1046,11 @@ fn fresh_name(area: &str, stem: &str, taken: &[String]) -> String {
/// when it has none and a copy is needed) → (jobs, skipped: `[{title, reason}]` for modified
/// documents that get none).
pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<RecoveryJob>, Vec<Value>)> {
// A lost lock is taken again first: copies that go with it are written again, even of
// documents unchanged since.
if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) {
keep_hold(s);
}
// Copies another app removed are written again.
repair(s);
let skipped: Vec<Value> = s
@@ -923,7 +1107,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
// Filled in as the copy is written.
images: BTreeMap::new(),
};
out.push(RecoveryJob { uid: st.uid, file, title, meta, save });
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
}
Ok((out, skipped))
}
@@ -954,7 +1138,7 @@ pub(crate) fn save_copies(s: &mut Session) -> Result<()> {
return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into()));
}
for j in jobs {
j.write(store.as_ref()).map_err(EngineError::Other)?;
j.write().map_err(EngineError::Other)?;
j.finish(s);
}
Ok(())
@@ -966,6 +1150,8 @@ pub fn forget(s: &mut Session, uid: u64) {
if s.script_in_run {
return;
}
// So does a copy of it left in an area this session left.
drop_left(s, uid);
let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return };
remove_copy(s, &copy.file);
}
@@ -975,12 +1161,16 @@ pub fn forget_all(s: &mut Session) {
release(s);
}
/// The copies of documents with no unsaved changes left (undone back to the saved state) go.
/// The copies of documents with no unsaved changes left (undone back to the saved state) go, and
/// the copies left in an area this session left of documents closed since.
pub fn forget_clean(s: &mut Session) {
let uids: Vec<u64> = s.documents().iter().filter(|d| !d.is_dirty() && d.recovery.is_some()).map(|d| d.uid).collect();
for uid in uids {
forget(s, uid);
}
if !s.script_in_run {
drop_left_done(s);
}
}
fn save(s: &mut Session, _: &Value) -> Result<Value> {
@@ -988,7 +1178,7 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> {
let (jobs, skipped) = jobs(s, &store)?;
let mut saved = vec![];
for j in jobs {
saved.push(j.write(store.as_ref()).map_err(EngineError::Other)?);
saved.push(j.write().map_err(EngineError::Other)?);
j.finish(s);
}
forget_clean(s);
@@ -1057,9 +1247,15 @@ fn open_copies(s: &Session) -> Vec<String> {
s.documents().iter().filter_map(|d| d.recovery.as_ref()).map(|c| c.file.clone()).collect()
}
/// The copies of documents open now in this session that are in an area it left, in `store`.
fn left_copies(s: &Session, store: &dyn RecoveryStore) -> Vec<String> {
s.recovery.left.values().filter(|(st, _)| st.location() == store.location()).map(|(_, f)| f.clone()).collect()
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let store = need_store(s, "file.recovery.list")?;
let open = open_copies(s);
let left = left_copies(s, store.as_ref());
let copies = copies_in(&store.list().map_err(EngineError::Other)?);
let mut rows = vec![];
for area in store.areas().map_err(EngineError::Other)? {
@@ -1071,7 +1267,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title };
rows.push(json!({
"file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved,
"open": who == Owner::Mine && open.contains(f), "running": who == Owner::Running,
"open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running,
}));
}
// A gone app's empty area is tidied away.
@@ -1095,7 +1291,14 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) ->
{
return Err(bad(cmd, format!("no recovery copy `{f}` (see file.recovery.list)")));
}
let picked = |c: &str| file.is_none_or(|f| f == c);
// A copy this session left in an area it had to leave is still its own.
let left = left_copies(s, store);
if let Some(f) = file
&& left.iter().any(|c| c == f)
{
return Err(bad(cmd, format!("`{f}` is the copy of a document open now")));
}
let picked = |c: &str| file.is_none_or(|f| f == c) && !left.iter().any(|l| l == c);
let areas: BTreeSet<&str> = copies.iter().filter(|(_, c)| picked(c)).map(|(a, _)| a.as_str()).collect();
let mut out = vec![];
for area in areas {
+36 -8
View File
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Tab Stops",
["Window", "Tabs"],
None,
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); at most 256 stops, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept",
has_selection,
set
),
@@ -38,10 +38,14 @@ pub fn specs() -> Vec<CommandSpec> {
fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
const C: &str = "text.tabs.set";
let arr = p.get("stops").and_then(Value::as_array).ok_or_else(|| bad(C, "missing stops"))?;
let max = TabStop::MAX_STOPS;
if arr.len() > max {
return Err(bad(C, format!("at most {max} tab stops")));
}
let mut stops = vec![];
for s in arr {
let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?;
if !(0.0..=100_000.0).contains(&position) {
if !(0.0..=TabStop::MAX_POSITION).contains(&position) {
return Err(bad(C, "positions must be between 0 and 100000 pt"));
}
let align = match s.get("align") {
@@ -60,16 +64,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
None | Some(Value::Null) => "",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(C, "`leader` must be a string")),
};
let (label, max) = ("`leader`", TabStop::MAX_LEADER);
if leader.chars().count() > max {
return Err(bad(C, format!("{label} must be at most {max} characters")));
}
.chars()
.take(8)
.collect();
let align_on = match s.get("alignOn") {
None | Some(Value::Null) => '.',
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
Some(Value::String(value)) => {
let mut chars = value.chars();
let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?;
if chars.next().is_some() {
let label = "`alignOn`";
return Err(bad(C, format!("{label} must be one character")));
}
c
}
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
};
stops.push(TabStop { position, align, leader, align_on });
stops.push(TabStop { position, align, leader: leader.to_string(), align_on });
}
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
@@ -128,7 +141,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use serde_json::json;
use serde_json::{Value, json};
use crate::Session;
@@ -139,6 +152,21 @@ mod tests {
}
}
/// A leader of more than eight characters, an `alignOn` of more than one character and a list
/// of more than 256 stops are errors, not cut short.
#[test]
fn long_leaders_long_align_on_and_too_many_stops_are_errors() {
let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string();
assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters"));
assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character"));
let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect();
assert!(err(Value::from(many.clone())).contains("at most 256 tab stops"));
let ok = super::parse_stops(&json!({ "stops": &many[..256] })).unwrap();
assert_eq!(ok.len(), 256);
let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap();
assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€'));
}
#[test]
fn set_get_clear_tabs() {
let mut s = Session::new();
+56 -16
View File
@@ -8,7 +8,7 @@
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef};
use super::clipboard::resources::import_text_styles;
use super::typecmd::{refresh_bounds, text_targets};
@@ -125,7 +125,7 @@ macro_rules! style_cmds {
}
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
pub fn specs() -> Vec<CommandSpec> {
let mut v = style_cmds!(
@@ -148,13 +148,13 @@ pub fn specs() -> Vec<CommandSpec> {
"paraStyle",
"Paragraph Styles",
"Paragraph",
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position"
));
v.push(spec(
"paraStyle.edit",
"Edit Paragraph Style",
&[],
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
|s, p| edit_style(s, p, Kind::Para),
true,
));
@@ -569,8 +569,9 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
char_attrs(&st)
}
Kind::Para => {
let st = with_attrs(&ParaStyle::default(), m, &c)?;
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
para_ranges(&st, m, kept, &c)?;
sort_tabs(&mut st, m, kept);
para_attrs(&st)
}
};
@@ -587,7 +588,8 @@ const PARA_DISTANCE: f64 = 1296.0;
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
/// `kept` does not hold. A value `kept` has is not checked.
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
let within = |key: &str, value: f64, lo: f64, hi: f64| {
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
@@ -644,18 +646,37 @@ fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<Str
}
}
if changed("tabs") {
let kept_tabs: Vec<f64> = kept
.and_then(|k| k.get("tabs"))
.and_then(Value::as_array)
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
.unwrap_or_default();
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
within("tabs.position", stop.position, 0.0, 100_000.0)?;
let kept_tabs = kept_tab_stops(kept);
let max = TabStop::MAX_STOPS;
if st.tabs.len() > max.max(kept_tabs.len()) {
return Err(bad(c, format!("at most {max} tab stops")));
}
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
if stop.leader.chars().count() > max {
return Err(bad(c, format!("{label} must be at most {max} characters")));
}
}
}
Ok(())
}
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> {
let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array);
stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect()
}
/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other,
/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`.
fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) {
if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") {
st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
}
}
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
@@ -1011,10 +1032,29 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name
/// is empty, which are skipped. → (the styles, the names in `src` of those skipped)
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"];
const RANGED: [&str; 16] = [
"size",
"h_scale",
"v_scale",
"leading",
"baseline_shift",
"tcyUpDown",
"tcyLeftRight",
"stroke_width",
"left_indent",
"right_indent",
"first_line_indent",
"space_before",
"space_after",
"hyphenation",
"justification",
"tabs",
];
let (mut defs, mut skipped) = (vec![], vec![]);
for def in kind.defs(src) {
let name = def.name.as_str();
+74
View File
@@ -1729,3 +1729,77 @@ fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
}
}
/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept
/// as it is, and a stop at a held position with another alignment is a changed stop. A changed
/// stop's leader has at most eight characters and its Align On one character, a changed list has
/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position,
/// keeping the first of stops at one position.
#[test]
fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() {
let (mut s, _) = session_with_text("Text");
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let held: Vec<Value> =
(0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect();
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone()));
let before = s.doc().unwrap().doc.clone();
let mut moved = held.clone();
moved[0]["align"] = json!("right");
for (stops, why) in [
(Value::from(moved), "`tabs.position`"),
(json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"),
(Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"),
(json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"),
] {
for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] {
let params = match cmd {
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}),
_ => json!({"name": "Body", "attrs": {"tabs": stops}}),
};
let error = s.execute(cmd, &params).unwrap_err().to_string();
assert!(error.contains(why), "{cmd}: {error}");
}
}
let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>());
let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string();
assert!(error.contains("at most 256 tab stops"), "{error}");
assert_eq!(s.doc().unwrap().doc, before);
// The held stops stay while one is dropped and another attribute changes.
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap();
assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299));
let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]);
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap();
assert_eq!(
def(&s)["tabs"],
json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."},
{"position": 72.0, "align": "right", "alignOn": "."}])
);
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap();
assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set");
}
/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing,
/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes,
/// and load the others with their stops.
#[test]
fn loading_skips_paragraph_styles_out_of_range() {
let file = [
("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})),
("Indent", json!({"left_indent": 2000.0})),
("Space", json!({"space_after": -1300.0})),
("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})),
("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})),
("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})),
];
let data = styles_file(&[], &file);
for cmd in ["paraStyle.load", "textStyle.loadAll"] {
let (mut s, _) = session_with_text("Title");
let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r };
assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}");
let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap();
assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}");
}
}
@@ -140,6 +140,35 @@ fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes()
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
}
#[test]
fn convert_to_point_type_turns_block_off_keeping_its_sizes() {
let mut s = session();
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line");
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>();
let fitted = sizes(&text(&s, id));
let n = undo_len(&s);
s.execute("type.convertToPointType", &json!({})).unwrap();
assert_eq!(undo_len(&s), n + 1, "one undo step");
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Point));
assert!(!t.dynamic_text, "point type has Dynamic Text off");
assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set");
assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText");
// Back to area type, the frame is not refitted: Block stays off.
s.execute("type.convertToAreaType", &json!({})).unwrap();
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Area { .. }));
assert!(!t.dynamic_text, "Block does not come on again");
assert_eq!(sizes(&t), fitted);
// Undo gives the Block frame back.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let t = text(&s, id);
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
assert_eq!(sizes(&t), fitted);
}
#[test]
fn bad_params_and_other_type_are_refused() {
let mut s = session();
+4 -1
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert To Point Type",
["Type"],
None,
"{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}",
"{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}",
has_selection,
to_point
),
@@ -410,6 +410,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1,
_ => x0,
};
// Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so
// converting back to area type does not turn it on again.
t.dynamic_text = false;
t.kind = TextKind::Point;
t.xf *= Affine::translate((ox, baseline));
refresh_bounds(t);
+2 -4
View File
@@ -171,10 +171,6 @@ pub struct Session {
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
/// [`Session::store_grant`] for the id takes it out.
ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>,
/// 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>,
@@ -306,6 +302,8 @@ pub struct Session {
pub(crate) press_point: Option<Option<(usize, cmd::gradient::StopOwner)>>,
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
/// The rulers' origin being dragged out of their corner ([`Session::ruler_origin_drag`]).
pub(crate) ruler_origin: Option<vectorcraft_tools::rulerguide::OriginDrag>,
/// Which selected type overflows its frame, for the ports every tool but the Type tools shows.
pub(crate) port_marks: vectorcraft_tools::text::PortMarks,
/// The last search for the files of missing fonts (`text.findFontFiles`), until another
+4 -3
View File
@@ -1787,6 +1787,10 @@ impl Session {
if let Some(e) = job.host.dialogs.take_failure() {
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() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
@@ -1798,9 +1802,6 @@ impl Session {
let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 };
return Some(self.script_failed(job, &e));
}
if vectorcraft_doc::cancel::check().is_err() {
self.script_stop.set();
}
job.host.calls_this_slice.set(0);
let outcome = run_slice(self, &mut job);
match outcome {
+1 -1
View File
@@ -87,7 +87,6 @@ impl Session {
color_settings_file: None,
plugin_dir: None,
scripts_dir: None,
ignored_plugin_grants: Default::default(),
plugin_output: None,
plugin_install_approval: None,
plugin_grants_from_requests: false,
@@ -124,6 +123,7 @@ impl Session {
press_type_selection: None,
press_point: None,
ruler_guide: None,
ruler_origin: None,
port_marks: Default::default(),
font_search: None,
link_search: None,
+7 -1
View File
@@ -82,7 +82,13 @@ impl Session {
&& params.get("ids").is_none_or(Value::is_null)
&& params.get("id").and_then(Value::as_str).is_some_and(|e| !e.starts_with('$'));
if cmd::params::id_stands_for_ids(spec.params) && !effect_named && self.active().is_some() {
cmd::given_objects(self, params, id)?;
// `effect.refreshDeferred` looks its objects up itself: they can also be in the art of
// a symbol, pattern, brush or opacity mask.
if id == "effect.refreshDeferred" {
cmd::given_object_ids(params, id)?;
} else {
cmd::given_objects(self, params, id)?;
}
}
if SELECTS_GIVEN_IDS.contains(&id) {
self.check_given_ids(id, params)?;
+117 -19
View File
@@ -89,6 +89,24 @@ static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
/// the plug-in is removed, which closes it and drops it.
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new());
/// The grants of plug-in stores that the sessions of the process don't count, and when each was
/// last written ([`IgnoredGrants`]). Another process reads `grants.json` as it is.
static IGNORED_PLUGIN_GRANTS: Mutex<IgnoredGrants> = Mutex::new(IgnoredGrants { ignored: BTreeSet::new(), written: BTreeMap::new(), writes: 0 });
/// How many of the latest grant writes [`IgnoredGrants`] keeps.
const MAX_GRANT_WRITES_KEPT: usize = 256;
/// Grants of plug-in stores, by the store's folder ([`plugin_store_key`]) and the plug-in id.
struct IgnoredGrants {
/// The grants that should be gone but could not be removed: no session in the process counts
/// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id
/// ([`Session::store_grant`]).
ignored: BTreeSet<(PathBuf, String)>,
/// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the
/// count of writes it made ([`IgnoredGrants::writes`]).
written: BTreeMap<(PathBuf, String), u64>,
/// How many grant writes the sessions of the process have made ([`Session::grant_writes`]).
writes: u64,
}
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
/// file system, then a hash of the name, so that names that differ only in characters a file name
@@ -100,6 +118,37 @@ pub(crate) fn file_stem(name: &str) -> String {
format!("{}-{hash:016x}", safe.trim())
}
/// The folder `dir` spelled one way for every path to it, so that sessions attached to it by
/// different paths share [`IGNORED_PLUGIN_GRANTS`]: the canonical path when the folder exists, else
/// the canonical path of its nearest folder that exists followed by the rest of the path, with `.`
/// and `..` taken out by name. The path as given when it has no absolute form (the current folder
/// can't be read).
pub(crate) fn plugin_store_key(dir: &Path) -> PathBuf {
if let Ok(path) = std::fs::canonicalize(dir) {
return path;
}
let Ok(absolute) = std::path::absolute(dir) else { return dir.to_path_buf() };
let mut parts: Vec<std::path::Component> = Vec::new();
for part in absolute.components() {
match part {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
if matches!(parts.last(), Some(std::path::Component::Normal(_))) {
parts.pop();
}
}
_ => parts.push(part),
}
}
for kept in (1..=parts.len()).rev() {
let base: PathBuf = parts[..kept].iter().collect();
if let Ok(found) = std::fs::canonicalize(&base) {
return parts[kept..].iter().fold(found, |path, part| path.join(part));
}
}
parts.iter().collect()
}
/// The regular files of `dir` with the extension `ext` (any case), by file name, at most
/// [`MAX_STORE_FILES`]; none when the folder can't be read.
fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
@@ -191,6 +240,9 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> {
thread_local! {
/// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume.
pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when
/// another program holds it open.
pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then
/// reports a failure, as when the last flush of a copy fails.
pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
@@ -205,7 +257,15 @@ thread_local! {
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
fn take(dir: &Path, file: &str) -> bool {
let path = dir.join(file);
match std::fs::remove_file(&path) {
#[cfg(test)]
let removed = if file == GRANTS_FILE && GRANTS_DELETE_FAILS.get() {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
} else {
std::fs::remove_file(&path)
};
#[cfg(not(test))]
let removed = std::fs::remove_file(&path);
match removed {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
log::warn!("can't remove {}: {e}", path.display());
false
@@ -344,9 +404,6 @@ impl Session {
let disabled =
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
safe_mode::set_disabled(disabled);
if self.plugin_dir.as_ref() != Some(&dir) {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
self.plugin_dir = Some(dir);
self.load_stored_plugins();
}
@@ -357,7 +414,8 @@ impl Session {
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
/// stays in the folder with its grant. A grant for an id whose stored module lists no
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
/// the rest of the session ([`Session::plugin_approver`]).
/// any session in the process attached to the folder until the file can be written for the id
/// ([`Session::ignore_stored_grant`]).
pub fn load_stored_plugins(&mut self) {
let Some(dir) = self.plugin_dir.clone() else { return };
if safe_mode::active() {
@@ -421,8 +479,11 @@ impl Session {
Ok(file) => file.names(id),
Err(e) => e.unread,
};
if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) {
self.ignore_stored_grant(id);
if named {
let writes = self.grant_writes();
if !self.store_grant(id, None) && self.holds_plugin_grant(id) {
self.ignore_stored_grant(id, writes);
}
}
}
}
@@ -504,12 +565,16 @@ impl Session {
}
}
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
/// doesn't count ([`Session::ignore_stored_grant`]).
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those the process
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner());
let key = plugin_store_key(dir);
let mut grants = stored_grants(dir);
grants.retain(|id, _| !ignored.contains(id));
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
grants.remove(id);
}
grants
}
@@ -562,20 +627,53 @@ impl Session {
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
/// again ([`Session::ignore_stored_grant`]).
/// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]).
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
let done = self.write_grant(id, grant);
if done {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
let entry = (key, id.to_string());
shared.ignored.remove(&entry);
shared.writes = shared.writes.saturating_add(1);
let writes = shared.writes;
shared.written.insert(entry, writes);
if shared.written.len() > MAX_GRANT_WRITES_KEPT
&& let Some(oldest) = shared.written.iter().min_by_key(|(_, at)| **at).map(|(entry, _)| entry.clone())
{
shared.written.remove(&oldest);
}
}
done
}
/// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next
/// succeeds for it or another store is attached: for a grant that should be gone and could not
/// be removed, which would otherwise approve the bytes it covers.
pub(crate) fn ignore_stored_grant(&self, id: &str) {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string());
/// How many grant writes the sessions of the process have made ([`Session::store_grant`]).
/// Taken before a write that may fail, for [`Session::ignore_stored_grant`].
pub(crate) fn grant_writes(&self) -> u64 {
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes
}
/// How many grant writes the process keeps ([`IgnoredGrants::written`]).
#[cfg(test)]
pub(crate) fn grant_writes_kept() -> usize {
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).written.len()
}
/// Stop counting the attached store's grant for the plug-in `id`, in every session in the
/// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in
/// one of them: for a grant that should be gone and could not be removed, which would otherwise
/// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed
/// write: when a session has written the store's grants for `id` since, the file holds what that
/// write asked for, and the grant keeps counting. A write no longer among the latest
/// [`MAX_GRANT_WRITES_KEPT`] is not seen, and the grant stops counting. Another process on the
/// folder reads `grants.json` as it is.
pub(crate) fn ignore_stored_grant(&self, id: &str, writes: u64) {
if let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
let entry = (key, id.to_string());
if shared.written.get(&entry).is_none_or(|at| *at <= writes) {
shared.ignored.insert(entry);
}
}
}
fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
+1
View File
@@ -133,6 +133,7 @@ mod placed_document;
mod plugins;
mod prefs;
mod prefs_file;
mod prefs_roots;
mod previewbounds;
mod print;
mod printadvanced;
+176
View File
@@ -418,3 +418,179 @@ fn native_blend_easing_values_clamp_and_non_finite_become_default() {
assert_eq!((spec.ease.ramp, spec.color_shift), (ramp, shift), "{bad}");
}
}
fn create_spine(s: &mut Session, p: Value) -> Value {
s.execute("object.blend.createSpine", &p).unwrap()["mode"].clone()
}
/// Two squares 100 pt apart blended with `p`; the blend.
fn make(s: &mut Session, y: f64, p: Value) -> NodeId {
let (a, b) = (rect(s, 0.0, y, 10.0), rect(s, 100.0, y, 10.0));
let mut p = p;
p["ids"] = json!([a.0, b.0]);
p["steps"] = json!(3);
id_of(&s.execute("object.blend.make", &p).unwrap())
}
#[test]
fn create_spine_sets_whether_new_blends_get_a_spine() {
let mut s = session();
assert_eq!(create_spine(&mut s, json!({})), "auto", "Auto until one is chosen");
let spined = make(&mut s, 0.0, json!({}));
assert!(!spec(&s, spined).1.no_spine);
let depth = s.doc().unwrap().history.undo.len();
assert_eq!(create_spine(&mut s, json!({"mode": "never"})), "never");
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "a tool setting, not an undo step");
assert_eq!(create_spine(&mut s, json!({})), "never");
// The Blend Options set with nothing selected keep it, and it keeps them.
s.execute("select.none", &json!({})).unwrap();
s.execute("object.blend.options", &json!({"steps": 7})).unwrap();
assert_eq!(create_spine(&mut s, json!({})), "never");
assert_eq!(s.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
// A new blend has no spine; the blend made before keeps its own.
let bare = make(&mut s, 50.0, json!({}));
assert!(spec(&s, bare).1.no_spine);
assert!(!spec(&s, spined).1.no_spine, "blends already made keep their spine");
sel(&mut s, &[bare]);
let info = s.execute("object.blend.info", &json!({})).unwrap();
assert_eq!(info["hasSpine"], json!(false));
assert!(info.get("spine").is_none(), "{info}");
sel(&mut s, &[spined]);
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap()["hasSpine"], json!(true));
// `createSpine` on Make chooses for that blend only.
let forced = make(&mut s, 100.0, json!({"createSpine": "always"}));
assert!(!spec(&s, forced).1.no_spine);
assert_eq!(create_spine(&mut s, json!({})), "never");
assert_eq!(create_spine(&mut s, json!({"mode": "always"})), "always");
let always = make(&mut s, 150.0, json!({}));
assert!(!spec(&s, always).1.no_spine);
assert!(spec(&s, bare).1.no_spine, "blends already made keep having no spine");
let none = make(&mut s, 200.0, json!({"createSpine": "never"}));
assert!(spec(&s, none).1.no_spine);
// The setting survives a round trip through the preferences file; Auto is not written.
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(back.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Always);
assert_eq!(s.prefs.to_json()["blendOptions"]["createSpine"], json!("always"));
create_spine(&mut s, json!({"mode": "auto"}));
assert!(s.prefs.to_json()["blendOptions"].get("createSpine").is_none());
let mut odd = s.prefs.to_json();
odd["blendOptions"]["createSpine"] = json!("sometimes");
let unknown: Prefs = serde_json::from_value(odd).unwrap();
assert_eq!(unknown.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Auto, "an unknown value reads as Auto");
}
#[test]
fn create_spine_refuses_bad_values_and_changes_nothing() {
let mut s = session();
create_spine(&mut s, json!({"mode": "never"}));
let prefs = s.prefs.blend_options;
for bad in [json!({"mode": "sometimes"}), json!({"mode": 1}), json!({"mode": true}), json!({"mode": ["never"]}), json!({"mode": "Never"})] {
let e = s.execute("object.blend.createSpine", &bad).unwrap_err().to_string();
assert!(e.contains("`mode` must be one of auto, always, never"), "{bad}: {e}");
assert_eq!(s.prefs.blend_options, prefs, "{bad}");
}
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0));
let depth = s.doc().unwrap().history.undo.len();
for bad in [json!({"createSpine": "x"}), json!({"createSpine": 0}), json!({"createSpine": "never", "easingType": "easeIn"}), json!({"ramp": 30})]
{
let mut p = bad.clone();
p["ids"] = json!([a.0, b.0]);
assert!(s.execute("object.blend.make", &p).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "{bad}: nothing made");
}
assert!(s.execute("object.blend.createSpine", &json!({"spine": "never"})).is_err(), "an unknown key");
}
#[test]
fn a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release() {
let mut s = session();
let g = make(&mut s, 0.0, json!({"createSpine": "never"}));
sel(&mut s, &[g]);
let before = node(&s, g);
let depth = s.doc().unwrap().history.undo.len();
// Reverse Spine, easing and the spine point commands refuse it and change nothing.
let refused = [
("object.blend.reverseSpine", json!({})),
("object.blend.options", json!({"easingType": "easeOut"})),
("object.blend.options", json!({"ramp": 40})),
("object.blend.spine.addAnchor", json!({"x": 50, "y": 5})),
("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 50})),
];
for (cmd, p) in refused {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("the blend has no spine"), "{cmd}: {e}");
assert_eq!((node(&s, g), s.doc().unwrap().history.undo.len()), (before.clone(), depth), "{cmd}");
}
// Spacing, Orientation and Shift still apply; Align to Path makes no spine.
s.execute("object.blend.options", &json!({"steps": 2, "orientation": "path", "colorShift": 20})).unwrap();
let sp = spec(&s, g).1;
assert_eq!((sp.spacing, sp.orientation, sp.color_shift, sp.no_spine), (BlendSpacing::Steps(2), BlendOrientation::AlignToPath, 20.0, true));
assert!(s.execute("object.blend.info", &json!({})).unwrap().get("spine").is_none());
// Taking in another key keeps it without a spine, whatever Create Spine says.
let c = rect(&mut s, 200.0, 0.0, 10.0);
sel(&mut s, &[g, c]);
create_spine(&mut s, json!({"mode": "always"}));
let g = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
assert_eq!(spec(&s, g).0.len(), 3);
assert!(spec(&s, g).1.no_spine && spec(&s, g).1.spine.is_none());
// Release gives back the keys and no spine path.
sel(&mut s, &[g]);
let r = s.execute("object.blend.release", &json!({})).unwrap();
assert_eq!((r["ids"].as_array().map(Vec::len), &r["spines"]), (Some(3), &json!([])));
s.execute("edit.undo", &json!({})).unwrap();
// Replace Spine gives it one: then it reverses and eases like any other.
let line = id_of(&s.execute("path.create", &json!({"d": "M0 100 L200 150"})).unwrap());
sel(&mut s, &[g, line]);
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
let sp = spec(&s, g).1;
assert!(!sp.no_spine && sp.spine.is_some());
let info = s.execute("object.blend.info", &json!({})).unwrap();
assert_eq!((&info["hasSpine"], &info["spine"]["explicit"]), (&json!(true), &json!(true)));
s.execute("object.blend.reverseSpine", &json!({})).unwrap();
s.execute("object.blend.options", &json!({"easingType": "easeOut", "ramp": 40})).unwrap();
assert_eq!(spec(&s, g).1.ease.ramp, 0.4);
}
#[test]
fn a_blend_without_a_spine_draws_its_steps_where_one_with_a_spine_does() {
let mut s = session();
for orientation in ["page", "path"] {
let spined = make(&mut s, 0.0, json!({"orientation": orientation}));
let bare = make(&mut s, 0.0, json!({"orientation": orientation, "createSpine": "never"}));
let boxes = |g: NodeId| -> Vec<_> { vectorcraft_doc::live::expand_live(&node(&s, g)).iter().map(|n| n.geometric_bounds()).collect() };
assert_eq!(boxes(bare), boxes(spined), "{orientation}");
assert!(boxes(bare).len() >= 3, "the three steps at least");
}
// Easing stored on a blend without a spine (a hand-edited file) leaves its steps evenly spaced.
let bare = make(&mut s, 300.0, json!({"orientation": "path", "createSpine": "never"}));
let even = vectorcraft_doc::live::expand_live(&node(&s, bare));
let mut eased = node(&s, bare);
if let NodeKind::Blend { spec, .. } = &mut eased.kind {
spec.ease = vectorcraft_doc::live::BlendEase { kind: vectorcraft_doc::live::BlendEaseType::In, ramp: 1.0 };
}
let boxes = |v: &[Node]| -> Vec<_> { v.iter().map(|n| n.geometric_bounds()).collect() };
assert_eq!(boxes(&vectorcraft_doc::live::expand_live(&eased)), boxes(&even));
}
#[test]
fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
let mut s = session();
let bare = make(&mut s, 0.0, json!({"createSpine": "never"}));
let spined = make(&mut s, 50.0, json!({}));
let d = &s.doc().unwrap().doc;
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
assert_eq!(&back.layers, &d.layers);
let saved = |g: NodeId| match &back.node(g).unwrap().kind {
NodeKind::Blend { spec, .. } => spec.no_spine,
_ => panic!("not a blend"),
};
assert!(saved(bare) && !saved(spined));
assert_eq!(serde_json::to_value(spec(&s, bare).1).unwrap()["noSpine"], json!(true));
assert!(serde_json::to_value(spec(&s, spined).1).unwrap().get("noSpine").is_none(), "a spine is not written");
let old: BlendSpec = serde_json::from_value(json!({"spacing": {"steps": 4}})).unwrap();
assert!(!old.no_spine, "a blend saved before Create Spine has a spine");
for odd in [json!("yes"), json!(1), json!(null)] {
let v: BlendSpec = serde_json::from_value(json!({"noSpine": odd.clone()})).unwrap_or_else(|e| panic!("{odd}: {e}"));
assert!(!v.no_spine, "{odd}");
}
}
+112
View File
@@ -253,6 +253,118 @@ fn selection_art_is_the_art_new_brush_takes() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only brush.new is an undo step");
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.clone()
}
/// The JSON of object `id`, as `brush.options` params take art.
fn art_json(s: &mut Session, id: NodeId) -> Value {
s.execute("brush.selectionArt", &json!({"ids": [id.0]})).unwrap()["art"].clone()
}
/// `brush.placeArt` places a copy of an art or scatter brush's art centered where it is dropped
/// (by default on the first artboard's center), selected, in one undo step; brushes without art,
/// unknown brushes and a position that is not a number are refused.
#[test]
fn place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped() {
let mut s = session();
let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0);
s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap();
let steps = undo_steps(&s);
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Bar", "x": 100, "y": 80})).unwrap()["id"].as_u64().unwrap());
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(selected(&s), vec![id]);
assert_ne!(id, r, "a copy, not the art the brush was made from");
assert!(close(bounds(&s, id), Rect::new(80.0, 76.0, 120.0, 84.0), 1e-6), "{:?}", bounds(&s, id));
// Without a position: the first artboard's center (the document is 400 × 300).
let scatter = NodeId(s.execute("brush.placeArt", &json!({"name": "Dots"})).unwrap()["id"].as_u64().unwrap());
let c = bounds(&s, scatter).center();
assert!((c.x - 200.0).abs() < 1e-6 && (c.y - 150.0).abs() < 1e-6, "{c:?}");
let steps = undo_steps(&s);
for (p, msg) in [
(json!({"name": "3 pt. Round"}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"),
(json!({"name": "Bristle Round"}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"),
(json!({"name": "Nope"}), "no brush named `Nope`"),
] {
let e = s.execute("brush.placeArt", &p).unwrap_err();
assert!(e.to_string().contains(msg), "{p}: {e}");
}
assert!(s.execute("brush.placeArt", &json!({"name": "Bar", "x": "100"})).is_err());
assert_eq!(undo_steps(&s), steps, "a refused call adds no undo step");
}
/// Brush art holding an instance of a symbol whose art lies away from the symbol's origin (as
/// imported symbols can) is centered by that art, not by the box an instance has without its
/// document.
#[test]
fn placed_art_with_a_symbol_instance_is_centered_by_the_symbols_art() {
let mut s = session();
let r = rect(&mut s, 300.0, 10.0, 100.0, 40.0);
let art = node(&s, r);
s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap();
let st = s.doc_mut().unwrap();
let d = std::sync::Arc::make_mut(&mut st.doc);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) });
let layer = d.layers[0].id;
let inst = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((50.0, 50.0));
d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap();
let inst = inst.0;
s.execute("brush.new", &json!({"type": "art", "name": "Stamp", "ids": [inst]})).unwrap();
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Stamp", "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
let st = s.doc().unwrap();
let b = st.doc.bounds_of(&[id], false).unwrap();
assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 150.0).abs() < 1e-6, "{b:?}");
assert!((b.width() - 100.0).abs() < 1e-6, "{b:?}");
}
/// A pattern brush with side, outer corner and start tiles, the side tile with a repeat frame
/// wider than its art: → its name.
fn framed_pattern_brush(s: &mut Session) -> String {
let side = rect(s, 0.0, 0.0, 20.0, 10.0);
let corner = rect(s, 0.0, 40.0, 10.0, 10.0);
let start = rect(s, 0.0, 80.0, 6.0, 10.0);
let name = s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "ids": [side.0]})).unwrap()["name"].as_str().unwrap().to_string();
let params = json!({
"side": art_json(s, side),
"side_frame": Rect::new(-2.0, 0.0, 22.0, 10.0),
"outer_corner": art_json(s, corner),
"start": art_json(s, start),
});
s.execute("brush.options", &json!({"name": name, "params": params})).unwrap();
name
}
/// `brush.placeArt` lays a pattern brush's tiles out left to right, each in a group named for its
/// tile, with an unpainted rectangle at the back of a tile with a repeat frame marking that frame.
#[test]
fn pattern_brushes_place_their_tiles_in_a_row() {
let mut s = session();
let name = framed_pattern_brush(&mut s);
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
let placed = node(&s, id);
let tiles: Vec<Node> = placed.children().unwrap().iter().map(|c| (**c).clone()).collect();
let names: Vec<&str> = tiles.iter().map(|t| t.name.as_deref().unwrap_or("")).collect();
assert_eq!(names, ["Side Tile", "Outer Corner Tile", "Start Tile"]);
let boxes: Vec<Rect> = tiles.iter().map(|t| t.geometric_bounds().unwrap()).collect();
assert!(boxes.windows(2).all(|w| (w[1].x0 - w[0].x1 - 10.0).abs() < 1e-6), "10 pt apart, left to right: {boxes:?}");
// The side tile: the frame's rectangle, unpainted, behind the art.
let side = tiles[0].children().unwrap();
assert_eq!(side.len(), 2);
let marker = &side[0];
assert!(marker.appearance.items.iter().all(|i| match i {
vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.is_none(),
vectorcraft_doc::AppearanceItem::Stroke(st) => st.paint.is_none(),
}));
let frame = marker.geometric_bounds().unwrap();
assert!((frame.width() - 24.0).abs() < 1e-6 && (frame.height() - 10.0).abs() < 1e-6, "{frame:?}");
assert_eq!(tiles[1].children().unwrap().len(), 1, "no frame, no rectangle");
}
#[test]
fn brush_options_rename_duplicate_and_delete_update_strokes() {
let mut s = session();
+114
View File
@@ -2945,6 +2945,120 @@ fn merged_live_paint_groups_keep_the_bottom_groups_gap_options() {
assert_eq!(merged(off, json!({"detect": false})), GapOptions { detect: false, size: GapSize::Custom(12.0), color: blue });
}
#[test]
fn live_paint_bucket_drag_fills_multiple_faces() {
let mut s = session();
let g = live(&mut s);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0));
let before = s.doc().unwrap().doc.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
// Skip the middle face between pointer events, as can happen in a fast drag.
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
let gn = node(&s, g);
for x in [25.0, 75.0, 125.0] {
let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap();
assert_eq!(f.appearance.fill_paint(), s.paint.fill, "dragged face at {x}");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before, "one Undo restores every face");
s.pointer(&PointerEvent::new(PointerKind::Move, 125.0, 50.0), v).unwrap();
assert!(!s.overlays(v).is_empty(), "hover still highlights a face");
assert_eq!(s.doc().unwrap().doc, before, "hover does not paint");
}
#[test]
fn live_paint_bucket_drag_crosses_thin_grid_cells_and_can_cancel() {
for (deferred, cancel) in [(false, false), (false, true), (true, false)] {
let mut s = session();
let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (50.25, 0.0), (50.25, 100.0))];
s.execute("select.set", &json!({"ids": ids.map(|i| i.0)})).unwrap();
let before = s.doc().unwrap().doc.clone();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.prefs.real_time_drawing = !deferred;
s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0));
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
if cancel {
assert!(s.tool_busy());
assert!(s.tool_claims_key(ToolKey::Escape, v));
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
assert!(!s.tool_claims_key(ToolKey::Escape, v));
}
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
if !cancel {
let g = s.doc().unwrap().selection.objects[0];
let gn = node(&s, g);
for x in [25.0, 50.125, 125.0] {
let f = vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap();
assert_eq!(f.appearance.fill_paint(), s.paint.fill, "deferred={deferred}, x={x}");
}
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(s.doc().unwrap().doc == before, "deferred={deferred}, cancel={cancel}: original paths and selection art must be restored");
}
}
#[test]
fn live_paint_bucket_long_drag_keeps_late_turns_and_release_as_one_undo() {
for cancel in [false, true] {
let mut s = session();
let ids = [rect(&mut s, 0.0, 0.0, 150.0, 100.0), line(&mut s, (50.0, 0.0), (50.0, 100.0)), line(&mut s, (100.0, 0.0), (100.0, 100.0))];
s.execute("select.set", &json!({"ids": ids.map(|id| id.0)})).unwrap();
let before = s.doc().unwrap().doc.clone();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.prefs.real_time_drawing = false;
s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0));
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
for i in 1..4096 {
s.pointer(&PointerEvent::new(PointerKind::Drag, 25.0 + f64::from(i) / 10000.0, 50.0), v).unwrap();
}
// Turn around the middle face after the chunk limit, then enter the right face on Up.
for (x, y) in [(25.0, 150.0), (125.0, 150.0)] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
}
if cancel {
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
if !cancel {
let g = s.doc().unwrap().selection.objects[0];
let gn = node(&s, g);
for x in [25.0, 125.0] {
assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().appearance.fill_paint(), s.paint.fill);
}
assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(75.0, 50.0)).unwrap().appearance.fill_paint(), Paint::solid(Color::WHITE));
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(s.doc().unwrap().doc == before, "long drag is one cancellable undo step");
}
}
#[test]
fn live_paint_bucket_drag_rejects_invalid_points_atomically() {
let mut s = session();
let g = live(&mut s);
let before = s.doc().unwrap().doc.clone();
for points in
[json!([]), json!([[26.0, 50.0]]), json!([[25.0, 50.0], [null, 0]]), json!([[25.0, 50.0], [1e30, 0]]), json!(vec![[25.0, 50.0]; 4097])]
{
assert!(s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": points})).is_err());
assert_eq!(s.doc().unwrap().doc, before);
}
for continuation in [json!(null), json!([[[26.0, 50.0], [125.0, 50.0]]]), json!([vec![[25.0, 50.0]; 4097]])] {
assert!(
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25.0, 50.0], "points": [[25.0, 50.0]], "continuation": continuation}))
.is_err()
);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn live_paint_bucket_tool_fills_face() {
let mut s = session();
+52 -1
View File
@@ -38,7 +38,10 @@ fn built_in_presets_are_the_gradient_libraries_by_theme_with_unique_names() {
// Grouped by library, the gradient libraries first, then the swatch libraries holding gradients.
let mut libraries: Vec<&str> = rows.iter().map(|r| r["library"].as_str().unwrap()).collect();
libraries.dedup();
assert_eq!(libraries, ["Spectrum Gradients", "Sky Gradients", "Neutral Gradients", "Duotone Gradients", "Radial Glows", "Metallic Gradients"]);
assert_eq!(
libraries,
["Spectrum Gradients", "Sky Gradients", "Neutral Gradients", "Organic Fades", "Duotone Gradients", "Radial Glows", "Metallic Gradients"]
);
let mut seen = std::collections::HashSet::new();
assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset");
let vignette = rows.iter().find(|r| r["name"] == "Vignette").unwrap();
@@ -65,6 +68,20 @@ fn applying_a_preset_edits_the_gradient_in_place_as_one_undo_step() {
assert_eq!(paint(&s, id, false), before);
}
#[test]
fn an_organic_fade_applies_with_its_method_midpoints_and_opacities() {
let (mut s, id) = session_with(json!({"color": "#336699"}));
let mist = s.gradient_preset("Mist").unwrap();
assert_eq!((mist.library, mist.gradient.method), (Some("Organic Fades"), GradientMethod::Perceptual));
s.execute("gradient.presets.apply", &json!({"name": "Mist"})).unwrap();
let g = paint(&s, id, false).gradient;
assert_eq!((g.kind, g.method, &g.stops), (GradientKind::Linear, GradientMethod::Perceptual, &mist.gradient.stops));
assert_eq!(s.gradient_preset_name(&g).as_deref(), Some("Mist"));
let list = s.execute("gradient.presets.list", &json!({})).unwrap();
let row = list["presets"].as_array().unwrap().iter().find(|r| r["name"] == "Mist").unwrap().clone();
assert_eq!(row["gradient"]["method"], "perceptual");
}
#[test]
fn a_preset_applies_to_the_stroke_and_to_a_solid_paint() {
let (mut s, id) = session_with(json!({"color": "#336699"}));
@@ -334,3 +351,37 @@ fn saved_presets_round_trip_with_the_preferences() {
fresh.apply_prefs(back);
assert!(fresh.gradient_preset("mine").is_some_and(|e| e.library.is_none()));
}
/// Preferences can hold saved presets named like a built-in preset (saved before it existed) or
/// like each other (edited by hand): applied, each gets a name of its own, any case.
#[test]
fn saved_presets_named_like_a_built_in_or_another_saved_one_get_a_free_name() {
let (mut s, id) = session_with(json!({"gradient": {"kind": "radial"}}));
let mist = s.gradient_preset("Mist").unwrap().gradient;
let mut own = paint(&s, id, false).gradient;
own.dither = true;
let preset = |name: &str| crate::cmd::GradientPreset { name: name.into(), gradient: own.clone() };
let mut prefs = s.prefs.clone();
prefs.gradient_presets =
vec![preset("mist"), preset("Mine"), preset("MINE"), preset("Mist 2"), preset("Plain"), preset("PLAIN"), preset("plain")];
s.apply_prefs(prefs);
let saved: Vec<&str> = s.prefs.gradient_presets.iter().map(|p| p.name.as_str()).collect();
assert_eq!(saved, ["mist 3", "Mine", "MINE 2", "Mist 2", "Plain", "PLAIN 2", "plain 3"]);
let list = s.execute("gradient.presets.list", &json!({})).unwrap();
let mut seen = std::collections::HashSet::new();
assert!(names(&list).iter().all(|n| seen.insert(n.to_lowercase())), "a name names one preset");
// The renamed one applies and deletes; the built-in Mist stays as it was.
s.execute("gradient.presets.apply", &json!({"name": "mist 3"})).unwrap();
assert_eq!(paint(&s, id, false).gradient, own);
assert_eq!(s.gradient_preset("Mist").unwrap().gradient, mist);
assert_eq!(s.execute("gradient.presets.delete", &json!({"name": "Mist 3"})).unwrap()["deleted"], "mist 3");
assert!(s.execute("gradient.presets.delete", &json!({"name": "Mist"})).is_err(), "built in");
assert_eq!(s.prefs.gradient_presets.len(), 6);
// Many presets with one name each get their own number.
let mut prefs = s.prefs.clone();
prefs.gradient_presets = (0..2000).map(|_| preset("Same")).collect();
s.apply_prefs(prefs);
let mut seen = std::collections::HashSet::new();
assert!(s.prefs.gradient_presets.iter().all(|p| seen.insert(p.name.to_lowercase())));
assert_eq!(s.prefs.gradient_presets.last().map(|p| p.name.as_str()), Some("Same 2000"));
}
+67
View File
@@ -1855,6 +1855,38 @@ fn convert_to_artboards_names_by_the_artboards_the_document_has() {
assert_eq!(name_after(&|s| _ = s.execute("edit.undo", &json!({})).unwrap()), "Artboard 3");
}
/// Convert to Artboards on several objects gives each new artboard an id above the ids given out
/// before and the deleted artboard's, and names it one past the highest id the artboards have,
/// counting the artboards it has just added. With an artboard whose id is `u32::MAX` (a damaged
/// file), each new artboard takes the smallest free id and the name stays at `u32::MAX`.
#[test]
fn convert_to_artboards_gives_each_object_the_next_id_and_name() {
let convert = |s: &mut Session| {
let ids: Vec<NodeId> = (0..3).map(|i| rect(s, 3000.0 + 300.0 * f64::from(i), 0.0, 200.0, 100.0)).collect();
sel(s, &ids);
assert_eq!(s.execute("artboard.convertToArtboards", &json!({})).unwrap()["artboards"], 3);
let d = &s.doc().unwrap().doc;
d.artboards.iter().map(|a| (a.id, a.name.clone())).collect::<Vec<_>>()
};
let named = |pairs: &[(u32, &str)]| pairs.iter().map(|&(id, n)| (id, n.to_string())).collect::<Vec<_>>();
// Artboards 1 and 2 are left after artboard 3 is deleted, so its id stays given out.
let mut s = session();
s.execute("artboard.new", &json!({})).unwrap();
s.execute("artboard.new", &json!({})).unwrap();
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
let ids: Vec<u32> = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect();
assert_eq!(ids, [1, 2]);
let got = convert(&mut s);
assert_eq!(got, named(&[(1, "Artboard 1"), (2, "Artboard 2"), (4, "Artboard 3"), (5, "Artboard 5"), (6, "Artboard 6")]));
let mut s = session();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards[0].id = u32::MAX;
let got = convert(&mut s);
let top = format!("Artboard {}", u32::MAX);
assert_eq!(got, named(&[(u32::MAX, "Artboard 1"), (1, &top), (2, &top), (3, &top)]));
}
/// Rearrange All Artboards refuses `columns` that are not a whole number (a fraction, a negative number or a string),
/// and the artboards stay where they were; 1.0, as the Rearrange All Artboards dialog sends a count, is one column.
#[test]
@@ -4457,6 +4489,41 @@ fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on(
assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]);
}
/// The rulers' origin dragged out of their corner snaps as a drawn point does: onto a shape's
/// corner and edge, the artboard's centre, and with Snap to Point along a ruler guide; with
/// nothing on it stays at the pointer. The drag changes nothing, and its guides go when it ends.
#[test]
fn the_ruler_origin_dragged_from_the_corner_snaps_as_a_drawn_point() {
use vectorcraft_geom::Point;
let mut s = session();
rect(&mut s, 100.0, 100.0, 100.0, 100.0);
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
let (n, doc) = (undo_len(&s), s.doc().unwrap().doc.clone());
let v = ViewInfo::default();
let at = |s: &mut Session, x, y| s.ruler_origin_drag(Some(Point::new(x, y)), v).unwrap();
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0), "the corner");
assert!(!s.overlays(v).is_empty(), "the guide showing it");
assert_eq!(at(&mut s, 130.0, 202.0), Point::new(130.0, 200.0), "the bottom edge");
assert_eq!(at(&mut s, 398.0, 301.5), Point::new(400.0, 300.0), "the artboard's centre");
assert_eq!(at(&mut s, 302.0, 50.0).x, 300.0, "along the ruler guide");
assert_eq!(s.ruler_origin_drag(None, v), None, "off the canvas");
assert!(s.overlays(v).is_empty());
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0));
s.end_ruler_origin_drag();
assert!(s.overlays(v).is_empty());
assert_eq!((undo_len(&s), &*s.doc().unwrap().doc), (n, &*doc), "nothing changed");
// Nothing on: it stays at the pointer.
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..v };
assert_eq!(s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), off), Some(Point::new(101.5, 98.5)));
s.end_ruler_origin_drag();
// Snap to Grid: onto a gridline crossing.
let grid = ViewInfo { snap_to_grid: true, ..v };
let p = s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), grid).unwrap();
s.end_ruler_origin_drag();
assert_eq!(p, Point::new(p.x.round(), p.y.round()), "{p:?}");
assert_ne!(p, Point::new(101.5, 98.5));
}
/// Guides saved before guides had layers are put on a layer when the document opens.
#[test]
fn guides_from_older_files_are_put_on_a_layer() {
+97
View File
@@ -280,6 +280,103 @@ fn a_missing_link_is_reported_not_copied() {
assert!(report.contains("blue.png: not found"), "{report}");
}
/// Packaged for a client whose read root holds neither the document's file nor its links: the report,
/// its Document Info part included, names them by their file names, and `document.info` gives no
/// link. The person's report names them whole.
#[test]
fn a_confined_package_names_files_outside_the_read_root_by_name() {
let dir = Folder::new("package-roots");
let mut s = poster(&dir);
std::fs::create_dir_all(dir.file("in")).unwrap();
std::fs::remove_file(dir.file("art/blue.png")).unwrap();
open(&mut s, &dir.file("poster.vectorcraft"));
let report = |r: &Value| {
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap()
};
let person = report(&run(&mut s, "file.package", json!({})));
assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}");
assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}");
assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}");
let in_root = dir.0.join("in");
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
let client = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
let text = report(&client);
assert!(text.contains("From: poster.vectorcraft\n"), "{text}");
assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}");
let base = dir.0.to_string_lossy().into_owned();
assert!(!text.contains(&base), "{text}");
for key in ["missingLinks", "warnings", "files"] {
assert!(!client[key].to_string().contains(&base), "{key}: {client}");
}
// Document Info, whose report the package holds, gives no link either.
for p in [json!({}), json!({"format": "text"})] {
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone()));
assert!(!info.to_string().contains(&base), "{p}: {info}");
}
let info = run(&mut s, "document.info", json!({"format": "text"}));
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
}
/// 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]
fn a_relative_link_inside_the_read_root_keeps_its_path() {
let dir = Folder::new("package-roots-relative");
write(&dir.file("art/near.png"), &png(8, 8, RED));
let mut s = session();
let id = place(&mut s, &dir.file("art/near.png"));
let mut doc = (*s.doc().unwrap().doc).clone();
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
im.link = Some(vectorcraft_doc::LinkInfo::new("art/near.png"));
write(&dir.file("near.vectorcraft"), &vectorcraft_format::save(&doc, false));
// Missing, the link keeps its stored path when the document opens (the package copies the
// image the document holds).
std::fs::remove_file(dir.file("art/near.png")).unwrap();
open(&mut s, &dir.file("near.vectorcraft"));
let roots = crate::file_access::AutomationRoots::new(&[dir.0.as_path()], &[]).unwrap();
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
assert!(text.contains("\nart/near.png → Links/near.png\n"), "{text}");
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({})));
let links: Vec<&Value> = info["images"].as_object().unwrap().values().map(|i| &i["link"]).collect();
assert_eq!(links, [&json!("art/near.png")], "{info}");
let text = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({"format": "text"})));
assert!(text.to_string().contains("art/near.png"), "{text}");
}
/// A link whose stored path names a place outside a confined request's read root, with its file
/// found by name beside the document inside the root: the package report and reply give the file
/// name, not the stored path.
#[test]
fn a_stored_path_outside_the_read_root_is_left_out_when_its_file_is_found_inside() {
let dir = Folder::new("package-roots-stale");
write(&dir.file("in/near.png"), &png(8, 8, RED));
let mut s = session();
let id = place(&mut s, &dir.file("in/near.png"));
let mut doc = (*s.doc().unwrap().doc).clone();
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
let stale = dir.file("out/near.png");
im.link = Some(vectorcraft_doc::LinkInfo::new(&stale));
write(&dir.file("in/near.vectorcraft"), &vectorcraft_format::save(&doc, false));
// Missing when the document opens, the link keeps its stored path; the file then appears beside it.
std::fs::remove_file(dir.file("in/near.png")).unwrap();
open(&mut s, &dir.file("in/near.vectorcraft"));
write(&dir.file("in/near.png"), &png(8, 8, RED));
let in_root = dir.0.join("in");
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
assert!(text.contains("\nnear.png → Links/near.png\n"), "{text}");
assert!(!text.contains(&stale), "{text}");
for key in ["missingLinks", "warnings", "files"] {
assert!(!r[key].to_string().contains(&stale), "{key}: {r}");
}
}
/// A file missing from a document that moved keeps the place its relative path names from the
/// document's folder: the packaged document writes its relative path from there.
#[test]
+304 -5
View File
@@ -1153,6 +1153,98 @@ fn deferred_stages_in_symbol_art_are_listed_and_refreshed() {
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
}
/// `effect.refreshDeferred` takes the id of an object in the art of a symbol, pattern, brush or
/// opacity mask, as `effect.deferredStatus` lists it: one with a deferred stage is refreshed, and
/// one without (or whose stage is gone) adds nothing to the counts. The id of art that is no
/// longer in the document is an error.
#[test]
fn refresh_takes_objects_in_definition_art() {
let mut s = session();
const FX: &str = "plugin.test.engine.deferred.nested";
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.nested", "effect", "{}"), &out));
// A symbol whose art holds an object with the effect and one without.
let staged = rect(&mut s, 10.0, "#ff0000");
let plain = rect(&mut s, 30.0, "#ff0000");
run(&mut s, "effect.apply", json!({"ids": [staged.0], "effect": FX}));
run(&mut s, "select.set", json!({"ids": [staged.0, plain.0]}));
run(&mut s, "symbol.new", json!({"name": "Nested"}));
// A pattern, an art brush (its source deleted) and an opacity mask, none with a stage.
let tile = rect(&mut s, 50.0, "#00ff00");
run(&mut s, "select.set", json!({"ids": [tile.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Tile", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let bar = rect(&mut s, 70.0, "#0000ff");
run(&mut s, "select.set", json!({"ids": [bar.0]}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Bar"}));
run(&mut s, "edit.clear", json!({"ids": [bar.0]}));
let masked = rect(&mut s, 90.0, "#ff0000");
let mask = rect(&mut s, 90.0, "#ffffff");
run(&mut s, "select.set", json!({"ids": [masked.0, mask.0]}));
run(&mut s, "transparency.makeOpacityMask", json!({}));
// A layer object with a stage that stays deferred, and one without.
let kept = rect(&mut s, 130.0, "#ff0000");
run(&mut s, "effect.apply", json!({"ids": [kept.0], "effect": FX}));
let bare = rect(&mut s, 150.0, "#ff0000");
// The ids of the objects of `art` that are not in the layers.
let nested = |s: &Session, art: &vectorcraft_doc::Node| {
let d = &s.doc().unwrap().doc;
let mut ids = Vec::new();
vectorcraft_doc::swatches::walk_with_masks(art, &mut |n| {
if d.node(n.id).is_none() {
ids.push(n.id.0);
}
});
ids
};
let d = s.doc().unwrap().doc.clone();
let in_symbol = nested(&s, &d.symbols[0].art);
let in_pattern = d.patterns.iter().flat_map(|p| p.art.iter().flat_map(|a| nested(&s, a))).collect::<Vec<_>>();
let brushes = vectorcraft_brush::library(&d);
let in_brush = brushes.iter().flat_map(|b| b.art().into_iter().flat_map(|a| nested(&s, a)).collect::<Vec<_>>()).collect::<Vec<_>>();
let in_mask = d.node(masked).and_then(|n| n.extras().mask.as_ref()).map(|m| nested(&s, &m.art)).unwrap_or_default();
for (what, ids) in [("symbol", &in_symbol), ("pattern", &in_pattern), ("brush", &in_brush), ("opacity mask", &in_mask)] {
assert!(!ids.is_empty(), "the {what} art has an object outside the layers");
}
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
fx.view(|| drawn(&s));
fx.first_view_done();
let listed = |s: &mut Session| {
run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::<Vec<_>>()
};
let deferred = listed(&mut s);
let [nested_staged, last] = deferred[..] else { panic!("two stages: {deferred:?}") };
assert!(in_symbol.contains(&nested_staged) && last == kept.0, "{deferred:?} {in_symbol:?}");
let Some(&nested_plain) = in_symbol.iter().find(|i| **i != nested_staged) else { panic!("{in_symbol:?}") };
// Objects without a stage, each on its own and together: nothing to refresh.
let none = json!({"refreshed": 0, "stillDeferred": 0, "failed": 0});
let mut plain_ids = vec![nested_plain, in_pattern[0], in_brush[0], in_mask[0], bare.0];
for id in &plain_ids {
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": id})), none, "object {id}");
}
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), none);
assert_eq!(listed(&mut s), [nested_staged, kept.0]);
// The staged object of the symbol's art, by its id, with the others.
step.store(0, std::sync::atomic::Ordering::Relaxed);
plain_ids.push(nested_staged);
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
assert_eq!(listed(&mut s), [kept.0]);
// Its stage is gone; the object is still there.
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": nested_staged})), none);
// Art no longer in the document, and an id of no object.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).patterns.clear();
assert!(s.execute("effect.refreshDeferred", &json!({"id": in_pattern[0]})).is_err(), "the pattern is gone");
assert!(s.execute("effect.refreshDeferred", &json!({"ids": [nested_plain, 999_999]})).is_err(), "not an object of the document");
assert_eq!(listed(&mut s), [kept.0]);
}
/// `CRAFT_PLUGIN_PAINTS_WASM=<folder>` saves a test live effect to try in the app
/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its
/// object's stroke is 5 pt wide, and hands the geometry back otherwise.
@@ -1820,11 +1912,11 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for
/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load.
/// A grant recorded later counts again, and another store starts with nothing ignored.
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals in
/// the process: both when `grants.json` can't be rewritten and when it can't be read at the load.
/// A grant recorded later counts again, and another store's grant for the id counts.
#[test]
fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-load-forget");
let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other");
@@ -1856,8 +1948,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
next.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
// A load that can rewrite the file forgets the grant, and the store has nothing ignored again.
std::fs::write(&grants, &recorded).unwrap();
next.attach_plugin_store(folder.0.clone());
assert!(!grants.exists(), "the load removes the grant");
// A directory at the file's path gives a read error on every platform.
std::fs::remove_file(&grants).unwrap();
std::fs::create_dir(&grants).unwrap();
vectorcraft_plugins::registry::remove(id);
let mut third = session();
@@ -1883,6 +1979,180 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
run(&mut third, "plugin.remove", json!({"id": id}));
}
/// A grant one session stops counting stops counting for every session in the process attached to
/// the same folder, by any path to it: one attached before, one attached after with no stored module
/// to try the removal for, and one that comes back from another folder. A successful write of the
/// grant in any of them makes it count in all of them again.
#[test]
fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-shared-ignore");
let elsewhere = crate::tests_links::Folder::new("plugin-store-shared-ignore-other");
let id = "test.engine.permissions.sharedignore";
let empty = json!({"objects": []});
let approved = asking(id, r#"["doc.read"]"#, &empty);
let approved_data = vectorcraft_format::base64_encode(&approved);
let plain = asking(id, "null", &empty);
let needs_approval = json!({"dataBase64": approved_data});
let grants = folder.0.join("grants.json");
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
std::fs::write(&grants, &recorded).unwrap();
let mut first = session();
first.attach_plugin_store(folder.0.clone());
let inside = folder.0.join("inside");
std::fs::create_dir(&inside).unwrap();
let mut other = session();
other.attach_plugin_store(inside.join(".."));
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
std::fs::write(&grants, &full).unwrap();
run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
let file = first.stored_plugin_file(id).unwrap();
assert!(!std::path::Path::new(&file).exists(), "the store keeps no module");
assert_eq!(std::fs::read(&grants).unwrap(), full);
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
let refused = other.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
assert!(refused.contains("doc.read"), "{refused}");
std::fs::write(&file, &approved).unwrap();
vectorcraft_plugins::registry::remove(id);
other.load_stored_plugins();
assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded");
std::fs::remove_file(&file).unwrap();
let mut later = session();
later.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it");
std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
other.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
other.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't");
std::fs::write(&grants, &recorded).unwrap();
assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
for s in [&mut first, &mut other, &mut later] {
assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
}
std::fs::remove_file(&grants).unwrap();
}
/// A plug-in folder that doesn't exist yet gets the key it gets once it is made, and every path to a
/// folder gets the same key.
#[test]
fn a_plugin_folder_has_one_key_for_every_path_to_it() {
use crate::store::plugin_store_key;
let folder = crate::tests_links::Folder::new("plugin-store-key");
let dir = folder.0.join("Plug-ins");
let before = plugin_store_key(&dir);
assert_eq!(plugin_store_key(&dir.join("sub").join("..")), before);
assert_eq!(plugin_store_key(&folder.0.join(".").join("Plug-ins")), before);
std::fs::create_dir(&dir).unwrap();
assert_eq!(plugin_store_key(&dir), before, "the key stays when the folder is made");
assert_eq!(plugin_store_key(&dir.join(".")), before);
#[cfg(windows)]
{
let plain = std::path::absolute(&dir).unwrap();
let verbatim = std::path::PathBuf::from(format!(r"\\?\{}", plain.display()));
assert_eq!(plugin_store_key(&verbatim), before, "a verbatim path names the same folder");
}
}
/// Sessions attached to a plug-in folder before it exists, by paths that only name the same folder
/// once it is made, share the grants the process doesn't count for it. A grant that one session
/// writes while another fails to remove it keeps counting.
#[test]
fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-late-folder");
let id = "test.engine.permissions.latefolder";
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
std::fs::create_dir_all(folder.0.join("a").join("b")).unwrap();
let dir = folder.0.join("a").join("Plug-ins");
// On disk `link/..` is `a`, so `link/../Plug-ins` is the folder; by name it is a `Plug-ins` beside `a`.
// On Windows the folder is named in other letter case.
#[cfg(unix)]
let alias = {
std::os::unix::fs::symlink(folder.0.join("a").join("b"), folder.0.join("link")).unwrap();
folder.0.join("link").join("..").join("Plug-ins")
};
#[cfg(windows)]
let alias = folder.0.join("A").join("PLUG-INS");
#[cfg(not(any(unix, windows)))]
let alias = dir.clone();
let mut first = session();
first.attach_plugin_store(dir.clone());
let mut other = session();
other.attach_plugin_store(alias);
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
first.ignore_stored_grant(id, first.grant_writes());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
assert!(other.store_grant(id, Some(serde_json::from_value(entry.clone()).unwrap())), "the file can be written");
assert_eq!(run(&mut first, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
// A write that fails in one session while another writes the grant for the id leaves the grant
// counting.
let before = first.grant_writes();
assert!(other.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the other session writes the grant");
first.ignore_stored_grant(id, before);
assert_eq!(run(&mut first, "plugin.inspect", needs_approval)["needsApproval"], false, "the written grant counts");
std::fs::remove_file(dir.join("grants.json")).unwrap();
}
/// Grant writes that change nothing, each for another id, don't grow what the process keeps past its
/// limit.
#[test]
fn the_process_keeps_a_bounded_number_of_grant_writes() {
let folder = crate::tests_links::Folder::new("plugin-store-writes-kept");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
for n in 0..300 {
assert!(s.store_grant(&format!("test.engine.permissions.unknown{n}"), None), "nothing to remove is a success");
}
assert!(Session::grant_writes_kept() <= 256, "{}", Session::grant_writes_kept());
}
/// A session attached by a link to a plug-in folder matches the grants the process doesn't count
/// with the folder the link leads to now, not the one it led to when the session was attached.
#[cfg(unix)]
#[test]
fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-relinked");
let id = "test.engine.permissions.relinked";
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins"));
for dir in [&old, &new] {
std::fs::create_dir(dir).unwrap();
std::fs::write(dir.join("grants.json"), &recorded).unwrap();
}
std::os::unix::fs::symlink(&old, &link).unwrap();
let mut linked = session();
linked.attach_plugin_store(link.clone());
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&new, &link).unwrap();
let mut direct = session();
direct.attach_plugin_store(new.clone());
direct.ignore_stored_grant(id, direct.grant_writes());
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the link leads to the ignored grant");
assert!(linked.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
assert_eq!(run(&mut direct, "plugin.inspect", needs_approval)["needsApproval"], false, "it counts again");
}
/// A grants file that can't be opened or read may name the old module once it reads again, so
/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the
/// file's path gives a read error on every platform.
@@ -2123,6 +2393,35 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module
/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant
/// still covers, and the grant is left as it was.
#[test]
fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() {
let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants");
let id = "test.engine.permissions.undeletablegrants";
let empty = json!({"objects": []});
let approved = asking(id, r#"["doc.read"]"#, &empty);
let approved_data = vectorcraft_format::base64_encode(&approved);
let plain = asking(id, "null", &empty);
let grants = folder.0.join("grants.json");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
let file = s.stored_plugin_file(id).unwrap();
let recorded = std::fs::read(&grants).unwrap();
crate::store::GRANTS_DELETE_FAILS.set(true);
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
crate::store::GRANTS_DELETE_FAILS.set(false);
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was");
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module");
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(!grants.exists(), "a removal that can delete the file forgets the grant");
}
/// A plug-in folder that leaves a module listing no permissions under an id forgets the process's
/// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in
/// the plug-in store stays, with the stored module it covers.
+107
View File
@@ -0,0 +1,107 @@
//! The preferences commands under automation roots: a confined request sees a folder preference and
//! an export preset's folder only inside its read roots.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::cmd::fileio::ScreenExportPreset;
use crate::file_access::{AutomationRoots, confine};
use crate::*;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
fn text(p: &Path) -> String {
p.to_string_lossy().to_string()
}
/// A fresh scratch folder for one test, with the folders `in` and `out`.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-prefs-roots-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for sub in ["in", "out"] {
std::fs::create_dir_all(dir.join(sub)).unwrap();
}
dir
}
/// The folder preferences that name the folder outside the read root.
const OUTSIDE: [&str; 3] = ["pluginsFolder", "scratchPrimary", "templatesFolder"];
/// A session whose folder preferences name `inside` (fonts, and the Data Recovery folder with
/// spaces around it) and `outside` (the [`OUTSIDE`] ones, the Templates folder with spaces around
/// it), with a scratch disk choice and an export preset kept with each folder.
fn session(inside: &str, outside: &str) -> Session {
let mut s = Session::new();
s.prefs.fonts_folder = inside.to_string();
s.prefs.recovery_folder = format!(" {inside} ");
s.prefs.plugins_folder = outside.to_string();
s.prefs.scratch_primary = outside.to_string();
s.prefs.scratch_secondary = "None".to_string();
s.prefs.templates_folder = format!(" {outside} ");
for (name, folder) in [("Inside", inside), ("Outside", outside)] {
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
s.prefs.screen_export_presets.push(ScreenExportPreset { name: name.into(), settings: settings.as_object().cloned().unwrap_or_default() });
}
s
}
/// Does a string anywhere in `v` hold `path`?
fn holds(v: &Value, path: &str) -> bool {
v.to_string().contains(&path.replace('\\', "\\\\"))
}
#[test]
fn prefs_commands_leave_out_folders_outside_the_read_root() {
let base = folder("get");
let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out")));
let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
let mut s = session(&inside, &outside);
let all = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({})));
let prefs = &all["prefs"];
assert_eq!(prefs["fontsFolder"], json!(inside), "a folder inside the root is shown");
assert_eq!(prefs["recoveryFolder"], json!(format!(" {inside} ")), "checked without the spaces, shown as kept");
assert_eq!(prefs["scratchSecondary"], json!("None"), "a scratch disk choice is shown");
for key in OUTSIDE {
assert_eq!(prefs[key], Value::Null, "{key}: {all}");
}
let presets = prefs["screenExportPresets"].as_array().unwrap();
assert_eq!(presets[0]["settings"]["folder"], json!(inside));
assert_eq!(presets[1]["name"], json!("Outside"), "the preset stays");
assert!(presets[1]["settings"].get("folder").is_none(), "{all}");
assert!(!holds(&all, &outside), "{all}");
for key in OUTSIDE {
let one = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": key})));
assert_eq!(one, Value::Null, "{key}");
}
assert_eq!(confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": "fontsFolder"}))), json!(inside));
let list = confine(roots.as_ref(), || run(&mut s, "prefs.list", json!({})));
assert!(!holds(&list, &outside), "{list}");
let row = |key: &str| list.as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap();
assert_eq!(row("fontsFolder")["value"], json!(inside));
assert_eq!(row("pluginsFolder")["value"], Value::Null);
assert_eq!(row("pluginsFolder")["kind"], json!("text"), "the row stays");
// A request that sets another preference, or resets a category without folders.
let set = confine(roots.as_ref(), || run(&mut s, "prefs.set", json!({"values": {"keyboardIncrement": 2, "pluginsFolder": outside}})));
assert_eq!(set, json!({"keyboardIncrement": 2.0, "pluginsFolder": null}), "a folder kept as it was is left out too");
let reset = confine(roots.as_ref(), || run(&mut s, "prefs.reset", json!({"category": "General"})));
assert!(!holds(&reset, &outside), "{reset}");
assert_eq!(reset["prefs"]["fontsFolder"], json!(inside));
// Unconfined and with only a write root.
let all = run(&mut s, "prefs.get", json!({}));
assert_eq!(all["prefs"]["pluginsFolder"], json!(outside), "unconfined, the folder is shown");
assert_eq!(all["prefs"]["screenExportPresets"][1]["settings"]["folder"], json!(outside));
let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap();
let all = confine(write_only.as_ref(), || run(&mut s, "prefs.get", json!({})));
assert_eq!(all["prefs"]["fontsFolder"], Value::Null, "without a read root no folder is shown");
assert_eq!(all["prefs"]["recoveryFolder"], Value::Null);
assert_eq!(s.prefs.plugins_folder, outside, "the preferences are unchanged");
let _ = std::fs::remove_dir_all(&base);
}
+436
View File
@@ -483,6 +483,105 @@ fn the_folder_store_reads_no_linked_entries() {
let _ = std::fs::remove_dir_all(&base);
}
/// A file where a folder of the store's path should be: the error names that file, not the area
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
/// save.
#[cfg(unix)]
#[test]
fn folder_errors_name_a_file_in_the_way() {
let base = std::env::temp_dir().join(format!("vc-recovery-file-in-way-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let file = base.join("file");
std::fs::write(&file, b"").unwrap();
let folder = file.join("recovery");
let store = FolderStore::new(&folder);
let mut s = Session::new();
s.prefs.recovery_folder = folder.to_string_lossy().to_string();
s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
let errors = [
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err()),
("lock", store.lock("1-2").err()),
("read", store.read("1-1/Untitled-1-1.vectorcraft").err()),
("list", store.list().err()),
("remove", store.remove("1-1/Untitled-1-1.vectorcraft").err()),
("save", s.execute("file.recovery.save", &json!({})).err().map(|e| e.to_string())),
];
let _ = std::fs::remove_dir_all(&base);
let named = format!("{} is not a folder: ", file.display());
let wrong: Vec<_> = errors.iter().filter(|(_, e)| !e.as_deref().is_some_and(|e| e.contains(&named))).collect();
assert!(wrong.is_empty(), "{wrong:?}");
}
/// A removal that finds the copy missing because a file is on the way to it (how Windows reports a
/// file in the way) names that file. A copy that is just not there still counts as removed.
#[test]
fn a_removal_reported_missing_names_a_file_in_the_way() {
let base = std::env::temp_dir().join(format!("vc-recovery-remove-in-way-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let file = base.join("file");
std::fs::write(&file, b"").unwrap();
let missing = || std::io::Error::from(std::io::ErrorKind::NotFound);
let behind = FolderStore::removed(&file.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
let gone = FolderStore::removed(&base.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
let _ = std::fs::remove_dir_all(&base);
let named = format!("{} is not a folder: ", file.display());
assert!(behind.as_ref().is_err_and(|e| e.starts_with(&named)), "{behind:?}");
assert_eq!(gone, Ok(()));
}
/// A folder of the store's path that is missing and can't be made: a write or a lock names it as
/// the folder it couldn't make, and a read names it as missing. An area folder that can't be made
/// in a store folder that is there is named the same way.
#[cfg(unix)]
#[test]
fn folder_errors_name_a_missing_folder_that_cannot_be_made() {
use std::os::unix::fs::PermissionsExt as _;
let base = std::env::temp_dir().join(format!("vc-recovery-missing-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let closed = base.join("closed");
std::fs::create_dir_all(&closed).unwrap();
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o500)).unwrap();
let gone = closed.join("gone");
let store = FolderStore::new(gone.join("recovery"));
let unmade = format!("couldn't make {}: ", gone.display());
let area = FolderStore::new(&closed).write("1-1/Untitled-1-1.vectorcraft", b"copy").err();
let errors = [
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err(), unmade.clone()),
("lock", store.lock("1-2").err(), unmade),
("read", store.read("1-1/Untitled-1-1.vectorcraft").err(), format!("{} is missing", gone.display())),
("area", area, format!("couldn't make {}: ", closed.join("1-1").display())),
];
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap();
let _ = std::fs::remove_dir_all(&base);
// An account that can write anywhere (root) makes the folders, so the test has nothing to check.
if errors[0].1.is_none() {
return;
}
let wrong: Vec<_> = errors.iter().filter(|(_, e, named)| !e.as_deref().is_some_and(|e| e.starts_with(named.as_str()))).collect();
assert!(wrong.is_empty(), "{wrong:?}");
}
/// When every folder on the way is there, an error names the folder it happened on.
#[cfg(unix)]
#[test]
fn folder_errors_name_the_folder_when_every_folder_is_there() {
use std::os::unix::fs::PermissionsExt as _;
let base = std::env::temp_dir().join(format!("vc-recovery-unreadable-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let unreadable = base.join("unreadable");
std::fs::create_dir_all(&unreadable).unwrap();
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o300)).unwrap();
let listed = FolderStore::new(&unreadable).list();
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o700)).unwrap();
let _ = std::fs::remove_dir_all(&base);
// An account that can read any folder (root) lists it, so the test has nothing to check.
let Err(err) = listed else { return };
assert!(err.starts_with(&format!("{}: ", unreadable.display())), "{err}");
}
/// A store in memory that notes each removal of an area (its lock file and folder, then its empty
/// folder) and whether the area was still held then.
#[derive(Default)]
@@ -682,6 +781,343 @@ fn a_recovery_save_takes_the_next_area_when_the_first_is_tidied_away() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A session keeping its copies in folder `dir`, with one modified document whose copy is written.
fn saved_in(dir: &std::path::Path) -> (Session, String) {
let mut s = Session::new();
s.prefs.recovery_folder = dir.to_string_lossy().to_string();
s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
s.execute("file.recovery.save", &json!({})).unwrap();
let area = s.recovery.own_area().unwrap().to_string();
(s, area)
}
/// A new app over folder `dir`, with nothing open.
#[cfg(unix)]
fn other_app(dir: &std::path::Path) -> Session {
let mut s = Session::new();
s.prefs.recovery_folder = dir.to_string_lossy().to_string();
s
}
/// The area's lock file was removed while its app runs: the next recovery save locks the area
/// again, so another app neither offers nor discards its copy.
#[cfg(unix)]
#[test]
fn a_recovery_save_locks_the_area_again_when_its_lock_file_was_removed() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-relock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
a.execute("file.recovery.save", &json!({})).unwrap();
assert_eq!(a.recovery.own_area(), Some(area.as_str()));
let mut b = other_app(&dir);
assert!(offered(&mut b).is_empty());
assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty());
assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file());
assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy)));
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// The whole area was removed while its app runs: the next recovery save makes it again, locked,
/// with the copy written again.
#[cfg(unix)]
#[test]
fn a_recovery_save_makes_the_area_again_when_it_was_removed() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-remade-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_dir_all(dir.join(&area)).unwrap();
let r = a.execute("file.recovery.save", &json!({})).unwrap();
assert_eq!(r["saved"][0]["file"], format!("{area}/Untitled-1-1").as_str(), "{r}");
assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file());
assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy)));
assert!(offered(&mut other_app(&dir)).is_empty());
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// Another app locked the area after its lock file was removed: the next heartbeat takes a new
/// area, and the document is to be copied again there. Its copy in the old area stays until then.
#[cfg(unix)]
#[test]
fn an_area_another_app_locked_meanwhile_is_left_for_a_new_one() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-moved-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let store = FolderStore::new(&dir);
let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") };
let uid = a.doc().unwrap().uid;
assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]);
let mine = a.recovery.own_area().unwrap().to_string();
assert_ne!(mine, area);
assert!(a.doc().unwrap().recovery.is_none());
assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file(), "kept until the new copy is written");
let r = a.execute("file.recovery.save", &json!({})).unwrap();
assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}");
assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists(), "the copy left there goes");
assert!(matches!(store.lock(&mine), Ok(Lock::Busy)));
drop(other);
assert!(offered(&mut other_app(&dir)).is_empty());
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy written in the background into the area the session left meanwhile is not the
/// document's copy: it stays only until the document is copied again in the new area.
#[cfg(unix)]
#[test]
fn a_copy_written_into_an_area_left_meanwhile_goes_once_copied_again() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-inflight-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap();
let store: Arc<dyn RecoveryStore> = Arc::new(FolderStore::new(&dir));
let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap();
assert_eq!(jobs.len(), 1);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = store.lock(&area) else { panic!("the other app locks the area") };
cmd::recovery::heartbeat(&mut a);
for j in jobs {
j.write().unwrap();
j.finish(&mut a);
}
assert!(a.doc().unwrap().recovery.is_none());
assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file());
let uid = a.doc().unwrap().uid;
assert_eq!(cmd::recovery::heartbeat(&mut a), [uid], "the next heartbeat has it copied again");
let r = a.execute("file.recovery.save", &json!({})).unwrap();
assert_eq!(r["saved"].as_array().unwrap().len(), 1, "{r}");
assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists());
assert!(cmd::recovery::heartbeat(&mut a).is_empty());
drop(other);
assert!(offered(&mut other_app(&dir)).is_empty());
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// Another app locked the area meanwhile and the document is unchanged since its copy: the next
/// recovery save still writes the copy, in the new area.
#[cfg(unix)]
#[test]
fn a_recovery_save_copies_unchanged_documents_into_the_new_area() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-unchanged-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") };
let r = a.execute("file.recovery.save", &json!({})).unwrap();
let mine = a.recovery.own_area().unwrap().to_string();
assert_ne!(mine, area);
assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}");
assert!(dir.join(&mine).join("Untitled-1-1.vectorcraft").is_file());
assert!(!dir.join(&area).join("Untitled-1-1.vectorcraft").exists());
drop(other);
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy left in an area the session had to leave goes at once when its document is saved,
/// reverted or closed, and every one goes when the app quits with nothing unsaved.
#[cfg(unix)]
#[test]
fn copies_left_behind_go_when_their_document_is_saved_reverted_or_closed() {
use cmd::recovery::Lock;
let base = std::env::temp_dir().join(format!("vc-recovery-leftgo-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let dir = base.join("recovery");
let path = base.join("doc.vectorcraft").to_string_lossy().to_string();
let left = |area: &str| std::fs::read_dir(dir.join(area)).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "vectorcraft"));
for how in ["save", "revert", "close", "quit"] {
let (mut a, _) = saved_in(&dir);
a.execute("document.save", &json!({"path": path})).unwrap();
a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap();
a.execute("file.recovery.save", &json!({})).unwrap();
let area = a.recovery.own_area().unwrap().to_string();
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") };
cmd::recovery::heartbeat(&mut a);
assert!(left(&area), "{how}");
match how {
"save" => a.execute("document.save", &json!({"path": path})).map(drop).unwrap(),
"revert" => a.execute("file.revert", &json!({})).map(drop).unwrap(),
"close" => a.execute("file.close", &json!({})).map(drop).unwrap(),
_ => cmd::recovery::forget_all(&mut a),
}
assert!(!left(&area), "{how}");
drop(other);
drop(a);
}
let _ = std::fs::remove_dir_all(&base);
}
/// The lock file was removed: the next heartbeat locks the area again, before any recovery save.
#[cfg(unix)]
#[test]
fn a_heartbeat_locks_the_area_again_when_its_lock_file_was_removed() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-beatlock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "the copy is still there");
assert_eq!(a.recovery.own_area(), Some(area.as_str()));
assert!(matches!(FolderStore::new(&dir).lock(&area), Ok(Lock::Busy)));
assert!(offered(&mut other_app(&dir)).is_empty());
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// The lock file was removed and can't be made again (the area folder can't be written to now):
/// the session takes a new area and writes its copy there.
#[cfg(unix)]
#[test]
fn an_area_whose_lock_file_cannot_be_made_again_is_left_for_a_new_one() {
use std::os::unix::fs::PermissionsExt as _;
use cmd::recovery::Lock;
// Permissions don't stop the superuser.
if rustix::process::geteuid().is_root() {
return;
}
let dir = std::env::temp_dir().join(format!("vc-recovery-readonly-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap();
let r = a.execute("file.recovery.save", &json!({})).unwrap();
let mine = a.recovery.own_area().unwrap().to_string();
assert_ne!(mine, area);
assert_eq!(r["saved"][0]["file"], format!("{mine}/Untitled-1-1").as_str(), "{r}");
assert!(matches!(FolderStore::new(&dir).lock(&mine), Ok(Lock::Busy)));
std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap();
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// A copy left behind that can't be removed when its document is saved (its area can't be written
/// to now) stays the session's own: it isn't offered here, and a later heartbeat removes it.
#[cfg(unix)]
#[test]
fn a_copy_left_behind_that_cannot_be_removed_yet_stays_the_sessions_own() {
use std::os::unix::fs::PermissionsExt as _;
use cmd::recovery::Lock;
// Permissions don't stop the superuser.
if rustix::process::geteuid().is_root() {
return;
}
let base = std::env::temp_dir().join(format!("vc-recovery-leftstuck-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let dir = base.join("recovery");
let path = base.join("doc.vectorcraft").to_string_lossy().to_string();
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") };
cmd::recovery::heartbeat(&mut a);
std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o500)).unwrap();
a.execute("document.save", &json!({"path": path})).unwrap();
std::fs::set_permissions(dir.join(&area), std::fs::Permissions::from_mode(0o700)).unwrap();
let copy = dir.join(&area).join("Untitled-1-1.vectorcraft");
assert!(copy.is_file());
drop(other);
assert!(offered(&mut a).is_empty());
cmd::recovery::heartbeat(&mut a);
assert!(!copy.exists());
drop(a);
let _ = std::fs::remove_dir_all(&base);
}
/// A copy left in an area the session had to leave is still the session's own after the app that
/// locked that area is gone: the session neither offers nor discards it.
#[cfg(unix)]
#[test]
fn a_copy_left_behind_is_not_offered_by_its_own_app() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-leftmine-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (mut a, area) = saved_in(&dir);
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") };
cmd::recovery::heartbeat(&mut a);
drop(other);
assert!(offered(&mut a).is_empty());
let r = a.execute("file.recovery.discard", &json!({})).unwrap();
assert!(r["discarded"].as_array().unwrap().is_empty(), "{r}");
assert!(a.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err());
assert!(dir.join(&area).join("Untitled-1-1.vectorcraft").is_file());
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// A complex document (Data Recovery off for those) gets no new copy after the session left its
/// area: it keeps the copy it left there, and the heartbeat asks for it only once.
#[cfg(unix)]
#[test]
fn a_complex_documents_copy_left_behind_is_asked_for_once() {
use cmd::recovery::Lock;
let dir = std::env::temp_dir().join(format!("vc-recovery-leftcomplex-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut a = other_app(&dir);
let mut d = vectorcraft_doc::Document::new(1000.0, 1000.0);
let layer = d.layers[0].id;
for i in 0..cmd::recovery::COMPLEX_OBJECTS {
let id = d.alloc_id();
let r = vectorcraft_geom::Rect::new((i % 200) as f64, (i / 200) as f64, (i % 200) as f64 + 1.0, (i / 200) as f64 + 1.0);
let n = vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art());
d.insert(Some(layer), i, n).unwrap();
}
a.add_document(d, None);
a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
let r = a.execute("file.recovery.save", &json!({})).unwrap();
let copy = r["saved"][0]["file"].as_str().unwrap().to_string();
let area = a.recovery.own_area().unwrap().to_string();
a.prefs.recovery_off_for_complex = true;
std::fs::remove_file(dir.join(&area).join(".lock")).unwrap();
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(&area) else { panic!("the other app locks the area") };
let uid = a.doc().unwrap().uid;
assert_eq!(cmd::recovery::heartbeat(&mut a), [uid]);
let r = a.execute("file.recovery.save", &json!({})).unwrap();
assert!(r["saved"].as_array().unwrap().is_empty(), "{r}");
assert!(cmd::recovery::heartbeat(&mut a).is_empty(), "asked for once");
assert!(dir.join(format!("{copy}.vectorcraft")).is_file(), "its copy stays");
drop(other);
drop(a);
let _ = std::fs::remove_dir_all(&dir);
}
/// The preference named another folder while a copy was written in the background: the copy goes
/// from the folder it was written to, and the document keeps its copy in the new folder.
#[test]
fn a_copy_finished_after_the_folder_changed_goes_from_its_own_folder() {
let base = std::env::temp_dir().join(format!("vc-recovery-refolder-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (old, new) = (base.join("old"), base.join("new"));
let (mut a, area) = saved_in(&old);
a.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap();
let store: Arc<dyn RecoveryStore> = Arc::new(FolderStore::new(&old));
let (jobs, _) = cmd::recovery::jobs(&mut a, &store).unwrap();
a.prefs.recovery_folder = new.to_string_lossy().to_string();
a.execute("file.recovery.save", &json!({})).unwrap();
let mine = a.doc().unwrap().recovery.as_ref().unwrap().file.clone();
for j in jobs {
j.write().unwrap();
j.finish(&mut a);
}
assert!(!old.join(&area).join("Untitled-1-1.vectorcraft").exists());
assert_eq!(a.doc().unwrap().recovery.as_ref().unwrap().file, mine);
assert!(new.join(format!("{mine}.vectorcraft")).is_file());
drop(a);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn saving_reverting_or_closing_removes_the_copy() {
let dir = std::env::temp_dir().join(format!("vc-recovery-save-{}", std::process::id()));
+141 -9
View File
@@ -40,6 +40,50 @@ fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.node_count()
}
/// A client confined by automation roots: a save without a path writes the document's own file, and
/// when that file is outside the read roots the reply leaves out its `path` and names the files
/// written beside it by their file names. A reply without a path leaves out a suggested `folder`
/// outside them. A path inside the read roots, and one the client gives, stay whole.
#[test]
fn a_confined_save_leaves_out_paths_outside_the_read_root() {
use crate::file_access::{AutomationRoots, confine};
let d = dir("roots");
let (inside, outside) = (d.join("in"), d.join("out"));
for f in [&inside, &outside] {
std::fs::create_dir_all(f).unwrap();
}
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
rect(&mut s);
let own = path(&outside, "doc.vectorcraft");
s.execute("document.save", &json!({"path": own})).unwrap();
let person = s.execute("document.save", &json!({"separateArtboards": true})).unwrap();
let files: Vec<String> = person["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert_eq!((files.len(), files[0].as_str()), (3, own.as_str()), "{person}");
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, id: &str, p: Value| {
confine(roots.as_ref(), || s.execute(id, &p)).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
};
let hidden = outside.to_string_lossy().into_owned();
let r = run(&mut s, &write_only, "document.save", json!({}));
assert!(r.get("path").is_none() && r["bytes"].as_u64().is_some_and(|n| n > 0), "{r}");
assert!(!r.to_string().contains(&hidden), "{r}");
let r = run(&mut s, &write_only, "document.save", json!({"separateArtboards": true}));
let names: Vec<Value> = files.iter().map(|f| json!(std::path::Path::new(f).file_name().unwrap().to_string_lossy())).collect();
assert_eq!((r.get("path"), r["files"].as_array()), (None, Some(&names)), "{r}");
// Inside the read roots, or given by the client: whole.
assert_eq!(run(&mut s, &both, "document.save", json!({}))["path"], json!(own));
assert_eq!(run(&mut s, &write_only, "document.save", json!({"path": own}))["path"], json!(own));
// A save without a path known suggests the document's folder.
let r = run(&mut s, &write_only, "file.saveCopy", json!({}));
assert!(r.get("folder").is_none() && r["name"] == "doc copy.vectorcraft" && r.get("dataBase64").is_some(), "{r}");
assert_eq!(run(&mut s, &both, "file.saveCopy", json!({}))["folder"], json!(hidden));
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn an_svg_path_writes_svg_and_save_writes_it_back() {
let d = dir("svg");
@@ -425,8 +469,16 @@ fn transparency_grid_round_trips_without_dirtying() {
let _ = std::fs::remove_dir_all(d);
}
/// The `%%BoundingBox` of an EPS file's PostScript.
fn bounding_box(eps: &[u8]) -> [i64; 4] {
let ps = std::str::from_utf8(vectorcraft_eps::sections(eps).unwrap().0).unwrap();
let line = ps.lines().find_map(|l| l.strip_prefix("%%BoundingBox:")).expect("a bounding box");
let v: Vec<i64> = line.split_whitespace().map(|n| n.parse().unwrap()).collect();
[v[0], v[1], v[2], v[3]]
}
#[test]
fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() {
fn opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page() {
let d = dir("eps-original-format");
let eps_path = path(&d, "Artwork.eps");
// Original, contributor-authored PostScript: the artwork occupies only part of the page.
@@ -440,11 +492,16 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() {
assert_eq!((board.width(), board.height()), (200.0, 100.0));
rect(&mut s);
let edited_layers = s.doc().unwrap().doc.layers.clone();
let r = s.execute("document.save", &json!({"options": {"previewFormat": "none", "thumbnails": false}})).unwrap();
// Without Use Artboards the bounding box fits the art, as Export draws it; the editing data
// keeps the page.
let quiet = json!({"previewFormat": "none", "thumbnails": false});
let r = s.execute("document.save", &json!({"options": quiet})).unwrap();
assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(eps_path.as_str()), Some("eps")));
let bytes = std::fs::read(&eps_path).unwrap();
assert!(bytes.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"));
assert!(std::str::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0).unwrap().contains("%%BoundingBox: 0 0 200 100"));
let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap());
assert_eq!(bounding_box(&bytes), bounding_box(&exported));
assert_ne!(bounding_box(&bytes), [0, 0, 200, 100], "the art does not fill the page");
let editing = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(editing.artboards[0].rect, board);
assert_eq!(editing.layers, edited_layers);
@@ -453,26 +510,101 @@ fn opened_eps_saves_to_its_own_file_with_editable_data_and_page_margins() {
assert_eq!(opened["restored"], true);
assert_eq!(s.doc().unwrap().doc.layers, edited_layers);
assert_eq!(s.doc().unwrap().doc.artboards[0].rect, board);
// Use Artboards keeps the opened file's page.
rect(&mut s);
s.execute("document.save", &json!({"options": {"useArtboards": true, "previewFormat": "none", "thumbnails": false}})).unwrap();
assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str()));
assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]);
// Save remembers it.
rect(&mut s);
s.execute("document.save", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().path.as_deref(), Some(eps_path.as_str()));
assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_save_keeps_all_editing_artboards_while_printing_one_page() {
fn eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": -50, "y": 20, "width": 300, "height": 40})).unwrap();
let quiet = json!({"previewFormat": "none", "thumbnails": false});
let r = s.execute("document.save", &json!({"format": "eps", "options": quiet})).unwrap();
let [x0, y0, x1, y1] = bounding_box(&b64(&r));
assert!(x0 <= -50 && x1 >= 250 && y0 >= 0 && y1 <= 100, "{:?}", [x0, y0, x1, y1]);
for (use_artboards, expected) in [(false, [x0, y0, x1, y1]), (true, [0, 0, 200, 100])] {
let options = json!({"useArtboards": use_artboards, "previewFormat": "none", "thumbnails": false});
let r = s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap();
assert_eq!(bounding_box(&b64(&r)), expected, "useArtboards: {use_artboards}");
}
}
#[test]
fn eps_save_keeps_all_editing_artboards_in_the_file_of_one_page() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
rect(&mut s);
let r = s.execute("document.save", &json!({"format": "eps", "artboard": 1, "previewFormat": "none", "thumbnails": false})).unwrap();
let bytes = b64(&r);
assert!(r.get("files").is_none(), "{r}");
let board = s.doc().unwrap().doc.artboards[1].rect;
let [x0, y0, x1, y1] = bounding_box(&bytes);
assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.width(), board.height()));
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(native.artboards.len(), 2);
assert_eq!(native.layers, s.doc().unwrap().doc.layers);
assert!(s.execute("document.save", &json!({"format": "eps", "range": "all"})).is_err(), "EPS is one printed page");
for options in [json!({"useArtboards": false}), json!({"selectedOnly": true})] {
assert!(s.execute("document.save", &json!({"format": "eps", "options": options})).is_err(), "cropping is Export's job");
assert!(s.execute("document.save", &json!({"format": "eps", "options": {"selectedOnly": true}})).is_err(), "selected-only is Export's job");
}
#[test]
fn eps_save_with_use_artboards_and_a_named_artboard_reports_it_as_the_range() {
let d = dir("eps-named-artboard");
let eps_path = path(&d, "Art.eps");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
rect(&mut s);
let options = json!({"useArtboards": true, "artboard": 1, "previewFormat": "none", "thumbnails": false});
s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap();
let o = s.execute("file.formatOptions", &json!({})).unwrap();
assert_eq!(o["options"]["useArtboards"]["value"], true);
assert_eq!(o["options"]["range"]["value"], "2", "the saved artboard, not All");
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard() {
let d = dir("eps-artboards");
let eps_path = path(&d, "Art.eps");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
rect(&mut s);
let options = json!({"useArtboards": true, "previewFormat": "none", "thumbnails": false});
let r = s.execute("document.save", &json!({"path": eps_path, "options": options})).unwrap();
let files: Vec<String> = r["files"].as_array().expect("files").iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert_eq!(files.len(), 3, "{r}");
assert_eq!(files[0], eps_path, "the file the document becomes comes first");
assert!(files[1..].iter().all(|f| f.starts_with(&path(&d, "Art_")) && f.ends_with(".eps")), "{files:?}");
// The central file: the visible art and the whole document.
let central = std::fs::read(&eps_path).unwrap();
let exported = b64(&s.execute("document.export", &json!({"format": "eps", "previewFormat": "none", "thumbnails": false})).unwrap());
assert_eq!(bounding_box(&central), bounding_box(&exported));
assert_eq!(vectorcraft_format::load(&vectorcraft_eps::native(&central).unwrap()).unwrap().artboards.len(), 2);
// Each artboard's file: its artboard as the page, holding that artboard.
let boards = s.doc().unwrap().doc.artboards.clone();
for (f, board) in files[1..].iter().zip(&boards) {
let bytes = std::fs::read(f).unwrap();
let [x0, y0, x1, y1] = bounding_box(&bytes);
assert_eq!(((x1 - x0) as f64, (y1 - y0) as f64), (board.rect.width(), board.rect.height()), "{f}");
let native = vectorcraft_format::load(&vectorcraft_eps::native(&bytes).unwrap()).unwrap();
assert_eq!(native.artboards.iter().map(|a| a.rect).collect::<Vec<_>>(), [board.rect], "{f}");
}
let st = s.doc().unwrap();
assert_eq!((st.path.as_deref(), st.is_dirty()), (Some(eps_path.as_str()), false));
// With no visible art the central file is still written, on the first artboard.
s.execute("select.all", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
std::fs::remove_file(&eps_path).unwrap();
s.execute("document.save", &json!({})).unwrap();
assert_eq!(bounding_box(&std::fs::read(&eps_path).unwrap()), [0, 0, 200, 100]);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
@@ -550,7 +682,7 @@ fn eps_save_bounds_large_page_preview_without_cropping_vector_or_editing_data()
s.execute("file.new", &json!({"width": 4000, "height": 4000})).unwrap();
rect(&mut s);
// Explicit colour preview remains a colour preview; Save bounds its resolution, not the art.
let r = s.execute("document.save", &json!({"format": "eps", "previewFormat": "tiffColor"})).unwrap();
let r = s.execute("document.save", &json!({"format": "eps", "useArtboards": true, "previewFormat": "tiffColor"})).unwrap();
let bytes = b64(&r);
let (ps, tiff) = vectorcraft_eps::sections(&bytes).unwrap();
let tiff = tiff.unwrap();
+20
View File
@@ -217,6 +217,26 @@ fn dialog_loop_stops_or_exhausts() {
assert_eq!(art(&s), before);
}
#[test]
fn a_run_waiting_at_a_dialog_stops_at_the_next_slice_once_its_work_is_canceled() {
let mut s = one_doc();
let before = art(&s);
let token = crate::cancel::CancelToken::new();
s.script_frames = true;
let source = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); alert('x'); vc.log('answered');";
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "d.js"})).unwrap()["running"], true);
assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none());
assert!(s.script_dialog().is_some());
token.cancel();
let ended = crate::cancel::scope(&token, None, || s.script_pump());
assert!(ended.expect("the run goes on waiting for an answer").is_err());
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}");
assert_eq!(report["dialogs"][0]["answer"], "stop");
assert_eq!(s.script_dialog(), None);
assert_eq!(art(&s), before);
}
#[test]
fn dialog_text_limits_and_controls() {
let mut s = one_doc();
+31
View File
@@ -5,6 +5,7 @@ use std::time::Duration;
use serde_json::{Value, json};
use crate::cancel::{self, CancelToken};
use crate::script::{TEST_ELAPSED, TEST_NO_CLOCK};
use crate::*;
@@ -204,6 +205,36 @@ fn a_sleeping_run_stops_when_asked() {
TEST_ELAPSED.set(None);
}
#[test]
fn a_sleeping_run_stops_at_the_next_slice_once_its_work_is_canceled() {
for (asleep_until, when) in
[(None, "before its first slice"), (Some(Duration::ZERO), "while it sleeps"), (Some(Duration::from_secs(1)), "at its wake time")]
{
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let before = (format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len());
s.script_frames = true;
TEST_ELAPSED.set(Some(Duration::ZERO));
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 5, height: 5}); $.sleep(1000); vc.log('woke'); \
vc.run('shape.rectangle', {x: 9, y: 0, width: 5, height: 5});";
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
let token = CancelToken::new();
if let Some(at) = asleep_until {
assert!(cancel::scope(&token, None, || s.script_pump()).is_none(), "{when}");
assert_eq!(s.script_sleep_left(), Some(Duration::from_secs(1)), "{when}");
TEST_ELAPSED.set(Some(at));
}
token.cancel();
let ended = cancel::scope(&token, None, || s.script_pump());
TEST_ELAPSED.set(None);
assert!(ended.unwrap_or_else(|| panic!("{when}: the run goes on waiting")).is_err(), "{when}");
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{when}: {report}");
assert!(!s.script_running(), "{when}");
assert_eq!((format!("{:?}", s.documents()[0].doc.layers), s.documents()[0].history.undo.len()), before, "{when}");
}
}
#[test]
fn sleep_takes_milliseconds_from_0_to_1000() {
let mut s = Session::new();
+24
View File
@@ -845,6 +845,30 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() {
assert_eq!(state(&s), before);
}
#[test]
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
TEST_GROWTH.with(|g| g.set(Some(20)));
let mut s = two_docs();
let before = state(&s);
s.script_frames = true;
run(&mut s, "for (var i = 0; i < 25; i++) vc.run('shape.rectangle', {x:i,y:1,width:1,height:1});").unwrap();
let token = crate::cancel::CancelToken::new();
for _ in 0..1_000 {
if s.script_waiting() {
break;
}
assert!(crate::cancel::scope(&token, None, || s.script_pump()).is_none());
}
assert!(s.script_waiting());
token.cancel();
let ended = crate::cancel::scope(&token, None, || s.script_pump());
TEST_GROWTH.with(|g| g.set(None));
assert!(ended.expect("the run goes on waiting for Continue").is_err());
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
assert!(!s.script_running());
assert_eq!(state(&s), before);
}
#[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()));
+81
View File
@@ -87,6 +87,87 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() {
let mut s = session();
let list = run(&mut s, "graphicStyle.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
let at = libs.iter().position(|l| l["id"] == "painted-sketched").expect("listed");
assert_eq!((libs[at]["name"].as_str(), libs[at]["count"].as_u64()), (Some("Painted and Sketched"), Some(7)));
assert_eq!(libs[at - 1]["id"], "textures");
let g = run(&mut s, "graphicStyle.library", json!({"library": "Painted and Sketched"}));
let listed: Vec<(&str, &str, Vec<&str>)> =
g["styles"].as_array().unwrap().iter().map(|x| (x["name"].as_str().unwrap(), x["fill"].as_str().unwrap(), names(&x["effects"]))).collect();
let want = [
("Washed Blue", "#8ab9c9", "artistic.watercolor"),
("Bristle Ochre", "#c4975a", "artistic.dryBrush"),
("Pastel Heather", "#a78ca5", "artistic.roughPastels"),
("Charcoal Shade", "#666666", "sketch.charcoal"),
("Ink Contour", "#d9e2df", "brushStrokes.inkOutlines"),
("Wet Ink", "#637b85", "brushStrokes.sumiE"),
("Fine Pen", "#d8d4c6", "sketch.graphicPen"),
];
assert_eq!(listed, want.iter().map(|&(n, f, e)| (n, f, vec![e])).collect::<Vec<_>>());
// Every setting of each effect is given, with the catalog's key and kind of value.
let (_, lib) = cmd::stylelib::library(&s, "painted-sketched").unwrap();
for st in &lib.styles {
let e = &st.appearance.effects[0];
let defaults = vectorcraft_render::effects::effect_info(&e.id).unwrap().defaults;
let (set, all) = (e.params.as_object().unwrap(), defaults.as_object().unwrap());
let keys = |m: &serde_json::Map<String, Value>| m.keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(set), keys(all), "{}", st.name);
for (k, v) in set {
let kind = |v: &Value| (v.is_number(), v.is_string(), v.is_boolean());
assert_eq!(kind(v), kind(&all[k]), "{} / {k}", st.name);
}
}
let strokes: Vec<(&str, f64)> =
lib.styles.iter().filter(|g| g.appearance.stroke_paint() != Paint::None).map(|g| (g.name.as_str(), g.appearance.stroke_width())).collect();
assert_eq!(strokes, [("Bristle Ochre", 1.0), ("Ink Contour", 1.0)]);
// Each one adds and applies to a rectangle in one undo step.
let mut ids = vec![];
for (i, (name, fill, effect)) in want.iter().enumerate() {
let id = rect(&mut s, 10.0 + 25.0 * i as f64, 20.0, 20.0, 30.0);
let before = undo_len(&s);
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": name, "apply": true, "ids": [id.0]}));
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name)));
assert_eq!(undo_len(&s), before + 1, "{name}");
let node = doc(&s).node(id).unwrap();
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex(fill).unwrap()), "{name}");
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), [*effect]);
assert_eq!(node.appearance.effects[0].params, lib.style(name).unwrap().appearance.effects[0].params, "{name}");
ids.push((id, *name));
}
// Adding one again reuses it: no new style, no undo step.
let before = (undo_len(&s), doc(&s).graphic_styles.len());
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink"}));
assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Wet Ink"]));
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
// An unknown style or library changes nothing.
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-sketched", "names": ["Wet Ink", "Nope"]})).is_err());
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-and-sketched", "name": "Wet Ink"})).is_err());
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
// Saved and opened again, the styles keep their effects and the rectangles stay linked to them.
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
run(&mut s, "document.open", json!({"name": "painted.vectorcraft", "dataBase64": b64}));
for (id, name) in &ids {
let d = doc(&s);
let style = d.graphic_style(name).unwrap();
assert!(style.same_look(lib.style(name).unwrap()), "{name}");
let node = d.node(*id).unwrap();
assert_eq!((node.extras().graphic_style, &node.appearance.effects), (Some(style.id), &style.appearance.effects), "{name}");
}
// With nothing selected, `apply` only adds; empty `names` adds the whole library in order.
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Fine Pen", "apply": true}));
assert!(r.get("applied").is_none() && doc(&s).graphic_style("Fine Pen").is_some());
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "names": []}));
assert_eq!((names(&r["added"]), names(&r["existing"])), (want[..6].iter().map(|w| w.0).collect::<Vec<_>>(), vec!["Fine Pen"]));
}
#[test]
fn add_dedupes_names_as_one_undo_step() {
let mut s = session();
+66
View File
@@ -638,6 +638,39 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi
assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into()));
}
#[test]
fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk() {
let lib = vectorcraft_color::libraries::builtin_library("organic-fades").unwrap();
for mode in ["rgb", "cmyk"] {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 100, "height": 100, "colorMode": mode}));
let list = run(&mut s, "swatch.library.list", json!({}));
let row = list["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "organic-fades").unwrap().clone();
assert_eq!(
(row["name"].as_str(), row["category"].as_str(), row["count"].as_u64()),
(Some("Organic Fades"), Some("gradients"), Some(lib.len() as u64))
);
let id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let r = run(&mut s, "swatch.library.add", json!({"library": "organic-fades", "names": ["Petal", "Dew"], "apply": "fill"}));
assert_eq!((r["added"].clone(), r["applied"].clone()), (json!(["Petal", "Dew"]), json!("Petal")), "{mode}");
for name in ["Petal", "Dew"] {
// The swatch comes as the library has it: stops (colors as given, opacities, midpoints) and method.
let Paint::Gradient(added) = &doc(&s).swatch(name).unwrap().paint else { panic!("{name} is a gradient") };
let Paint::Gradient(want) = &lib.swatch(name).unwrap().paint else { panic!("{name} is a gradient") };
assert_eq!(added.gradient, want.gradient, "{mode} {name}");
assert_eq!(added.gradient.method, vectorcraft_color::GradientMethod::Perceptual);
assert!(added.gradient.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{mode} {name}: the stops stay RGB");
assert!(added.gradient.stops.iter().any(|st| st.opacity < 1.0 && (st.midpoint - 0.5).abs() > 0.02), "{mode} {name}");
}
// The fill takes the fade's method, opacities and midpoints.
let fill = doc(&s).node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().appearance.fill_paint();
let (Paint::Gradient(fill), Paint::Gradient(want)) = (fill, &lib.swatch("Petal").unwrap().paint) else { panic!("a gradient fill") };
assert_eq!(fill.gradient.method, want.gradient.method, "{mode}");
let shape = |g: &vectorcraft_color::Gradient| g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect::<Vec<_>>();
assert_eq!(shape(&fill.gradient), shape(&want.gradient), "{mode}");
}
}
#[test]
fn pattern_libraries_bring_their_patterns_and_add_each_once() {
let mut s = session();
@@ -765,6 +798,39 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() {
assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint));
}
/// Grit Textures is listed after Geometric Patterns. One of its patterns comes in with its swatch
/// once, as one undo step that also takes both away, and both stay after a save and reopen.
#[test]
fn a_grit_texture_adds_once_undoes_and_saves() {
let mut s = session();
let list = run(&mut s, "swatch.library.list", json!({}));
let ids: Vec<&str> =
list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect();
assert_eq!(ids, ["geometric-patterns", "grit-textures"]);
let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"}));
let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]);
let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count());
let empty = counts(doc(&s));
let undo = undo_len(&s);
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
assert_eq!(r["added"], json!(["Stipple"]));
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1));
let def = doc(&s).pattern("Stipple").expect("the pattern comes with its swatch").clone();
assert!(def.art.len() >= 144, "{} marks", def.art.len());
assert!(matches!(doc(&s).swatch("Stipple").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Stipple"));
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Stipple"])));
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once");
run(&mut s, "edit.undo", json!({}));
assert_eq!(counts(doc(&s)), empty);
assert!(doc(&s).pattern("Stipple").is_none() && doc(&s).swatch("Stipple").is_none());
run(&mut s, "edit.redo", json!({}));
let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap();
assert_eq!(back.pattern("Stipple"), Some(&def));
assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").map(|w| &w.paint));
}
/// A device name is saved with a `-` after it, which can be another library's own name: neither
/// library replaces the other, and saving either again replaces only itself.
#[test]
@@ -114,3 +114,12 @@ fn keys_named(doc: &str) -> Vec<String> {
}
found.into_iter().map(|(k, _)| k).collect()
}
/// Turn notes the key walk above doesn't reach: a numeric reflection axis and the Scatter brush's
/// `rotation [a, b]` range, whose head isn't a plain key.
#[test]
fn turns_outside_plain_keys_say_which_way() {
let doc = |id: &str| command_specs().iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default();
assert!(doc("object.reflect").contains("|deg (the mirror line, counter-clockwise from horizontal"), "object.reflect's numeric axis");
assert!(doc("brush.options").contains("rotation [a, b] −180..180° (counter-clockwise)"), "the Scatter brush's rotation");
}
+24
View File
@@ -751,6 +751,27 @@ impl Session {
self.apply_actions(acts).map(drop)
}
/// The rulers' origin dragged out of their corner, whatever the tool, with the pointer at `p` in
/// document space (none off the canvas): where it goes, snapped as a drawn point is
/// ([`vectorcraft_tools::rulerguide::OriginDrag`]), the targets gathered on the drag's first
/// call. It changes nothing: the caller sets the origin where the button is released
/// (`document.setRulerOrigin`) and ends the drag ([`Session::end_ruler_origin_drag`]).
pub fn ruler_origin_drag(&mut self, p: Option<Point>, view: ViewInfo) -> Option<Point> {
let drag = match self.ruler_origin.take() {
Some(d) => Some(d),
None => self.with_tool_cx(view, |_, cx| Some(vectorcraft_tools::rulerguide::OriginDrag::new(cx))),
};
let Some(mut drag) = drag else { return p };
let at = self.with_tool_cx(view, |_, cx| drag.pointer(cx, p));
self.ruler_origin = Some(drag);
at
}
/// The drag of the rulers' origin ended, released or cancelled: its guides go.
pub fn end_ruler_origin_drag(&mut self) {
self.ruler_origin = None;
}
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
@@ -1112,6 +1133,9 @@ impl Session {
v.extend(self.with_tool_cx(view, |_, cx| g.overlays(cx)));
self.ruler_guide = Some(g);
}
if let Some(d) = &self.ruler_origin {
v.extend(d.overlays());
}
let deferred_preview = self.unapplied_interaction_preview();
if let Some(d) = self.active() {
let w = self.prefs.perspective_widget;
+2
View File
@@ -674,6 +674,8 @@ fn structured_junk() {
("object.blend.options", json!({"spacing": "distance", "value": -1e308, "orientation": 5})),
("object.blend.options", json!({"ramp": 1e308, "colorShift": -1e308, "easingType": [1]})),
("object.blend.make", json!({"ids": [1, 2], "ramp": f64::NAN, "colorShift": [1]})),
("object.blend.make", json!({"ids": [1, 2], "createSpine": ["never"], "easingType": "easeIn"})),
("object.blend.createSpine", json!({"mode": 1e308})),
("object.blend.spine.moveAnchor", json!({"id": 2, "anchor": u64::MAX, "x": 1e308, "y": -1e308, "handle": "sideways"})),
("object.blend.spine.addAnchor", json!({"id": u64::MAX, "x": 0, "y": 0})),
("object.blend.spine.reshapeSegment", json!({"id": 2, "segment": u64::MAX, "t": f64::NAN, "dx": 1e308, "dy": -1e308})),
@@ -115,15 +115,27 @@ fn both_lexers_take_the_same_characters_into_names() {
assert!(checker_member("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}") && one_identifier("\u{88F}\u{1ACF}", "\u{88F}\u{1ACF}"));
for &c in NAME_CHARS {
let escape = format!("\\u{:04X}", u32::from(c));
let braced = format!("\\u{{{:X}}}", u32::from(c));
for (src, name) in [
(format!("a{c}b"), format!("a{c}b")),
(format!("{c}b"), format!("{c}b")),
(format!("a{escape}b"), format!("a{c}b")),
(format!("{escape}b"), format!("{c}b")),
(format!("a{braced}b"), format!("a{c}b")),
(format!("{braced}b"), format!("{c}b")),
] {
assert_eq!(checker_member(&src, &name), one_identifier(&src, &name), "{src:?} (U+{:04X})", u32::from(c));
}
}
// Braced escapes past U+FFFF and with leading zeros are read by both.
for (src, name) in [("\\u{1D49C}b", "\u{1D49C}b"), ("a\\u{0000000062}", "ab")] {
assert!(checker_member(src, name) && one_identifier(src, name), "{src:?}");
}
// Out of range, a surrogate and an empty one: the parser reads no identifier, and the checker's
// name ends before the escape.
for src in ["a\\u{110000}", "a\\u{D800}", "a\\u{}"] {
assert!(checker_member(src, "a") && !one_identifier(src, "a"), "{src:?}");
}
}
#[test]
+2 -1
View File
@@ -187,7 +187,8 @@ pub enum Expr {
qualifier: Option<XmlQualifier>,
name: XmlNamePart,
},
/// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope.
/// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope
/// that holds it, and also an assignment, update or `delete` target.
XmlScopeName(ExprId),
/// `object..name`.
XmlDescendants {
+2
View File
@@ -466,6 +466,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
.chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()])
.fold(0usize, usize::saturating_add);
interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?;
interp.prepare_source(total)?;
let mut units = Vec::with_capacity(total);
units.extend(HEAD.encode_utf16());
for (i, p) in parts.iter().enumerate() {
@@ -554,6 +555,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
let x = arg(args, 0);
let Value::String(s) = &x else { return Ok(x) };
interp.check_source_units(s.len()).map_err(|e| interp.compile_error_to_abrupt(e))?;
interp.prepare_source(s.len())?;
let units = s.flat();
let code = interp.compile_source(&units, false, CodeKind::Eval).map_err(|e| interp.compile_error_to_abrupt(e))?;
interp.run_global(code, true)
+20 -13
View File
@@ -13,6 +13,7 @@ use super::{
};
use crate::heap::{Class, NativeKind, ObjId};
use crate::interp::{Abrupt, Interp, JsResult, strict_eq};
use crate::string_builtins::flat_charged;
use crate::value::{Str, Value, to_uint32};
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
@@ -278,17 +279,20 @@ fn join_with(interp: &mut Interp, o: ObjId, separator: &Value, item: fn(&mut Int
if len == 0 {
return Ok(Value::str(""));
}
let flat = sep.flat();
let sep = &flat[..];
// A result that cannot fit is refused before any element is read.
let least = (sep.len() as u64).saturating_mul(u64::from(len - 1));
if least > (interp.limits.heap_bytes / 4) as u64 {
return Err(Abrupt::Limit(crate::LimitKind::Heap));
}
interp.join_stack.push(o);
let r = join_elements(interp, o, len, sep, item);
interp.join_stack.pop();
r
// The separator stays rooted for the whole join, so its flattened copy stays counted.
interp.rooted(&[Value::String(sep.clone())], |interp| {
let flat = flat_charged(interp, &sep)?;
let sep = &flat[..];
// A result that cannot fit is refused before any element is read.
let least = (sep.len() as u64).saturating_mul(u64::from(len - 1));
if least > (interp.limits.heap_bytes / 4) as u64 {
return Err(Abrupt::Limit(crate::LimitKind::Heap));
}
interp.join_stack.push(o);
let r = join_elements(interp, o, len, sep, item);
interp.join_stack.pop();
r
})
}
fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(&mut Interp, Value) -> JsResult<Option<Str>>) -> JsResult<Value> {
@@ -301,7 +305,10 @@ fn join_elements(interp: &mut Interp, o: ObjId, len: u32, sep: &[u16], item: fn(
let Some(s) = item(interp, v)? else { continue };
out.push_repeated(interp, sep, k.saturating_sub(seps))?;
seps = k;
out.push_units(interp, &s.flat())?;
interp.rooted(&[Value::String(s.clone())], |interp| {
let units = flat_charged(interp, &s)?;
out.push_units(interp, &units)
})?;
}
out.push_repeated(interp, sep, u64::from(len - 1).saturating_sub(seps))?;
Ok(out.finish(interp))
@@ -472,7 +479,7 @@ fn unshift(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul
with_this(interp, &this, |interp, o| {
let len = u64::from(length_of(interp, o)?);
let count = args.len() as u64;
// With no arguments each element is still read and written back in place (steps 6 and 7).
// With no arguments each element is still read and written back in place (step 6).
let maps = vec![Map::Shift(-1), Map::Shift(count as i64 - 1)];
let mut it = Indices::new(interp, o, 1, len + 1, false, maps)?;
while let Some(k) = it.next(interp)? {
+6 -2
View File
@@ -13,6 +13,7 @@ use std::collections::HashSet;
use super::{Builder, ELEMENT_BYTES, arg, data, key_of, length_of, method, new_array, new_string, to_integer};
use crate::heap::{Class, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key, string_bytes};
use crate::interp::{Desc, ErrorType, Hint, Interp, JsResult};
use crate::string_builtins::flat_charged;
use crate::value::{Str, Value, number_to_str};
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
@@ -473,7 +474,7 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult<Se
let n = to_integer(interp, &space)?.clamp(0.0, 10.0) as usize;
s.gap = vec![u16::from(b' '); n];
}
Value::String(t) => s.gap = t.flat().iter().take(10).copied().collect(),
Value::String(t) => s.gap = flat_charged(interp, &t)?.iter().take(10).copied().collect(),
_ => {}
}
Ok(s)
@@ -632,7 +633,10 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul
Value::Bool(b) => out.push_str(interp, if *b { "true" } else { "false" }),
Value::Number(n) if n.is_finite() => out.push_units(interp, &number_to_str(*n).flat()),
Value::Number(_) => out.push_str(interp, "null"),
Value::String(s) => write_quoted(interp, out, &s.flat()),
Value::String(s) => interp.rooted(std::slice::from_ref(v), |i| {
let units = flat_charged(i, s)?;
write_quoted(i, out, &units)
}),
Value::Undefined | Value::Object(_) => Ok(()),
}
}
+9 -4
View File
@@ -160,8 +160,11 @@ pub(crate) enum Op {
parts: u32,
list: bool,
},
/// `name` → the value of the name on the nearest XML value in scope.
/// `name` → the value of the name on the nearest XML value in scope that holds it.
XmlScopeGet,
/// `name` → `object name`: the nearest XML value in scope that holds the name, for an
/// assignment, update or `delete`.
XmlScopeRef,
/// `object` → the filter's state.
XmlFilterStart,
/// `state` → `state item`, or jumps with `state` when the items are used up.
@@ -170,8 +173,9 @@ pub(crate) enum Op {
XmlFilterTest,
/// `state` → the XMLList of the items kept.
XmlFilterEnd,
/// `iterator name` → `iterator value`: the value under the name a `for each` got.
ForEachValue,
/// `iterator name x₁…xₙ` → `iterator name x₁…xₙ value`: the value under the name a `for each`
/// got, read after the `n` values its target pushed.
ForEachValue(u32),
/// `value` → nothing: sets the default XML namespace of the running code.
SetDefaultNamespace,
}
@@ -308,7 +312,8 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::XmlDescendants | Op::XmlFilterTest => e(2, 1),
Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1),
Op::XmlLiteral { parts, .. } => e(parts, 1),
Op::ForEachValue => e(2, 2),
Op::XmlScopeRef => e(1, 2),
Op::ForEachValue(n) => e(n + 2, n + 3),
Op::SetDefaultNamespace => e(1, 0),
})
}
+78 -4
View File
@@ -497,16 +497,21 @@ impl<'a> FnCompiler<'a> {
let brk = self.new_label();
self.bind(head);
self.jump(Op::ForInNext, brk);
if each {
self.emit(Op::ForEachValue);
}
match target {
ForInTarget::Var(d) => {
let n = self.var_name(&d.name.name);
if each {
self.emit(Op::ForEachValue(0));
}
self.emit(Op::SetVar(n));
}
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
ForInTarget::Expr(e) => self.store_key_to(*e)?,
}
if each {
// The value; the name under it goes next.
self.emit(Op::Pop);
}
self.emit(Op::Pop);
self.loop_body(body, labels, brk, head)?;
self.jump(Op::Jump, head);
@@ -538,6 +543,11 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::Rot3);
self.emit(Op::SetIndex);
}
Some(Expr::XmlScopeName(name)) => {
self.xml_scope_ref(target, *name)?;
self.emit(Op::Rot3);
self.emit(Op::SetIndex);
}
_ => {
self.expr(target)?;
self.emit(Op::Pop);
@@ -547,6 +557,46 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
/// Assigns the value under the name on top of the stack to a `for each` target expression,
/// leaving the name and then the value on top. The target is evaluated before the value is
/// read (ECMA-357 section 12.3).
fn store_value_to(&mut self, target: ExprId) -> CResult<()> {
let target = self.ast.unparenthesized(target);
self.at(self.ast.expr_span(target).start);
match self.ast.expr(target) {
Some(Expr::Ident(name)) => {
let n = self.var_name(name);
self.emit(Op::ForEachValue(0));
self.emit(Op::SetVar(n));
}
Some(Expr::Member { object, property }) => {
self.expr(*object)?;
self.emit(Op::ForEachValue(1));
let n = self.name_key(key_of(&property.name));
self.emit(Op::SetMember(n));
}
Some(Expr::Index { object, index }) => {
self.expr(*object)?;
self.expr(*index)?;
self.emit(Op::ToKey);
self.emit(Op::ForEachValue(2));
self.emit(Op::SetIndex);
}
Some(Expr::XmlScopeName(name)) => {
self.xml_scope_ref(target, *name)?;
self.emit(Op::ForEachValue(2));
self.emit(Op::SetIndex);
}
_ => {
self.expr(target)?;
self.emit(Op::Pop);
self.emit(Op::ForEachValue(0));
self.throw_invalid_target();
}
}
Ok(())
}
fn throw_invalid_target(&mut self) {
let s = self.string(&"invalid assignment target".encode_utf16().collect::<Vec<u16>>());
let depth = self.depth;
@@ -854,6 +904,15 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
/// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression
/// `id`, then the name, as an assignment, update or `delete` uses them.
fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> {
self.expr(name)?;
self.at(self.ast.expr_span(id).start);
self.emit(Op::XmlScopeRef);
Ok(())
}
fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> {
for part in parts {
match part {
@@ -1096,6 +1155,10 @@ impl<'a> FnCompiler<'a> {
self.expr(*index)?;
self.emit(Op::DeleteIndex);
}
Some(Expr::XmlScopeName(name)) => {
self.xml_scope_ref(arg, *name)?;
self.emit(Op::DeleteIndex);
}
_ => {
self.expr(arg)?;
self.emit(Op::Pop);
@@ -1202,6 +1265,13 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::GetIndex);
}
}
Some(Expr::XmlScopeName(name)) => {
self.xml_scope_ref(target, *name)?;
if op.is_some() {
self.emit(Op::Dup2);
self.emit(Op::GetIndex);
}
}
_ => {
self.expr(target)?;
if op.is_none() {
@@ -1222,7 +1292,7 @@ impl<'a> FnCompiler<'a> {
let n = self.name_key(key_of(&property.name));
self.emit(Op::SetMember(n));
}
Some(Expr::Index { .. }) => self.emit(Op::SetIndex),
Some(Expr::Index { .. } | Expr::XmlScopeName(_)) => self.emit(Op::SetIndex),
_ => self.throw_invalid_target(),
}
Ok(())
@@ -1246,6 +1316,10 @@ impl<'a> FnCompiler<'a> {
self.expr(*index)?;
self.emit(Op::IncIndex { prefix, dec });
}
Some(Expr::XmlScopeName(name)) => {
self.xml_scope_ref(target, *name)?;
self.emit(Op::IncIndex { prefix, dec });
}
_ => {
self.expr(target)?;
self.emit(Op::ToNumber);
+21 -3
View File
@@ -397,11 +397,29 @@ impl Interp {
let writes = strict_writes().unwrap_or_else(|| self.writes_mode());
self.evaluated = self.evaluated.saturating_add(1);
let tag = std::mem::replace(&mut self.source_tag, self.evaluated);
let code = self.encode_source(&source).and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval));
// UTF-8 takes at most 3 bytes for each UTF-16 code unit, so the fuel for a third of the
// bytes is taken before the source is encoded, and the rest after. A source within the
// source limit must fit in the heap whole before it is encoded; a longer one is refused as
// a syntax error when it is encoded.
let floor = source.len().div_ceil(3);
let fits = |interp: &mut Self| {
let units = source.encode_utf16().count();
if interp.check_source_units(units).is_ok() { interp.reserve_heap(string_bytes(units)) } else { Ok(()) }
};
let code = self.prepare_source(floor).and_then(|()| fits(self)).map(|()| {
let units = self.encode_source(&source);
let rest = match &units {
Ok(units) => self.prepare_source(units.len().saturating_sub(floor)),
Err(_) => Ok(()),
};
rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)))
});
let code = code.and_then(|c| c);
self.source_tag = tag;
let r = match code {
Ok(code) => self.run_global(code, true),
Err(e) => Err(self.compile_error_to_abrupt(e)),
Ok(Ok(code)) => self.run_global(code, true),
Ok(Err(e)) => Err(self.compile_error_to_abrupt(e)),
Err(limit) => Err(limit),
};
end();
r
+39
View File
@@ -638,6 +638,45 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn
assert_eq!(r.error_source(), 0, "a syntax error is in the script");
}
#[test]
fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
// The evaluator gives 131,072 spaces and a number: far more code units than the fuel left.
let ends = Rc::new(Cell::new(0));
let ended = ends.clone();
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
let mut r = realm(10_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
let e = r.run("host.evaluate()").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel));
assert_eq!(ends.get(), 1, "the evaluator's end runs once");
// This fuel covers a third of the source's bytes but not all of its code units.
r.set_limits(Limits { fuel: 60_000, ..Limits::default() });
assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Fuel));
assert_eq!(ends.get(), 2);
r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() });
assert_eq!(r.run("host.evaluate()"), Ok(JsValue::Number(7.0)));
assert_eq!(ends.get(), 3);
}
#[test]
fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
// A third of the source and the other two thirds each fit in the heap; the whole does not.
// The source does not parse, so a parse would throw a syntax error instead.
let n = (1 << 17) + 1;
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
let mut r = realm(1_000_000);
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
r.interp().collect_for_room();
let heap_bytes = r.interp().heap.bytes + crate::heap::string_bytes(n * 5 / 6);
r.set_limits(Limits { fuel: 1_000_000, heap_bytes, ..Limits::default() });
assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Limit(LimitKind::Heap));
// With room for the whole source, it is parsed.
r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() });
assert_eq!(r.run("host.evaluate()").unwrap_err().kind, RunErrorKind::Thrown);
}
proptest::proptest! {
/// A slice size does not change what a script computes.
#[test]
+92 -19
View File
@@ -9,7 +9,8 @@
//! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and,
//! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap
//! limit, the frame limit, the re-entry limit and the interrupt flag each end the run with an
//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks.
//! [`Abrupt::Limit`] that unwinds every frame without running catch or finally blocks. Source
//! compiled during a run takes a unit of fuel for each code unit before it is parsed.
//!
//! Collection runs only between instructions. An operation that may run JavaScript in the middle
//! keeps its operands on the operand stack until it is done, so everything it holds is reachable
@@ -26,6 +27,7 @@ use crate::heap::{
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
};
use crate::string_builtins::flat_charged;
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
use crate::{LimitKind, Limits, Options};
@@ -204,6 +206,12 @@ pub(crate) struct Interp {
pub(crate) date_host: crate::date_builtins::DateHost,
/// The bytes native code holds outside the heap's cells through [`HeldBytes`].
pub(crate) held: Rc<HeldCount>,
/// Bytes of the copies [`Self::get_own_property`] made flattening the rope of a String
/// object, which the heap's total adds before the next limit check.
flattened: std::cell::Cell<usize>,
/// Fuel for the units those copies took and the rope nodes it read in place, which the next
/// step takes.
pub(crate) flattened_fuel: std::cell::Cell<u64>,
/// The global code's default XML namespace URI (ECMA-357 section 12.1).
pub(crate) xml_default_uri: Key,
/// Set by the host to end the current slice of a resumable run at the next safe point.
@@ -449,6 +457,8 @@ impl Interp {
files: None,
date_host: crate::date_builtins::DateHost::default(),
held: Rc::default(),
flattened: std::cell::Cell::new(0),
flattened_fuel: std::cell::Cell::new(0),
xml_default_uri: Rc::from(Vec::new()),
pause: Rc::default(),
in_slice: false,
@@ -568,6 +578,7 @@ impl Interp {
fn tick(&mut self) -> JsResult<()> {
self.use_fuel()?;
crate::regexp_vm::use_fuel_n(self, self.flattened_fuel.replace(0))?;
self.settle_held();
if self.heap.bytes > self.gc_threshold {
self.collect_garbage();
@@ -594,10 +605,12 @@ impl Interp {
Ok(())
}
/// Takes the bytes that dropped [`HeldBytes`] released off the heap's total.
/// Takes the bytes that dropped [`HeldBytes`] released off the heap's total, and adds the
/// bytes of the ropes [`Self::get_own_property`] flattened.
fn settle_held(&mut self) {
let released = self.held.released.replace(0);
self.heap.bytes = self.heap.bytes.saturating_sub(released);
let flattened = self.flattened.replace(0);
self.heap.bytes = self.heap.bytes.saturating_sub(released).saturating_add(flattened);
}
/// Collects garbage now and sets when the next collection runs.
@@ -617,6 +630,22 @@ impl Interp {
Ok(())
}
/// Prepares for parsing `units` code units of source at run time: takes a unit of fuel for
/// each code unit and checks that the source text fits in the heap, before any of it is
/// flattened, parsed or compiled. Running out of fuel uses up what was left.
pub(crate) fn prepare_source(&mut self, units: usize) -> JsResult<()> {
let fuel = u64::try_from(units).unwrap_or(u64::MAX);
if fuel > self.fuel {
self.fuel = 0;
return Err(Abrupt::Limit(LimitKind::Fuel));
}
self.fuel -= fuel;
if self.interrupt.load(Ordering::Relaxed) {
return Err(Abrupt::Limit(LimitKind::Interrupted));
}
self.reserve_heap(string_bytes(units))
}
/// Removes the [`Self::finally_marks`] entries of `finally` blocks that `break`, `continue` or
/// `return` left: those whose stack slot no longer holds their exception.
fn drop_left_finally_marks(&mut self) {
@@ -663,6 +692,7 @@ impl Interp {
self.heap.collect(&roots);
// The collection counts the live total again, so bytes already released are not in it.
self.held.released.set(0);
self.flattened.set(0);
self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get());
}
@@ -926,11 +956,12 @@ impl Interp {
Op::XmlEscape(kind) => self.op_xml_escape(kind),
Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list),
Op::XmlScopeGet => self.op_xml_scope_get(),
Op::XmlScopeRef => self.op_xml_scope_ref(),
Op::XmlFilterStart => self.op_xml_filter_start(),
Op::XmlFilterNext(t) => self.op_xml_filter_next(t),
Op::XmlFilterTest => self.op_xml_filter_test(),
Op::XmlFilterEnd => self.op_xml_filter_end(),
Op::ForEachValue => self.op_for_each_value(),
Op::ForEachValue(n) => self.op_for_each_value(n as usize),
Op::SetDefaultNamespace => self.op_set_default_namespace(),
Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"),
}
@@ -1217,7 +1248,33 @@ impl Interp {
if let Some(i) = array_index(k)
&& (i as usize) < s.len()
{
let unit = s.flat().get(i as usize).copied().unwrap_or(0);
let unit = if s.is_rope() {
let owed = self.flattened_fuel.get();
let flattened = self.flattened.get().saturating_add(string_bytes(s.len()));
if self.heap.bytes.saturating_add(flattened) > self.limits.heap_bytes {
// The copy does not fit without a collection, which needs `&mut self`:
// the unit is read along the rope instead, a unit of fuel per node.
let Some((unit, visited)) = s.unit_at(i as usize, self.fuel.saturating_sub(owed)) else {
return Err(Abrupt::Limit(LimitKind::Fuel));
};
self.flattened_fuel.set(owed.saturating_add(visited));
unit
} else {
// Flattening copies the units. The run ends here when the fuel for
// the copy is not left; otherwise the next step takes it, and the
// next limit check adds the copy's bytes.
let fuel = owed.saturating_add((s.len() / crate::string_builtins::UNITS_PER_FUEL) as u64 + 1);
if fuel > self.fuel {
return Err(Abrupt::Limit(LimitKind::Fuel));
}
self.flattened_fuel.set(fuel);
self.flattened.set(flattened);
s.flat().get(i as usize).copied()
}
} else {
s.flat().get(i as usize).copied()
}
.unwrap_or(0);
return Ok(Some(Prop::Data { value: Value::String(Str::from_units(vec![unit])), flags: ENUMERABLE }));
}
}
@@ -1294,7 +1351,7 @@ impl Interp {
if let Some(i) = array_index(k)
&& (i as usize) < s.len()
{
let unit = s.flat().get(i as usize).copied().unwrap_or(0);
let unit = flat_charged(self, s)?.get(i as usize).copied().unwrap_or(0);
return Ok(Value::String(Str::from_units(vec![unit])));
}
}
@@ -2401,7 +2458,8 @@ impl Interp {
};
let strict = self.strict();
self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?;
let units = s.flat();
self.prepare_source(s.len())?;
let units = self.flat_reserved(s)?;
let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?;
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
let frame = self.frame()?;
@@ -2566,7 +2624,7 @@ impl Interp {
Value::Null => 0.0,
Value::Bool(b) => f64::from(u8::from(*b)),
Value::Number(n) => *n,
Value::String(s) => string_to_number(&s.flat()),
Value::String(s) => string_to_number(&flat_charged(self, s)?),
Value::Object(_) => {
let p = self.to_primitive(v, Hint::Number)?;
return self.to_number(&p);
@@ -2600,19 +2658,28 @@ impl Interp {
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_key(&mut self, v: &Value) -> JsResult<Key> {
match v {
Value::String(s) => {
let rope = s.is_rope();
let flat = s.flat();
if rope {
self.heap.bytes += string_bytes(flat.len());
}
Ok(flat)
}
Value::String(s) => self.flat_reserved(s),
Value::Number(n) if *n >= 0.0 && *n < 4_294_967_295.0 && n.fract() == 0.0 => Ok(index_key(*n as u32)),
_ => Ok(self.to_str(v)?.flat()),
_ => {
let s = self.to_str(v)?;
self.flat_reserved(&s)
}
}
}
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that
/// copy's bytes are reserved and added to the heap first, without taking fuel. The rope stays
/// rooted while the copy is reserved; everything else the caller still needs must be
/// reachable from the roots.
fn flat_reserved(&mut self, s: &Str) -> JsResult<Key> {
if s.is_rope() {
let bytes = string_bytes(s.len());
self.rooted(&[Value::String(s.clone())], |i| i.reserve_heap(bytes))?;
self.heap.bytes = self.heap.bytes.saturating_add(bytes);
}
Ok(s.flat())
}
/// ToObject (section 9.9).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_object(&mut self, v: &Value) -> JsResult<ObjId> {
@@ -2735,7 +2802,11 @@ impl Interp {
(self.to_primitive(x, Hint::Number)?, py)
};
if let (Value::String(a), Value::String(b)) = (&px, &py) {
return Ok(Some(*a.flat() < *b.flat()));
// Both stay rooted, so the first copy is still counted while the second is made.
return self.rooted(&[px.clone(), py.clone()], |i| {
let (a, b) = (flat_charged(i, a)?, flat_charged(i, b)?);
Ok(Some(*a < *b))
});
}
let nx = self.to_number(&px)?;
let ny = self.to_number(&py)?;
@@ -2760,7 +2831,9 @@ impl Interp {
| (Value::String(_), Value::String(_))
| (Value::Bool(_), Value::Bool(_))
| (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)),
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => return Ok(*n == string_to_number(&s.flat())),
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => {
return Ok(*n == string_to_number(&flat_charged(self, s)?));
}
(Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))),
(_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))),
(Value::Number(_) | Value::String(_), Value::Object(_)) => y = self.to_primitive(&y, Hint::Default)?,
+16 -2
View File
@@ -500,6 +500,19 @@ fn declarations_take_fuel() {
assert_eq!(limit(&mut realm, &format!("Function('var {vars};')();")), LimitKind::Fuel);
}
#[test]
fn source_compiled_during_a_run_takes_fuel_before_it_is_parsed() {
// Doubling a string 17 times makes 131,072 spaces in about a hundred instructions, so only
// the compiled source can use up the fuel.
let build = "var s = ' '; for (var i = 0; i < 17; i++) s += s;";
let mut realm = small(Limits { fuel: 10_000, ..Limits::default() });
for call in ["eval(s)", "(0, eval)(s)", "Function(s)", "new Function('a', s)"] {
assert_eq!(limit(&mut realm, &format!("{build} {call};")), LimitKind::Fuel, "{call}");
}
let mut realm = small(Limits { fuel: 1_000_000, ..Limits::default() });
assert_eq!(realm.run(&format!("{build} eval(s + '1') + (0, eval)(s + '2') + Function(s + 'return 3')()")), Ok(JsValue::Number(6.0)));
}
#[test]
fn a_lower_heap_limit_applies_to_what_is_already_live() {
// A heap already past the new limit ends the next run.
@@ -823,13 +836,14 @@ fn long_property_names_count_toward_the_heap_after_their_strings_are_collected()
// Each name is a 16,385-unit buffer that only the object's key or the function's binding
// holds once the string that made it is garbage, so about 32 of them fill the heap well before
// the fuel runs out. In the second script the property lookup flattens a long string each
// time, so collections run.
// time, so collections run. Each eval there also takes fuel for its source, so that run has
// more fuel.
let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() });
let src = "var s = 'x'; while (s.length < 10000) s += s; var o = {}; for (var i = 0; ; i++) o[s + i] = 1;";
assert_eq!(limit(&mut realm, src), LimitKind::Heap);
let src = "var s = 'x'; while (s.length < 10000) s += s; \
(function () { for (var i = 0; ; i++) { eval('var ' + s + i + ' = 1'); ({})[s + i]; } })();";
let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 20_000, ..Limits::default() });
let mut realm = small(Limits { heap_bytes: 1 << 20, fuel: 5_000_000, ..Limits::default() });
assert_eq!(limit(&mut realm, src), LimitKind::Heap);
}
+4 -3
View File
@@ -873,8 +873,9 @@ impl<'s> Parser<'s> {
}
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
/// neither `eval` nor `arguments`), a property, or outside strict mode code a call (assigning
/// to its result fails at run time, as ECMA-262 2015 Annex B and web browsers have it).
/// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`;
/// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails
/// at run time, as ECMA-262 2015 Annex B and web browsers have it).
fn check_target(&self, expr: ExprId, message: &str) -> Result<()> {
let inner = self.ast.unparenthesized(expr);
match self.ast.expr(inner) {
@@ -884,7 +885,7 @@ impl<'s> Parser<'s> {
}
Ok(())
}
Some(Expr::Member { .. } | Expr::Index { .. }) => Ok(()),
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()),
Some(Expr::Call { .. }) if !self.ctx.strict => Ok(()),
_ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)),
}
+3 -1
View File
@@ -14,7 +14,8 @@ use crate::{Options, SyntaxError};
/// cannot catch it, and their `finally` blocks do not run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Limits {
/// Instructions a run may execute.
/// Instructions a run may execute. Source that `eval`, `Function` or a host evaluator
/// compiles during the run also takes one unit for each UTF-16 code unit, before it is parsed.
pub fuel: u64,
/// Estimated bytes the heap (objects, environments and the strings they hold) may reach
/// after a collection. A string longer than a quarter of this many code units cannot be
@@ -230,6 +231,7 @@ impl Realm {
return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 });
}
interp.fuel = interp.limits.fuel;
interp.flattened_fuel.set(0);
interp.source_units = 0;
interp.throw_site = None;
interp.last_thrown = Value::Undefined;
+3 -2
View File
@@ -109,10 +109,11 @@ fn push_held<T>(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec<T>, it
}
/// The code units of `s`. Flattening a rope makes a copy of its units, so for a rope that copy's
/// bytes are reserved and added to the heap, and its units charged as fuel, first.
/// bytes are reserved and added to the heap, and its units charged as fuel, first. The rope stays
/// rooted while the copy is reserved, so what it holds is still counted.
pub(crate) fn flat_charged(interp: &mut Interp, s: &Str) -> JsResult<Rc<[u16]>> {
if s.is_rope() {
reserve_units(interp, s.len())?;
interp.rooted(&[Value::String(s.clone())], |interp| reserve_units(interp, s.len()))?;
}
Ok(s.flat())
}
+125
View File
@@ -309,6 +309,131 @@ fn flattening_a_rope_counts_against_the_heap() {
}
}
#[test]
fn operators_and_builtins_count_a_flattened_rope_against_the_heap() {
// Three ropes of about 524,288 units, each 1 MiB once flat, with a 3 MiB heap.
let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z';";
let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() };
let not_stopped: Vec<_> =
["X < 'a'", "X == 1", "+X", "X[0]", "({})[{ toString: function () { return X; } }]", "JSON.stringify(0, null, X)", "[1].join(X)"]
.into_iter()
.filter(|read| {
let src = format!("{build} {}; {}; {}; 0", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u"));
let result = Realm::with_options(Options::default(), limits.clone()).run(&src);
!matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))
})
.collect();
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
}
#[test]
fn a_flattened_temporary_stays_counted_while_the_next_copy_is_made() {
// Ropes of 262,145 units, each about half the heap once flat: one fits, two don't. Each is
// made by a function, so nothing but the native code holds it while it is flattened.
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; }";
let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() };
let run = |read: &str| Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0"));
assert!(run("f('a')[0]").is_ok(), "one flattened copy fits");
let not_stopped: Vec<_> = [
"({ valueOf: function () { return f('a'); } }) < ({ valueOf: function () { return f('b'); } })",
"JSON.stringify({ toJSON: function () { return f('a'); } })",
"[1, 2].join({ toString: function () { return f('a'); } })",
"[{ toString: function () { return f('a'); } }].join('')",
]
.into_iter()
.filter(|read| !matches!(run(read), Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)))
.collect();
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
}
#[test]
fn a_converted_rope_counts_what_it_holds_while_its_copy_is_made() {
// `mk` returns a rope whose left half is a flat string of about half the heap, held by
// nothing else. Its flattened copy is the other half, so the two don't fit together.
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \
function mk() { var a = f('a'); a[0]; return a + 'b'; }";
let limits = Limits { heap_bytes: 4 * 262_146, ..Limits::default() };
let not_stopped: Vec<_> = [
"+({ valueOf: mk })",
"({})[{ toString: mk }]",
"({ valueOf: mk }) == 1",
"++({ get x() { return mk(); } }).x",
"JSON.stringify(0, null, (function () { var o = new String(''); o.toString = mk; return o; })())",
]
.into_iter()
.filter(|read| {
let result = Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} {read}; 0"));
!matches!(result, Err(ref e) if e.kind == RunErrorKind::Limit(LimitKind::Heap))
})
.collect();
assert!(not_stopped.is_empty(), "not stopped by the heap limit: {not_stopped:?}");
}
#[test]
fn a_string_object_counts_its_flattened_rope_against_the_heap() {
// The same three ropes, each wrapped in a String object and read by index.
let build = "var s = 'x'; for (var i = 0; i < 19; i++) s = s + s; var t = s + 'y', u = s + 'z'; \
String.prototype.first = function () { return this[0]; };";
let limits = Limits { heap_bytes: 3 << 20, ..Limits::default() };
// Wrapping alone reads no units, so it makes no copy.
let lengths =
Realm::with_options(Options::default(), limits.clone()).run(&format!("{build} Object(s).length + new String(t).length + Object(u).length"));
assert_eq!(lengths, Ok(JsValue::Number(1_572_866.0)));
// Two copies fit. The third read finds no room for its copy and reads the unit along the
// rope, so the live heap stays within the limit.
for (read, expected) in [
("Object(X)[0]", "xxx"),
("new String(X)[0]", "xxx"),
("0 in Object(X)", "truetruetrue"),
("Object(X).hasOwnProperty(0)", "truetruetrue"),
("X.first()", "xxx"),
("Object(X)[524288]", "undefinedyz"),
] {
let src = format!("{build} '' + ({}) + ({}) + ({})", read.replace('X', "s"), read.replace('X', "t"), read.replace('X', "u"));
let mut realm = Realm::with_options(Options::default(), limits.clone());
assert_eq!(realm.run(&src), Ok(JsValue::String(expected.into())), "{read}");
let interp = realm.interp();
interp.collect_garbage();
assert!(interp.heap.bytes <= limits.heap_bytes, "{read}: {} bytes live", interp.heap.bytes);
}
let wrapped =
Realm::with_options(Options::default(), Limits::default()).run(&format!("{build} Object(t)[524288] + new String(u)[524288] + t.first()"));
assert_eq!(wrapped, Ok(JsValue::String("yzx".into())));
}
#[test]
fn a_string_object_takes_fuel_for_the_rope_it_flattens() {
let limits = Limits { fuel: 40_000, ..Limits::default() };
let build = "var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object(s).length";
assert!(Realm::with_options(Options::default(), limits.clone()).run(build).is_ok());
for read in ["Object(s)[0]", "0 in new String(s)"] {
let e = fail_with(Realm::with_options(Options::default(), limits.clone()), &format!("{build}; {read}"));
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{read}: {e:?}");
}
// A run that ends with an error right after the read leaves the next run its whole fuel.
let mut realm = Realm::with_options(Options::default(), Limits { fuel: 100_000, ..Limits::default() });
let defined = realm.run("var s = ' '; for (var i = 0; i < 20; i++) s = s + s; Object.defineProperty(new String(s), 0, { value: 'a' })");
assert!(matches!(defined, Err(ref e) if e.kind == RunErrorKind::Thrown), "{defined:?}");
assert!(realm.run("for (var j = 0; j < 5000; j++) {} j").is_ok());
}
#[test]
fn a_call_keeps_its_operands_while_a_string_receiver_is_boxed() {
// `g` leaves a garbage string, so the heap is close to its limit when the rope receiver of a
// non-strict function is boxed. The callee and the argument object are off the stack by
// then, and must survive anything boxing the receiver does.
let build = "var s = 'x'; for (var i = 0; i < 17; i++) s = s + s; function f(c) { return s + c; } \
function mk() { var a = f('a'); a[0]; return a + 'b'; } 0";
let mut realm = Realm::with_options(Options::default(), Limits::default());
assert_eq!(realm.run(build), Ok(JsValue::Number(0.0)));
let interp = realm.interp();
interp.collect_garbage();
interp.limits.heap_bytes = interp.heap.bytes + 2 * crate::heap::string_bytes(131_073) + (64 << 10);
interp.reset_gc_threshold();
let src = "(function () { var g = f('g'); g[0]; })(); (function (o) { return o.x; }).call(mk(), { x: 1 })";
assert_eq!(realm.run(src), Ok(JsValue::Number(1.0)));
}
#[test]
fn compiling_a_pattern_counts_against_the_heap() {
let src = "var s = '[\\\\s\\\\S]a*'; for (var i = 0; i < 14; i++) s = s + s; new RegExp(s).source.length";
+28
View File
@@ -163,6 +163,34 @@ impl Str {
flat
}
/// The code unit at `i` read along the rope without flattening it, visiting at most
/// `max_nodes` nodes: `None` when that is not enough, otherwise the unit (when `i` is in
/// range) and the number of nodes visited.
pub(crate) fn unit_at(&self, mut i: usize, max_nodes: u64) -> Option<(Option<u16>, u64)> {
let mut node = self.clone();
let mut visited = 0u64;
loop {
visited += 1;
if visited > max_nodes {
return None;
}
let next = match &*node.0.borrow() {
Node::Flat(f) => return Some((f.get(i).copied(), visited)),
Node::Concat { left, right, .. } => {
let left_len = left.len();
if i < left_len {
left.clone()
} else {
i -= left_len;
right.clone()
}
}
Node::Taken => return Some((None, visited)),
};
node = next;
}
}
pub(crate) fn to_rust_string(&self) -> String {
String::from_utf16_lossy(&self.flat())
}
+28 -18
View File
@@ -2863,27 +2863,24 @@ impl Interp {
self.replace(n, value)
}
pub(crate) fn op_xml_scope_get(&mut self) -> JsResult<()> {
let name = self.peek(0)?;
let n = self.xml_name_only(&name)?;
/// The nearest XML or XMLList value in scope whose [[HasProperty]] accepts `n`, or a
/// ReferenceError when none does (ECMA-357 section 11.1).
fn xml_scope_holder(&mut self, n: &NameRef) -> JsResult<ObjId> {
let mut cur = Some(self.frame()?.env);
let mut first = None;
let mut any_xml = false;
while let Some(e) = cur {
match self.heap.env(e) {
Some(Env::Decl { outer, .. }) => cur = *outer,
Some(&Env::Obj { object, outer, .. }) => {
let v = Value::Object(object);
if self.is_xml(&v) {
if first.is_none() {
first = Some(object);
}
any_xml = true;
let found = match self.classify(&v) {
Xv::Node(x) => self.node_has_name(x, &n)?,
_ => self.list_has_name(object, &n)?,
Xv::Node(x) => self.node_has_name(x, n)?,
_ => self.list_has_name(object, n)?,
};
if found {
first = Some(object);
break;
return Ok(object);
}
}
cur = outer;
@@ -2891,13 +2888,26 @@ impl Interp {
None => return Err(Abrupt::Internal("environment out of range".into())),
}
}
let Some(object) = first else {
return Err(self.throw(ErrorType::Reference, "an XML name is used outside any XML value"));
};
let message = if any_xml { "no XML value in scope has the XML name" } else { "an XML name is used outside any XML value" };
Err(self.throw(ErrorType::Reference, message))
}
pub(crate) fn op_xml_scope_get(&mut self) -> JsResult<()> {
let name = self.peek(0)?;
let n = self.xml_name_only(&name)?;
let object = self.xml_scope_holder(&n)?;
let v = self.xml_select(object, &n)?;
self.replace(1, Value::Object(v))
}
pub(crate) fn op_xml_scope_ref(&mut self) -> JsResult<()> {
let name = self.peek(0)?;
let n = self.xml_name_only(&name)?;
let object = self.xml_scope_holder(&n)?;
self.replace(1, Value::Object(object))?;
self.push(name)
}
pub(crate) fn op_xml_filter_start(&mut self) -> JsResult<()> {
let base = self.peek(0)?;
let input = match self.classify(&base) {
@@ -2951,9 +2961,9 @@ impl Interp {
self.replace(1, Value::Object(out))
}
pub(crate) fn op_for_each_value(&mut self) -> JsResult<()> {
let name = self.peek(0)?;
let Value::Object(iter) = self.peek(1)? else { return Err(Abrupt::Internal("for-in iterator is not an object".into())) };
pub(crate) fn op_for_each_value(&mut self, above: usize) -> JsResult<()> {
let name = self.peek(above)?;
let Value::Object(iter) = self.peek(above + 1)? else { return Err(Abrupt::Internal("for-in iterator is not an object".into())) };
let object = match self.heap.object(iter).map(|o| &o.class) {
Some(Class::ForIn(state)) => state.object,
_ => return Err(Abrupt::Internal("not a for-in iterator".into())),
@@ -2965,7 +2975,7 @@ impl Interp {
}
None => Value::Undefined,
};
self.replace(1, v)
self.push(v)
}
/// The URI of a Namespace value or of its string form.
+97
View File
@@ -688,6 +688,103 @@ fn a_scope_name_skips_a_list_without_that_name() {
truth("var outer = <o id='1'/>; var inner = <><i id='2'/></>; with (outer) with (inner) { @id == '2' }");
}
#[test]
fn bare_attribute_assignment_uses_nearest_holder() {
truth("var x = <a b='1'/>; with (x) { @b = '2'; } x.@b == '2'");
truth("var outer = <o id='1'/>; var inner = <i/>; with (outer) with (inner) { @id = '9'; } outer.@id == '9' && inner.@id.length() === 0");
truth("var outer = <o id='1'/>; var inner = <i id='2'/>; with (outer) with (inner) { @id = '9'; } outer.@id == '1' && inner.@id == '9'");
truth("var outer = <o id='1'/>; var inner = <><i/></>; with (outer) with (inner) { @id = '9'; } outer.@id == '9' && inner.@id.length() === 0");
truth("var x = <a b='1'/>; with (x) with ({ b: 7 }) { @b = '3'; } x.@b == '3'");
truth("with (<a b='1'/>) { (@b = 5) === 5 }");
truth("var x = <a b='1' c='2'/>; with (x) { @b = @c = 'v'; } x.@b == 'v' && x.@c == 'v'");
truth("var n = 0; var x = <a b='1'/>; with (x) { @[(n++, 'b')] = 'z'; } n === 1 && x.@b == 'z' && x.attributes().length() === 1");
truth("var x = <a><c>1</c></a>; with (x) { *::c = '2'; } x.c == '2' && x.*.length() === 1");
truth("var x = <a b='1'/>; x.@b = '4'; x.@b == '4'");
}
#[test]
fn bare_qualified_assignment_keeps_namespace() {
truth(
"var ns = new Namespace('u'); var x = <a xmlns:p='u'><p:c>1</p:c><c>0</c></a>; with (x) { ns::c = '2'; } \
x.ns::c == '2' && x.ns::c.name().uri === 'u' && x.c == '0' && x.*.length() === 2",
);
truth(
"var ns = new Namespace('u'); var x = <a xmlns:p='u' p:t='1' t='0'/>; with (x) { @ns::t = '5'; } \
x.@ns::t == '5' && x.@ns::t.name().uri === 'u' && x.@t == '0'",
);
}
#[test]
fn bare_assignment_in_filter_mutates_each_matching_item() {
truth("var l = <><i id='1'/><i id='2'/></>; var r = l.(@id = 'z', true); r.length() === 2 && l[0].@id == 'z' && l[1].@id == 'z'");
truth("var l = <><i n='1'/><i n='2'/></>; var r = l.(@n = 0); r.length() === 0 && l[0].@n == '0' && l[1].@n == '0'");
truth("var l = <><i n='1'/><i n='2'/></>; var r = l.(@n = 'k'); r.length() === 2");
truth("var o = <o k='1'/>; var l = <><i/><i/></>; with (o) { l.(@k += 'x', true); } o.@k == '1xx' && l[0].@k.length() === 0");
}
#[test]
fn bare_assignment_without_holder_throws_reference_error_before_rhs() {
assert_eq!(thrown_name("@a = 1"), "ReferenceError");
assert_eq!(thrown_name("with ({ a: 1 }) { @a = 1 }"), "ReferenceError");
assert_eq!(thrown_name("with (<x/>) { @a = 1 }"), "ReferenceError");
assert_eq!(thrown_name("with (<x/>) { @a += 1 }"), "ReferenceError");
assert_eq!(thrown_name("with (<x/>) { @a++ }"), "ReferenceError");
assert_eq!(thrown_name("var ns = new Namespace('u'); with (<x><c/></x>) { ns::c = 1 }"), "ReferenceError");
truth("var n = 0; var e = ''; try { with (<x/>) { @a = (n++, 1); } } catch (err) { e = err.name; } e === 'ReferenceError' && n === 0");
truth(
"var b = 'g'; var x = <x/>; var e = ''; try { with (x) { @b = 'w'; } } catch (err) { e = err.name; } \
e === 'ReferenceError' && b === 'g' && x.@b.length() === 0 && x.*.length() === 0",
);
}
#[test]
fn bare_name_read_without_holder_throws_reference_error() {
assert_eq!(thrown_name("with (<x/>) { @a }"), "ReferenceError");
assert_eq!(thrown_name("var l = <><i id='1'/><i/></>; l.(@id == '1')"), "ReferenceError");
truth("var o = <o id='0'/>; var l = <><i id='1'/><i/></>; var r; with (o) { r = l.(@id == '1'); } r.length() === 1");
}
#[test]
fn bare_scope_compound_and_updates_resolve_once() {
truth("var n = 0; var x = <a t='1'/>; with (x) { @[(n++, 't')] += 1; } n === 1 && x.@t == '11'");
truth("var n = 0; var x = <a t='1'/>; with (x) { @[(n++, 't')]++; } n === 1 && x.@t == '2'");
truth("var x = <a t='1'/>; var r; with (x) { r = ++@t; } r === 2 && x.@t == '2'");
truth("var x = <a t='1'/>; var r; with (x) { r = @t++; } r === 1 && x.@t == '2'");
truth("var x = <a t='5'/>; var r; with (x) { r = --@t; } r === 4 && x.@t == '4'");
truth("var x = <a t='5'/>; var r; with (x) { r = @t--; } r === 5 && x.@t == '4'");
}
#[test]
fn bare_scope_delete_removes_attribute() {
truth("var x = <a t='1' u='2'/>; var r; with (x) { r = delete @t; } r === true && x.@t.length() === 0 && x.@u == '2'");
truth("var x = <a><c/><d/></a>; with (x) { delete *::c; } x.c.length() === 0 && x.d.length() === 1");
assert_eq!(thrown_name("with (<a/>) { delete @t }"), "ReferenceError");
}
#[test]
fn bare_scope_for_targets_assign_each_iteration() {
truth("var x = <a k=''/>; var s = ''; with (x) { for (@k in { p: 1, q: 2 }) s += @k; } s === 'pq' && x.@k == 'q'");
truth("var x = <a k=''/>; var s = ''; with (x) { for each (@k in [3, 4]) s += @k; } s === '34' && x.@k == '4'");
assert_eq!(thrown_name("with (<a/>) { for (@k in { p: 1 }); }"), "ReferenceError");
}
#[test]
fn for_each_evaluates_its_target_before_reading_the_value() {
truth("var o = { p: 1 }; var t = {}; for each ((o.p = 2, t).v in o); t.v === 2");
truth("var o = { p: 1 }; var t = {}; for each (t[(o.p = 3, 'w')] in o); t.w === 3");
truth("var x = <a k=''/>; var o = { p: 1 }; with (x) { for each (@[(o.p = 2, 'k')] in o); } x.@k == '2'");
truth("var o = { p: 1, q: 2 }; var s = ''; for each (var v in o) s += v; var t; for each (t in o) s += t; s === '1212' && t === 2");
}
#[test]
fn bare_scope_targets_need_e4x_option() {
for src in ["@a = 1", "ns::a = 1", "@a += 1", "++@a", "@a--", "for (@a in o);", "for each (@a in o);", "\"use strict\"; @a = 1"] {
assert!(parse(src, &Options::default()).is_err(), "{src}");
assert!(parse(src, &e4x()).is_ok(), "{src}");
}
truth("'use strict'; var l = <><i b='1'/></>; l.(@b = '2', true); l[0].@b == '2'");
}
#[test]
fn a_bracket_key_converts_to_a_string_before_it_names_a_child() {
truth("var x = <a><true>1</true></a>; x[true] == '1' && (true in x) && !(false in x)");
+46 -24
View File
@@ -56,6 +56,24 @@ fn s<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
p.get(k).and_then(Value::as_str)
}
/// An optional param read with `read`: none when it is omitted or null, else an error naming the
/// key when `read` gets nothing from its value.
fn opt<T>(p: &Value, k: &str, read: impl Fn(&Value) -> Option<T>, what: &str) -> Result<Option<T>, String> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(v) => read(v).map(Some).ok_or_else(|| format!("`{k}` must be {what}")),
}
}
fn opt_bool(p: &Value, k: &str) -> Result<Option<bool>, String> {
opt(p, k, Value::as_bool, "true or false")
}
/// A pointer packet's `mods`: none when omitted or null, else an object of booleans.
fn packet_mods(p: &Value) -> Result<Option<Mods>, String> {
opt(p, "mods", |m| m.as_object().and_then(|_| serde_json::from_value(m.clone()).ok()), "an object of true or false values")
}
pub(crate) fn pointer_kind(k: &str) -> Option<PointerKind> {
Some(match k {
"down" => PointerKind::Down,
@@ -210,28 +228,30 @@ impl Headless {
fn pointer(&mut self, p: &Value) -> Result<Value, String> {
let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?;
let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
let base = packet_mods(p)?.unwrap_or_default();
let default = PointerEvent::json_backquote(p, false)?;
let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::<Result<Vec<_>, _>>()?;
// Every event is read before any is sent, so a malformed packet sends none of them.
let read = events
.iter()
.zip(held)
.map(|(e, backquote)| {
let mods = packet_mods(e)?.unwrap_or(base);
let kind = s(e, "kind").unwrap_or("");
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
PointerEvent::json_check(e)?;
if s(e, "space") == Some("screen") {
return Err("screen-space pointer events need the desktop app; use document coordinates".to_string());
}
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
Ok((e, kind, Point::new(x, y), mods, backquote))
})
.collect::<Result<Vec<_>, String>>()?;
self.ensure_document();
let mut requests = vec![];
for (e, backquote) in events.iter().zip(held) {
let kind = s(e, "kind").unwrap_or("");
let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?;
if s(e, "space") == Some("screen") {
return Err("screen-space pointer events need the desktop app; use document coordinates".into());
}
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base);
let ev = PointerEvent {
kind,
pos: Point::new(x, y),
mods,
backquote,
pressure: PointerEvent::json_pressure(e),
pen: PointerEvent::json_pen(e),
};
for (e, kind, pos, mods, backquote) in read {
let ev = PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen: PointerEvent::json_pen(e) };
let reqs = self.session.pointer(&ev, self.view).map_err(|e| e.to_string())?;
self.apply_ui_requests(reqs, &mut requests)?;
// With no frames to show the highlight or apply an edit in later, each event waits for
@@ -253,8 +273,8 @@ impl Headless {
fn key(&mut self, p: &Value) -> Result<Value, String> {
let key = s(p, "key").ok_or("missing `key`")?;
let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
let mods = Mods { shift: b("shift"), alt: b("alt"), cmd: b("cmd"), ctrl: b("ctrl"), ..Mods::default() };
let b = |n: &str| opt_bool(p, n).map(|on| on.unwrap_or(false));
let mods = Mods { shift: b("shift")?, alt: b("alt")?, cmd: b("cmd")?, ctrl: b("ctrl")?, ..Mods::default() };
// A letter reaches the tool only when the tool claims it without Cmd, Ctrl or Alt (E while
// a selection marquee is dragged); otherwise it is a shortcut.
let mut tk = tool_key(key);
@@ -296,16 +316,18 @@ impl Headless {
}
fn render(&mut self, p: &Value) -> Result<Value, String> {
let idx = opt(p, "artboard", |v| v.as_u64().and_then(|i| usize::try_from(i).ok()), "a whole number of 0 or more")?.unwrap_or(0);
let scale = opt(p, "scale", Value::as_f64, "a number")?.unwrap_or(1.0).clamp(0.01, 16.0);
let trace_views = opt_bool(p, "traceViews")? == Some(true);
let data = opt_bool(p, "data")? == Some(true);
let st = self.session.active().ok_or("no document")?;
let doc = st.doc.clone();
let idx = p.get("artboard").and_then(Value::as_u64).unwrap_or(0) as usize;
let r = doc.artboards.get(idx).map(|a| a.rect).ok_or("no such artboard")?;
let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.01, 16.0);
vectorcraft_render::raster_size(r, scale)?;
// Rendered with the options of a PNG export on white, so its pixels are the exported file's.
// `traceViews: true` draws Image Trace objects as their View shows them, as the canvas does.
let mut opts = RasterExportOptions { background: Some([255; 3]), ..Default::default() }.render_options(RasterFormat::Png);
opts.trace_views = p.get("traceViews").and_then(Value::as_bool) == Some(true);
opts.trace_views = trace_views;
let img = self.renderer.render_region_with(&doc, r, scale, &opts);
// A cancelled render stops drawing: the picture is not whole and is not written.
vectorcraft_engine::cancel::check().map_err(|e| e.to_string())?;
@@ -317,7 +339,7 @@ impl Headless {
vectorcraft_format::write_atomic(std::path::Path::new(path), &png).map_err(|e| format!("write {path}: {e}"))?;
out["path"] = json!(path);
// `data: true` asks for the image as well as the file.
if p.get("data").and_then(Value::as_bool) == Some(true) {
if data {
out["pngBase64"] = json!(vectorcraft_format::base64_encode(&png));
}
}
+38
View File
@@ -1452,6 +1452,44 @@ fn headless_backend_methods() {
assert!(h.call("ui.resize", json!({})).is_err());
}
/// The headless key, pointer and screenshot calls refuse a value of the wrong type and change
/// nothing; omitting it or giving null keeps its default.
#[test]
fn headless_methods_refuse_params_of_the_wrong_type() {
let mut h = Headless::new();
h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 200}})).unwrap();
h.call("ui.tool.select", json!({"tool": "rectangle"})).unwrap();
let before = h.call("document.json", json!({})).unwrap();
let drag = |mods: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60, "mods": mods}, {"kind": "up", "x": 60, "y": 60}]});
let after_rect = |last: Value| json!({"events": [{"kind": "down", "x": 10, "y": 10}, {"kind": "drag", "x": 60, "y": 60}, {"kind": "up", "x": 60, "y": 60}, last]});
for (method, params, key) in [
("ui.render", json!({"artboard": "0"}), "artboard"),
("ui.render", json!({"scale": "2"}), "scale"),
("ui.render", json!({"traceViews": 1}), "traceViews"),
("ui.screenshot", json!({"data": "yes", "path": "x.png"}), "data"),
("ui.key", json!({"key": "Delete", "shift": "true"}), "shift"),
("ui.pointer", drag(json!({"shift": "yes"})), "mods"),
("ui.pointer", json!({"mods": 1, "events": []}), "mods"),
("ui.pointer", drag(json!([true])), "mods"),
// A whole rectangle comes before the malformed event, and none of it is drawn.
("ui.pointer", after_rect(json!({"kind": "move", "x": "bad", "y": 0})), "x"),
("ui.pointer", after_rect(json!({"kind": "wiggle", "x": 0, "y": 0})), "wiggle"),
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "pressure": "bad"})), "pressure"),
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "holdMs": true})), "holdMs"),
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "tiltX": "5"})), "tiltX"),
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "rotation": [0]})), "rotation"),
("ui.pointer", after_rect(json!({"kind": "move", "x": 1, "y": 1, "space": "screeen"})), "space"),
] {
let e = h.call(method, params.clone()).unwrap_err();
assert!(e.contains(&format!("`{key}`")), "{method} {params}: {e}");
}
assert_eq!(h.call("document.json", json!({})).unwrap(), before, "a refused call changes nothing");
let r = h.call("ui.render", json!({"artboard": null, "scale": null, "traceViews": null})).unwrap();
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(300), Some(200)));
h.call("ui.pointer", drag(Value::Null)).unwrap();
assert_ne!(h.call("document.json", json!({})).unwrap(), before, "null mods keep the packet's");
}
// ---------- workflow tools ----------
fn id_of(result: &Value) -> u64 {
+1 -1
View File
@@ -259,7 +259,7 @@ pub fn tool_definitions() -> Vec<Value> {
"radius1": num("Star outer radius"),
"radius2": num("Star inner radius"),
"points": {"type": "integer", "minimum": 3, "description": "Star points (default 5)"},
"rotation": num("Rotation in degrees clockwise (polygon/star; 0: a corner or point straight up)"),
"rotation": num("Rotation in degrees clockwise about the centre (rectangle/ellipse: 0 upright; polygon/star: 0 a corner or point straight up)"),
"x1": num("Line start x"),
"y1": num("Line start y"),
"x2": num("Line end x"),
+8 -2
View File
@@ -748,6 +748,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{} open the Safe Mode dialog (dialog `safeMode`): whether VectorCraft is in Safe Mode, and the disabled plug-ins, each with Enable on Re-launch (engine: plugin.setEnabled). Closing it leaves Safe Mode as it is; Safe Mode is chosen at launch (--safe-mode, or the choice after a launch that stopped while a plug-in was loading, dialog `pluginStopped`)",
),
(
"help.copyTroubleshootingInfo",
"Copy Troubleshooting Info",
"",
"{} put text for a bug report on the clipboard: the version, and in the desktop app the platform, the window system, the graphics processor, the commands and frame times of the last few frames, and the hang reports of this session and the session before (no document contents or file paths) → {chars}",
),
("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"),
(
"ui.swatchOptions",
@@ -1486,7 +1492,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"css.exportFile",
"Export CSS…",
"",
"{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}",
"{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first and how many there are, and hovering the message lists up to 30 of them, fewer when the window is small, with how many were left out)}",
),
(
"file.print",
@@ -1523,7 +1529,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.installPlugin",
"Install Plug-in…",
"",
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing",
"{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)",
),
(
"plugin.cancelRuns",
+35 -12
View File
@@ -211,23 +211,46 @@ pub(crate) fn verify(pdf: &[u8], standard: Standard) -> Result<(), PdfError> {
Ok(())
}
/// `pdf` without its streams' data (dictionaries and the rest of the syntax), so that what is
/// looked for there isn't found in image or font bytes.
/// `pdf` without its streams' data, the text of its literal strings and its comments (dictionaries
/// and the rest of the syntax), so that what is looked for there isn't found in image or font
/// bytes, or in a string such as the file identifier, whose base64 hash can hold `/BM`.
fn without_streams(pdf: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(pdf.len().min(1 << 20));
let mut at = 0;
while let Some(s) = find(pdf, b"stream", at) {
let data = s + b"stream".len();
// `endstream` itself, or a stream keyword that isn't one (inside a name or string).
if (s >= 3 && pdf.get(s - 3..s) == Some(b"end")) || !pdf.get(data).is_some_and(|b| matches!(b, b'\r' | b'\n')) {
out.extend_from_slice(pdf.get(at..data).unwrap_or_default());
at = data;
continue;
while let Some(&b) = pdf.get(at) {
match b {
// A literal string: parentheses nest, and a backslash escapes the next byte.
b'(' => {
out.extend_from_slice(b"()");
let mut depth = 0usize;
at += 1;
while let Some(&c) = pdf.get(at) {
at += 1;
match c {
b'\\' => at += 1,
b'(' => depth += 1,
b')' if depth == 0 => break,
b')' => depth -= 1,
_ => {}
}
}
}
// A comment, to the end of its line.
b'%' => at += pdf.get(at..).unwrap_or_default().iter().take_while(|c| !matches!(c, b'\r' | b'\n')).count(),
// A stream keyword (not `endstream`, and followed by its end of line): its data is left out.
b's' if pdf.get(at..at + 6) == Some(b"stream")
&& !(at >= 3 && pdf.get(at - 3..at) == Some(b"end"))
&& pdf.get(at + 6).is_some_and(|c| matches!(c, b'\r' | b'\n')) =>
{
out.extend_from_slice(b"stream");
at = find(pdf, b"endstream", at + 6).unwrap_or(pdf.len());
}
_ => {
out.push(b);
at += 1;
}
}
out.extend_from_slice(pdf.get(at..data).unwrap_or_default());
at = find(pdf, b"endstream", data).unwrap_or(pdf.len());
}
out.extend_from_slice(pdf.get(at..).unwrap_or_default());
out
}
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more