Merge main into feat/dynamic-text-release-path

This commit is contained in:
dotCooCoo committed 2026-11-11 23:31:01 -08:00
commit 2c6bd2826b
153 files changed
+6944 -530

No files matched your search

+1
View File
@@ -137,6 +137,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,
+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,
}
}
+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);
+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))?;
+25 -4
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"));
}
@@ -1092,6 +1094,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 +1125,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. 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 +1179,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
),
@@ -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",
+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
),
+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);
}
}
}
@@ -676,6 +676,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()
+165 -18
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> {
@@ -416,6 +424,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 +475,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 +548,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 +644,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 +680,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 +847,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 +909,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 +990,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 +1051,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 +1082,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 +1094,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 +1105,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 +1122,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 +1191,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 +1211,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 +1235,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 {
@@ -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);
-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>,
+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
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,
+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}");
}
}
+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"));
}
+32
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]
+212 -5
View File
@@ -1820,11 +1820,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 +1856,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 +1887,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 +2301,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);
}
+337
View File
@@ -682,6 +682,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()));
+97 -9
View File
@@ -425,8 +425,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 +448,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 +466,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 +638,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()));
+33
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();
@@ -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");
}
+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})),
+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)
+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]
+21 -2
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
@@ -617,6 +618,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) {
@@ -926,11 +943,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"),
}
@@ -2401,6 +2419,7 @@ impl Interp {
};
let strict = self.strict();
self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?;
self.prepare_source(s.len())?;
let units = s.flat();
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))?;
+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)),
}
+2 -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
+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"),
+7 -1
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",
@@ -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
}
+20
View File
@@ -224,3 +224,23 @@ fn verify_finds_what_each_standard_forbids() {
assert!(matches!(verify(&file(font), Standard::PdfX4), Err(PdfError::Unsupported(m)) if m.contains("fonts")));
assert!(verify(&file("<</Type/FontDescriptor/FontFile2 4 0 R>>"), Standard::PdfX4).is_ok());
}
/// Names inside a string or a comment are text, not syntax: a file identifier, whose base64 hash
/// can hold `/BM` or `/Lab`, does not make a file break its standard.
#[test]
fn verify_skips_names_in_strings_and_comments() {
use crate::pdfx::verify;
let file = |body: &str| format!("%PDF-1.3\n%/BM/Multiply\n1 0 obj\n{body}\nendobj\n").into_bytes();
for ok in [
"<</Size 2/ID[(q/BM+Zt1kR0x/Lab=) (q/BM+Zt1kR0x/Lab=)]>>",
"<</Title(a\\)/SMask 5 0 R)/Subject(a(b)/ca 0.5)>>",
"<</Title(stream\n/BM/Multiply\nendstream)>>",
] {
for standard in [Standard::PdfX1a, Standard::PdfX3] {
assert!(verify(&file(ok), standard).is_ok(), "{standard:?}: {ok}");
}
}
// A name after a string is still read.
let after = "<</Title(a(b)c)/BM/Multiply>>";
assert!(matches!(verify(&file(after), Standard::PdfX3), Err(PdfError::Unsupported(m)) if m.contains("blend modes")));
}
+73 -10
View File
@@ -736,10 +736,41 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
/// the list), and a list is refused at its first entry past [`MAX_COMMANDS`].
/// the list), and a list is refused at its first entry past [`MAX_COMMANDS`]. A `commands` value,
/// an entry, an `id` or a `label` of the wrong type gets a fixed message of this function's own.
fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<Command>, D::Error> {
use serde::de::{Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor};
/// A visitor's methods for a boolean, a number and a string: each is the error its type's
/// `wrong()` gives.
macro_rules! refuse_scalars {
() => {
fn visit_bool<E: serde::de::Error>(self, _: bool) -> std::result::Result<Self::Value, E> {
Err(E::custom(self.wrong()))
}
fn visit_i64<E: serde::de::Error>(self, _: i64) -> std::result::Result<Self::Value, E> {
Err(E::custom(self.wrong()))
}
fn visit_u64<E: serde::de::Error>(self, _: u64) -> std::result::Result<Self::Value, E> {
Err(E::custom(self.wrong()))
}
fn visit_f64<E: serde::de::Error>(self, _: f64) -> std::result::Result<Self::Value, E> {
Err(E::custom(self.wrong()))
}
fn visit_str<E: serde::de::Error>(self, _: &str) -> std::result::Result<Self::Value, E> {
Err(E::custom(self.wrong()))
}
};
}
/// A string field of an entry: anything else is the error "`{key}` must be a string".
fn string_field<'de, A: MapAccess<'de>>(map: &mut A, key: &str) -> std::result::Result<std::result::Result<String, String>, A::Error> {
Ok(match map.next_value::<Value>()? {
Value::String(s) => Ok(s),
_ => Err(format!("`{key}` must be a string")),
})
}
/// A command's `params`, read in declaration order.
struct Params(Vec<(String, Param)>);
impl<'de> Deserialize<'de> for Params {
@@ -750,6 +781,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
/// The entry at place `.0` in the list.
struct Entry(usize);
impl Entry {
fn wrong(&self) -> String {
format!("command {} must be an object with an `id` and a `label`", command_name(self.0, ""))
}
}
impl<'de> serde::de::DeserializeSeed<'de> for Entry {
type Value = Command;
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> std::result::Result<Command, D::Error> {
@@ -759,21 +795,29 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
impl<'de> Visitor<'de> for Entry {
type Value = Command;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "command [{}] as {{id, label, params?}}", self.0)
f.write_str(&self.wrong())
}
refuse_scalars!();
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Command, E> {
Err(E::custom(self.wrong()))
}
fn visit_seq<A: SeqAccess<'de>>(self, _: A) -> std::result::Result<Command, A::Error> {
Err(A::Error::custom(self.wrong()))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
};
while let Some(key) = map.next_key::<String>().map_err(|e| named(&id, &e))? {
// A key and an ignored value can only fail as JSON syntax, which keeps serde's own error.
while let Some(key) = map.next_key::<String>()? {
let repeated = match key.as_str() {
"id" if id.is_none() => {
id = Some(map.next_value().map_err(|e| named(&id, &e))?);
id = Some(string_field(&mut map, "id")?.map_err(|e| named(&id, &e))?);
false
}
"label" if label.is_none() => {
label = Some(map.next_value().map_err(|e| named(&id, &e))?);
label = Some(string_field(&mut map, "label")?.map_err(|e| named(&id, &e))?);
false
}
"params" if params.is_none() => {
@@ -782,7 +826,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
}
"id" | "label" | "params" => true,
_ => {
map.next_value::<IgnoredAny>().map_err(|e| named(&id, &e))?;
map.next_value::<IgnoredAny>()?;
false
}
};
@@ -801,16 +845,22 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
}
struct List;
impl List {
fn wrong(&self) -> &'static str {
"`commands` must be a list of commands, each with an `id` and a `label`"
}
}
impl<'de> Visitor<'de> for List {
type Value = Vec<Command>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("`commands` as a list of {id, label, params?}")
f.write_str(self.wrong())
}
refuse_scalars!();
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
Ok(Vec::new())
}
fn visit_map<A: MapAccess<'de>>(self, _: A) -> std::result::Result<Self::Value, A::Error> {
Err(A::Error::custom("`commands` must be a list of {id, label, params?}"))
Err(A::Error::custom(self.wrong()))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error> {
let mut out = Vec::new();
@@ -1215,14 +1265,27 @@ mod tests {
r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"r":{"type":"bool"},"r":{"type":"int"}}}]}"#,
"command `x`: parameter `r` is declared twice",
),
(r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0]"),
(r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#, "must be a list"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0] must be an object with an `id` and a `label`"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A"},null]}"#, "command [1] must be an object"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[["x"]]}"#, "command [0] must be an object"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":1,"label":"A"}]}"#, "command [0]: `id` must be a string"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":true}]}"#, "command `x`: `label` must be a string"),
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","id":"y","label":"A"}]}"#, "command `x`: duplicate field `id`"),
(
r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#,
"`commands` must be a list of commands, each with an `id` and a `label`",
),
(r#"{"id":"a","name":"x","kind":"filter","commands":"x"}"#, "`commands` must be a list of commands"),
(r#"{"id":"a","name":"x","kind":"filter","commands":7}"#, "`commands` must be a list of commands"),
(r#"{"id":"a","name":"x","kind":"filter","commands":true}"#, "`commands` must be a list of commands"),
(r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"commands":[{"id":"x","label":"A"}]}"#, "only a filter or a live effect"),
(r#"{"id":"a","name":"x","kind":"filter","budget":"heavy","commands":[{"id":"x","label":"A"}]}"#, "heavy filter"),
(too_many.as_str(), "at most 32 `commands`"),
] {
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
assert!(e.contains(says), "{bad}: {e}");
// The message is the manifest reader's own, with serde's place in the manifest once.
assert!(!e.contains("invalid type") && !e.contains("expected") && e.matches(" at line ").count() <= 1, "{bad}: {e}");
}
let long_id = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"{}","label":"A"}}]}}"#, "c".repeat(MAX_COMMAND_ID + 1));
assert!(Manifest::parse(long_id.as_bytes()).is_err());
+2 -2
View File
@@ -37,8 +37,8 @@ use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache};
use live_paint::LpHover;
use live_paint::lp_color;
pub use live_paint::{
LP_BUCKET_EDGE_FRACTION, LP_BUCKET_WIDTH, LP_BUCKET_WIDTH_RANGE, LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE, LivePaintBucketTool,
LivePaintSelectionTool,
LP_BUCKET_EDGE_FRACTION, LP_BUCKET_WIDTH, LP_BUCKET_WIDTH_RANGE, LP_FILL_CHUNK_POINTS, LP_SELECT_WIDTH, LP_SELECT_WIDTH_RANGE,
LivePaintBucketTool, LivePaintSelectionTool,
};
pub use lookup::{
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, SOURCES_NAME, builder_members, drawn_outlines, edge_near, edges, face_at, faces,
+70 -3
View File
@@ -114,7 +114,8 @@ enum LpPaint {
}
/// Live Paint Bucket: by default, a click fills the face under the cursor with the current fill,
/// and Shift-click paints the nearest edge with the current stroke. Alt-click samples a fill or
/// and dragging fills the faces crossed in that group as one undo step (Escape cancels).
/// Shift-click paints the nearest edge with the current stroke. Alt-click samples a fill or
/// stroke into the paint defaults; Alt+Shift-click samples only the color under the pointer.
/// Clicking selected ordinary paths without Alt makes them a Live Paint group first. Its Tool
/// Options (double-click the tool) are `paintFills` (on) and `paintStrokes` (off), `highlight`
@@ -130,6 +131,8 @@ pub struct LivePaintBucketTool {
pub(super) hover: LpHover,
/// Where the pointer last moved, and whether Shift and Alt were held.
at: Option<(Point, bool, bool)>,
/// The fill command and polyline previewed from the press's snapshot.
fill_drag: Option<(Value, Vec<Vec<Point>>)>,
fills: bool,
strokes: bool,
highlight: bool,
@@ -137,12 +140,16 @@ pub struct LivePaintBucketTool {
width: f64,
}
/// Maximum points in one Live Paint fill path chunk.
pub const LP_FILL_CHUNK_POINTS: usize = 4096;
impl Default for LivePaintBucketTool {
fn default() -> Self {
Self {
cache: RegionCache::live_paint(),
hover: LpHover::None,
at: None,
fill_drag: None,
fills: true,
strokes: false,
highlight: true,
@@ -153,6 +160,36 @@ impl Default for LivePaintBucketTool {
}
impl LivePaintBucketTool {
fn begin_fill(&mut self, params: Value, p: Point) -> Vec<Action> {
self.fill_drag = Some((params.clone(), vec![vec![p]]));
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), params)]
}
fn drag_fill(&mut self, p: Point) -> Vec<Action> {
let Some((params, chunks)) = &mut self.fill_drag else { return vec![] };
let Some(points) = chunks.last_mut() else { return vec![] };
let Some(&last) = points.last() else { return vec![] };
if last == p {
return vec![];
}
if points.len() == LP_FILL_CHUNK_POINTS {
// Share the boundary point so no segment is lost between chunks.
chunks.push(vec![last, p]);
} else {
points.push(p);
}
let mut params = params.clone();
let mut chunks = chunks.iter().map(|chunk| json!(chunk.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>()));
if let Some(first) = chunks.next() {
params["points"] = first;
}
let continuation: Vec<_> = chunks.collect();
if !continuation.is_empty() {
params["continuation"] = Value::Array(continuation);
}
vec![Action::Preview("livePaint.fill".into(), params)]
}
/// What a click paints, Shift held or not. Shift switches Paint Fills alone to Paint Strokes
/// alone and back, and switches both to Paint Fills alone.
fn paints(&self, shift: bool) -> LpPaint {
@@ -191,6 +228,12 @@ impl Tool for LivePaintBucketTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
// A second press finishes the preceding click, including callers without a release.
if ev.kind == PointerKind::Down && self.fill_drag.take().is_some() {
let mut acts = vec![Action::Commit];
acts.extend(self.pointer(cx, ev));
return acts;
}
match ev.kind {
PointerKind::Move => {
self.at = Some((p, ev.mods.shift, ev.mods.alt));
@@ -232,18 +275,42 @@ impl Tool for LivePaintBucketTool {
return vec![];
}
if let Some(g) = live_paint_at(cx.doc, p) {
return vec![Action::Exec("livePaint.fill".into(), json!({ "group": g.0, "point": point }))];
return self.begin_fill(json!({ "group": g.0, "point": point }), p);
}
if self.cache.at(cx, p).is_some() {
let roots = sorted_roots(cx.doc, &cx.selection.objects);
return vec![Action::Exec("livePaint.fill".into(), json!({ "ids": json_ids(&roots), "point": point }))];
return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p);
}
vec![]
}
PointerKind::Drag => self.drag_fill(p),
PointerKind::Up => {
let mut acts = self.drag_fill(p);
if self.fill_drag.take().is_some() {
acts.push(Action::Commit);
}
acts
}
_ => vec![],
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape && self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] }
}
fn busy(&self) -> bool {
self.fill_drag.is_some()
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
key == ToolKey::Escape && self.busy()
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] }
}
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32)
}
+45 -9
View File
@@ -1045,6 +1045,25 @@ fn live_square(d: &mut Document, r: Rect) -> (NodeId, [NodeId; 4]) {
(gid, ids)
}
#[test]
fn bucket_long_drag_keeps_turns_and_release_after_the_point_limit() {
let (d, gid, ..) = live_group_doc();
let s = Selection::default();
let paint = paint();
let cx = cx(&d, &s, &paint);
let mut t = LivePaintBucketTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0));
for i in 1..4096 {
t.pointer(&cx, &ev(PointerKind::Drag, 25.0 + f64::from(i) / 10000.0, 25.0));
}
t.pointer(&cx, &ev(PointerKind::Drag, 25.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 100.0));
let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0));
let [Action::Preview(id, params), Action::Commit] = acts.as_slice() else { panic!("release must extend the drag before committing") };
assert_eq!(id, "livePaint.fill");
assert_eq!(params["group"], gid.0);
}
#[test]
fn bucket_click_fills_face_and_shift_click_strokes_edge() {
let (d, gid, f2, _e) = live_group_doc();
@@ -1058,9 +1077,10 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
let ov = t.overlays(&cx);
assert!(matches!(&ov[0], Overlay::Path { color: HIGHLIGHT_RED, .. }));
let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0));
let Action::Exec(id, v) = &acts[0] else { panic!() };
let [Action::Begin(_), Action::Preview(id, v)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!(id, "livePaint.fill");
assert_eq!(v["group"], gid.0);
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)), vec![Action::Commit]);
let shift = Mods { shift: true, ..Default::default() };
let acts = t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift));
let Action::Exec(id, _) = &acts[0] else { panic!() };
@@ -1074,9 +1094,15 @@ fn bucket_options_choose_what_a_click_paints() {
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let fill = |x: f64| vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))];
let fill = |x: f64| {
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))]
};
let stroke = |x: f64| vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 }))];
let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m));
let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| {
let acts = t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m));
t.pointer(&cx, &ev(PointerKind::Up, x, 25.0).with_mods(m));
acts
};
let hovered = |t: &mut LivePaintBucketTool, x: f64, m: Mods| {
t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m));
match t.overlays(&cx).as_slice() {
@@ -1162,7 +1188,9 @@ fn bucket_options_set_the_highlight() {
// Highlight off: nothing is highlighted, and a click still paints.
t.set_option("highlight", &json!(false));
assert_eq!(highlight(&mut t), None);
assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)).len(), 1);
let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0));
assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "livePaint.fill"));
t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0));
t.set_option("highlight", &json!(true));
assert!(highlight(&mut t).is_some());
}
@@ -1326,7 +1354,7 @@ fn bucket_on_plain_selection_makes_live_paint() {
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0));
let Action::Exec(id, v) = &acts[0] else { panic!() };
let [Action::Begin(_), Action::Preview(id, v)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!(id, "livePaint.fill");
assert_eq!(v["ids"], json!([a.0, b.0]));
}
@@ -1344,7 +1372,13 @@ fn bucket_rebuilds_its_map_for_a_new_revision_at_the_same_address() {
d = two_rects_at(300.0).0;
let cx2 = ToolContext { revision: (1, 2), ..cx(&d, &s, &p) };
let acts = t.pointer(&cx2, &ev(PointerKind::Down, 375.0, 50.0));
assert_eq!(acts, vec![Action::Exec("livePaint.fill".into(), json!({ "ids": [a.0, b.0], "point": [375.0, 50.0] }))]);
assert_eq!(
acts,
vec![
Action::Begin("Live Paint Bucket".into()),
Action::Preview("livePaint.fill".into(), json!({ "ids": [a.0, b.0], "point": [375.0, 50.0] }))
]
);
}
#[test]
@@ -1357,7 +1391,8 @@ fn bucket_keeps_its_map_while_the_document_is_unchanged() {
let cx1 = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) };
t.pointer(&cx1, &ev(PointerKind::Move, 75.0, 50.0));
let acts = t.pointer(&cx1, &ev(PointerKind::Down, 75.0, 50.0));
assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "livePaint.fill"), "{acts:?}");
assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "livePaint.fill"), "{acts:?}");
t.pointer(&cx1, &ev(PointerKind::Up, 75.0, 50.0));
// The fill left the document as it was: the map still fits it.
t.pointer(&cx1, &ev(PointerKind::Move, 25.0, 50.0));
assert_eq!(t.cache.builds, 1, "a hover after a fill that changed nothing");
@@ -1745,8 +1780,9 @@ fn live_paint_tools_skip_hidden_faces() {
let mut bucket = LivePaintBucketTool::default();
bucket.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
assert_eq!(part(&bucket.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
let fill = Action::Exec("livePaint.fill".into(), json!({ "group": back.0, "point": [75.0, 50.0] }));
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)), vec![fill]);
let fill = Action::Preview("livePaint.fill".into(), json!({ "group": back.0, "point": [75.0, 50.0] }));
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)), vec![Action::Begin("Live Paint Bucket".into()), fill]);
bucket.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0));
let mut sel = LivePaintSelectionTool::default();
sel.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
assert_eq!(part(&sel.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
+34
View File
@@ -109,6 +109,19 @@ impl PointerEvent {
pub fn json_backquote(v: &Value, default: bool) -> Result<bool, String> {
v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned()))
}
/// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`,
/// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or
/// `screen`. A key that is absent or null keeps its default.
pub fn json_check(e: &Value) -> Result<(), String> {
let given = |k: &str| e.get(k).filter(|v| !v.is_null());
if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) {
return Err(format!("`{k}` must be a number"));
}
if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) {
return Err("`space` must be doc or screen".to_owned());
}
Ok(())
}
}
#[cfg(test)]
@@ -135,6 +148,27 @@ mod tests {
assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}");
}
}
#[test]
fn json_check_refuses_pen_values_and_spaces_of_the_wrong_type() {
use serde_json::json;
for ok in [
json!({}),
json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}),
json!({"pressure": null, "space": null}),
json!({"space": "doc"}),
] {
assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}");
}
for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] {
for bad in [json!("1"), json!(true), json!([1])] {
assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}");
}
}
for bad in [json!("screeen"), json!(true), json!(1)] {
assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}");
}
}
}
/// Keys tools care about.
+1
View File
@@ -135,6 +135,7 @@ impl VectorcraftApp {
last_window_title: String::new(),
fullscreen_for_mode: false,
graphics_adapter: None,
beacon: &crate::hang_beacon::BEACON,
place: Default::default(),
system_paste: false,
clipboard_image_request: None,
+1
View File
@@ -73,6 +73,7 @@ fn substitute_warnings_follow_current_font_inventory() {
impl VectorcraftApp {
/// Run a UI or engine command by id. The single entry point for every frontend path.
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
self.beacon.command(id);
let touch_workspace = self.session.prefs.touch_workspace;
// A file dialog it shows off the UI thread runs it again with the path picked.
let result = if self.picks.is_entry_free() {
+20 -7
View File
@@ -1,4 +1,5 @@
use super::{VectorcraftApp, io, place};
use crate::services::Inbox;
impl VectorcraftApp {
/// A file dialog is open off the UI thread (a sheet on macOS, [`picks`]): what asked for it runs
@@ -13,13 +14,25 @@ impl VectorcraftApp {
self.services.dialogs_are_sheets && self.file_dialog_open()
}
pub(super) fn drain_inbox(&mut self) {
let arrived: Vec<(String, Vec<u8>)> =
self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();
for (name, bytes) in arrived {
if let Err(e) = io::open_bytes(self, &name, &bytes, None) {
io::report_open_error(self, &name, &e);
}
pub(crate) fn drain_inbox(&mut self) {
fn take(q: Option<&Inbox>) -> Vec<(String, Vec<u8>)> {
q.map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default()
}
let answers = self.services.picked_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner())));
// The web's file picker answers for automation when automation opened it; the page's script
// is automation.
let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect();
for answer in answers.unwrap_or_default() {
let automated = self.picks.answer_web_open();
arrived.extend(answer.map(|f| (f, automated)));
}
arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true)));
for ((name, bytes), automated) in arrived {
crate::picks::as_automated(self, automated, |app| {
if let Err(e) = io::open_bytes(app, &name, &bytes, None) {
io::report_open_error(app, &name, &e);
}
});
}
place::drain(self);
}
+7
View File
@@ -36,6 +36,13 @@ impl VectorcraftApp {
self.ui.answering_control || self.synthetic_frame
}
/// Did automation ask for what is being handled now: [`Self::automation_is_acting`], or the
/// answer of a file dialog that automation opened ([`crate::picks::as_automated`]), even when a
/// person picked the file in it?
pub(crate) fn automation_asked(&self) -> bool {
self.automation_is_acting() || self.picks.automated()
}
/// Run a Help link command and open the URL it returns.
pub fn open_link(&mut self, id: &str) {
if let Ok(v) = self.run(id, serde_json::json!({}))
+5 -2
View File
@@ -2850,10 +2850,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() {
"{old_rot}° -> {new_rot}°, DPI {old_ppp} -> {new_ppp}, pixel={pixel}: {vertex:?}"
);
}
// Deliver the actual replacement and verify that it replaces the cached key.
// Deliver the actual replacement and verify that it replaces the cached key. The frame
// reports a slow render: when a parallel test makes a placed document's bitmap, the key's
// process-wide `placed` generation moves, and the next frame goes to the controlled worker
// instead of rendering over the delivered frame on this thread.
let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts);
let expected = job.key.clone();
completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap();
completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap();
frame(&mut app, size, new_ppp);
assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived");
}
+111 -40
View File
@@ -474,9 +474,24 @@ fn key_from(name: &str) -> Option<egui::Key> {
/// The modifier keys a request holds down (`cmd`, `ctrl`, `alt`, `shift`; `cmd` is Command on
/// macOS, Ctrl elsewhere).
fn modifiers(p: &Value) -> egui::Modifiers {
let b = |n: &str| p.get(n).and_then(Value::as_bool).unwrap_or(false);
egui::Modifiers { alt: b("alt"), ctrl: b("ctrl"), shift: b("shift"), mac_cmd: b("cmd") && cfg!(target_os = "macos"), command: b("cmd") }
fn modifiers(p: &Value) -> Result<egui::Modifiers, String> {
let b = |n: &str| crate::menus::opt_bool(p, n).map(|on| on.unwrap_or(false));
let cmd = b("cmd")?;
Ok(egui::Modifiers { alt: b("alt")?, ctrl: b("ctrl")?, shift: b("shift")?, mac_cmd: cmd && cfg!(target_os = "macos"), command: cmd })
}
/// An optional number param of a control request as `f32`, `default` when it is omitted or null.
fn coord(p: &Value, key: &str, default: f32) -> Result<f32, String> {
crate::menus::opt_number(p, key).map(|n| n.map_or(default, |n| n as f32))
}
/// A pointer packet's `mods`: none when omitted or null, else an object of booleans.
fn packet_mods(value: Option<&Value>) -> Result<Option<Mods>, String> {
match value {
None | Some(Value::Null) => Ok(None),
Some(m) if !m.is_object() => Err("`mods` must be an object of true or false values".to_string()),
Some(m) => serde_json::from_value(m.clone()).map(Some).map_err(|e| format!("`mods` must be an object of true or false values: {e}")),
}
}
pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
@@ -512,10 +527,13 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
"ui.pointer" => pointer_events(app, ctx, req),
"ui.key" => {
let Some(k) = s("key").and_then(key_from) else { return err("unknown or missing `key`") };
let m = match modifiers(p) {
Ok(m) => m,
Err(e) => return err(e),
};
if let Err(e) = reserve_synthetic(app, 2 + usize::from(s("text").is_some())) {
return err(e);
}
let m = modifiers(p);
app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });
// Typed text comes with the press, so it shares the key's frame and modifiers.
if let Some(t) = s("text") {
@@ -526,31 +544,39 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
ok(Value::Null)
}
"ui.move" => {
let pos = match coord(p, "x", 0.0).and_then(|x| Ok(egui::pos2(x, coord(p, "y", 0.0)?))) {
Ok(pos) => pos,
Err(e) => return err(e),
};
if let Err(e) = reserve_synthetic(app, 1) {
return err(e);
}
let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32);
app.synthetic.push(egui::Event::PointerMoved(pos));
ctx.request_repaint();
ok(Value::Null)
}
"ui.click" | "ui.drag" => synthetic_click(app, ctx, req),
"ui.wheel" => {
// Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways
// (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them.
let given =
(|| Ok::<_, String>(([coord(p, "dx", 0.0)?, coord(p, "dy", 0.0)?, coord(p, "x", 0.0)?, coord(p, "y", 0.0)?], modifiers(p)?)))();
let ([dx, dy, x, y], modifiers) = match given {
Ok(given) => given,
Err(e) => return err(e),
};
if let Err(e) = reserve_synthetic(app, 2) {
return err(e);
}
// Mouse wheel notches over screen point (x, y): `dy` up (+) or down, `dx` sideways
// (`unit: "point"` for trackpad-like points), with modifiers as `ui.click` takes them.
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
let unit = if s("unit") == Some("point") { egui::MouseWheelUnit::Point } else { egui::MouseWheelUnit::Line };
// Notches, not a flood: a turn stays within what a real wheel sends.
let delta = egui::vec2(f("dx"), f("dy")).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0));
app.synthetic.push(egui::Event::PointerMoved(egui::pos2(f("x"), f("y"))));
let delta = egui::vec2(dx, dy).clamp(egui::Vec2::splat(-100.0), egui::Vec2::splat(100.0));
app.synthetic.push(egui::Event::PointerMoved(egui::pos2(x, y)));
app.synthetic.push(egui::Event::MouseWheel {
unit,
delta,
phase: egui::TouchPhase::Move,
modifiers: modifiers(p),
modifiers,
source: egui::MouseWheelSource::Unknown,
});
ctx.request_repaint();
@@ -615,8 +641,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
ok(Value::Null)
}
"ui.resize" => {
let w = p.get("width").and_then(Value::as_f64).unwrap_or(1440.0) as f32;
let h = p.get("height").and_then(Value::as_f64).unwrap_or(900.0) as f32;
let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) {
Ok(size) => size,
Err(e) => return err(e),
};
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h)));
ok(Value::Null)
}
@@ -629,32 +657,48 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
if let Some(Err(e)) = s("path").map(vectorcraft_engine::file_access::check_write) {
return err(e);
}
if p.get("focus").and_then(Value::as_bool).unwrap_or(true) {
let flags = crate::menus::opt_bool(p, "focus").and_then(|focus| Ok((focus, crate::menus::opt_bool(p, "data")?)));
let (focus, data) = match flags {
Ok(flags) => flags,
Err(e) => return err(e),
};
if focus.unwrap_or(true) {
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
ctx.request_repaint();
Outcome::Screenshot { path: s("path").map(str::to_string), data: p.get("data").and_then(Value::as_bool) == Some(true) }
Outcome::Screenshot { path: s("path").map(str::to_string), data: data == Some(true) }
}
"ui.render" => {
let given = (|| {
Ok::<_, String>((
crate::menus::opt_index(p, "artboard")?,
crate::menus::opt_number(p, "scale")?,
crate::menus::opt_bool(p, "traceViews")?,
crate::menus::opt_bool(p, "data")?,
))
})();
let (index, scale, trace_views, data) = match given {
Ok(given) => given,
Err(e) => return err(e),
};
let Some(st) = app.session.active() else { return err("no document") };
let doc = st.doc.clone();
// The artboard asked for (0-based, as headless), else the first.
let index = p.get("artboard").and_then(Value::as_u64).map_or(Some(0), |i| usize::try_from(i).ok());
let Some(r) = index.and_then(|i| doc.artboards.get(i)).map(|a| a.rect) else { return err("no such artboard") };
let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0);
let Some(r) = doc.artboards.get(index.unwrap_or(0)).map(|a| a.rect) else { return err("no such artboard") };
let scale = scale.unwrap_or(1.0);
if let Err(e) = vectorcraft_render::raster_size(r, scale) {
return err(e);
}
// 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 == Some(true);
let img = app.canvas.renderer.render_region_with(&doc, r, scale, &opts);
let png = match img.to_png() {
Ok(png) => png,
Err(e) => return err(e),
};
let data = p.get("data").and_then(Value::as_bool) == Some(true);
let data = data == Some(true);
match s("path") {
Some(path) => match app.services.write.as_mut() {
Some(w) => wrap(
@@ -857,7 +901,7 @@ fn rotate_view_pointer(
/// A Rotate View packet accepts only the documented boolean modifier fields.
fn validate_rotate_view_mods(value: Option<&Value>) -> Result<(), String> {
let Some(value) = value else { return Ok(()) };
let Some(value) = value.filter(|value| !value.is_null()) else { return Ok(()) };
let Some(fields) = value.as_object() else { return Err("Rotate View `mods` must be an object of booleans".into()) };
if fields.iter().any(|(key, value)| !matches!(key.as_str(), "shift" | "alt" | "cmd" | "ctrl" | "space") || !value.is_boolean()) {
return Err("Rotate View `mods` accepts only boolean shift, alt, cmd, ctrl and space".into());
@@ -906,9 +950,36 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con
if rotating && let Err(error) = validate_rotate_view_events(p, events) {
return err(error);
}
let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default();
// Every event is read before any is sent, so a malformed packet sends none of them.
let read = packet_mods(p.get("mods")).and_then(|base| {
let base = base.unwrap_or_default();
events
.iter()
.map(|e| {
let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
"down" => PointerKind::Down,
"drag" => PointerKind::Drag,
"up" => PointerKind::Up,
"move" => PointerKind::Move,
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
other => return Err(format!("unknown pointer kind `{other}`")),
};
PointerEvent::json_check(e)?;
let at = |k: &str| crate::menus::opt_number(e, k).map(|n| n.unwrap_or(0.0));
Ok((kind, at("x")?, at("y")?, packet_mods(e.get("mods"))?.unwrap_or(base)))
})
.collect::<Result<Vec<_>, String>>()
});
let read = match read {
Ok(read) => read,
Err(e) => return err(e),
};
let view = app.view_info();
let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v));
let screen = |e: &Value| e.get("space").and_then(Value::as_str) == Some("screen");
if !rotating && xf.is_none() && events.iter().any(screen) {
return err("no canvas yet");
}
let from = app.session.input_count();
let held =
PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::<Result<Vec<_>, _>>());
@@ -916,19 +987,8 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con
Ok(held) => held,
Err(e) => return err(e),
};
for (e, backquote) in events.iter().zip(held) {
let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") {
"down" => PointerKind::Down,
"drag" => PointerKind::Drag,
"up" => PointerKind::Up,
"move" => PointerKind::Move,
"doubleclick" | "dblclick" => PointerKind::DoubleClick,
other => return err(format!("unknown pointer kind `{other}`")),
};
let x = e.get("x").and_then(Value::as_f64).unwrap_or(0.0);
let y = e.get("y").and_then(Value::as_f64).unwrap_or(0.0);
let screen = e.get("space").and_then(Value::as_str) == Some("screen");
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods);
for ((e, backquote), (kind, x, y, mods)) in events.iter().zip(held).zip(read) {
let screen = screen(e);
if rotating {
if let Err(e) = rotate_view_pointer(app, kind, vectorcraft_geom::Point::new(x, y), screen, mods.shift) {
return err(e);
@@ -987,18 +1047,24 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR
let Some(events) = count.checked_mul(2).and_then(|n| n.checked_add(steps)).and_then(|n| n.checked_add(1)) else {
return err("synthetic input event count is out of range");
};
// Screen-space (egui points) pointer input through egui itself: reaches every widget.
let drag = req.method == "ui.drag";
let given = (|| {
let a = egui::pos2(coord(p, "x", 0.0)?, coord(p, "y", 0.0)?);
let end = if drag { egui::pos2(coord(p, "toX", 0.0)?, coord(p, "toY", 0.0)?) } else { a };
Ok::<_, String>((a, end, modifiers(p)?))
})();
let (a, end, modifiers) = match given {
Ok(given) => given,
Err(e) => return err(e),
};
if let Err(e) = reserve_synthetic(app, events) {
return err(e);
}
// Screen-space (egui points) pointer input through egui itself: reaches every widget.
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
let button = match s("button") {
Some("right") | Some("secondary") => egui::PointerButton::Secondary,
_ => egui::PointerButton::Primary,
};
let modifiers = modifiers(p);
let a = egui::pos2(f("x"), f("y"));
let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };
app.synthetic.push(egui::Event::PointerMoved(a));
app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
if req.method == "ui.drag" {
@@ -1020,6 +1086,11 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR
fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome {
let p = &req.params;
let s = |k: &str| p.get(k).and_then(Value::as_str);
// A flag of the wrong type is refused before anything is set.
let flags = ["rulers", "outline", "grid", "smartGuides", "boundingBox", "controlBar", "imageTracePreview"];
if let Some(e) = flags.iter().find_map(|k| crate::menus::opt_bool(p, k).err()) {
return err(e);
}
// Outline is a setting of the active document's view: without one, nothing is set.
if p.get("outline").is_some_and(Value::is_boolean) && app.session.active().is_none() {
return err("no document");
+116
View File
@@ -314,6 +314,93 @@ fn render_takes_the_artboard_asked_for() {
assert_eq!(got, size.map(Some), "{params}: {r}");
}
assert!(request("ui.render", json!({"artboard": 2}))["error"].is_string());
for (params, key) in [
(json!({"artboard": "1"}), "artboard"),
(json!({"artboard": -1}), "artboard"),
(json!({"scale": "0.5"}), "scale"),
(json!({"traceViews": 1}), "traceViews"),
(json!({"data": "yes"}), "data"),
] {
let r = request("ui.render", params.clone());
assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{params}: {r}");
}
let r = request("ui.render", json!({"artboard": null, "scale": null}));
assert_eq!([&r["result"]["width"], &r["result"]["height"]].map(Value::as_u64), [Some(64), Some(64)], "null keeps the default: {r}");
}
/// The control channel's input methods refuse a number or switch of the wrong type before they
/// queue any event; omitting it keeps its default.
#[test]
fn control_input_refuses_params_of_the_wrong_type() {
let move_to = |mods: Value| json!({"events": [{"kind": "move", "x": 5, "y": 5}, {"kind": "move", "x": 6, "y": 6, "mods": mods}]});
for (method, params, key) in [
("ui.move", json!({"x": "10"}), "x"),
("ui.move", json!({"y": true}), "y"),
("ui.wheel", json!({"dy": "1"}), "dy"),
("ui.wheel", json!({"dy": 1, "shift": "yes"}), "shift"),
("ui.click", json!({"x": [1]}), "x"),
("ui.click", json!({"cmd": 1}), "cmd"),
("ui.drag", json!({"toX": "5"}), "toX"),
("ui.key", json!({"key": "Enter", "alt": "true"}), "alt"),
("ui.resize", json!({"width": "800"}), "width"),
("ui.screenshot", json!({"focus": "no"}), "focus"),
("ui.screenshot", json!({"data": 1}), "data"),
("ui.set", json!({"rulers": "true"}), "rulers"),
("ui.set", json!({"grid": true, "controlBar": 0}), "controlBar"),
("ui.pointer", json!({"events": [{"kind": "move", "x": "5", "y": 0}]}), "x"),
("ui.pointer", move_to(json!({"shift": "yes"})), "mods"),
("ui.pointer", move_to(json!([true])), "mods"),
("ui.pointer", json!({"mods": "shift", "events": [{"kind": "move", "x": 1, "y": 1}]}), "mods"),
] {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.synthetic.push(egui::Event::Text("pending".into()));
let before = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar);
let r = input_request(&mut app, method, params.clone());
assert_eq!(r["ok"], false, "{method} {params}: {r}");
assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{method} {params}: {r}");
let after = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar);
assert_eq!(after, before, "{method} {params}: nothing is queued or set");
}
let mut app = VectorcraftApp::new(Session::new(), Services::default());
assert_eq!(input_request(&mut app, "ui.move", json!({"x": null, "y": 4}))["ok"], true);
assert!(matches!(app.synthetic.first(), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(0.0, 4.0)));
}
/// The app's own commands refuse a param of the wrong type and change nothing; omitting it or
/// giving null keeps its default.
#[test]
fn ui_commands_refuse_params_of_the_wrong_type() {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("view.setZoom", json!({"zoom": 300, "center": [5, 5]})).unwrap();
let view = |app: &VectorcraftApp| app.view().map(|v| (v.zoom, v.center.x, v.center.y));
let before = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone());
for (id, params, key) in [
("view.setZoom", json!({"zoom": "200"}), "zoom"),
("view.setZoom", json!({"zoom": 200, "center": [1]}), "center"),
("view.setZoom", json!({"zoom": 200, "center": "0,0"}), "center"),
("view.screenMode", json!({"mode": "2"}), "mode"),
("view.screenMode", json!({"mode": 1.5}), "mode"),
("window.panel", json!({"panel": "layers", "toggle": "true"}), "toggle"),
("window.panel", json!({"panel": "layers", "toggle": true, "toggleGroup": 1}), "toggleGroup"),
("file.revert", json!({"confirmed": "yes"}), "confirmed"),
("file.close", json!({"index": "0"}), "index"),
("ui.newSwatch", json!({"spot": "true"}), "spot"),
("ui.newSwatch", json!({"global": 1}), "global"),
("ui.symbolOptions", json!({"edit": 1}), "edit"),
("ui.batchDialog", json!({"set": "1"}), "set"),
("ui.batchDialog", json!({"action": -1}), "action"),
("file.exportSelection", json!({"multiple": "true"}), "multiple"),
] {
let e = app.run(id, params.clone()).unwrap_err();
assert!(e.contains(&format!("`{key}`")), "{id} {params}: {e}");
let after = (view(&app), app.ui.screen_mode, app.session.documents().len(), app.ui.dialog.is_some(), app.ui.open_panel.clone());
assert_eq!(after, before, "{id} {params}: nothing changes");
}
app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap();
assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size)));
}
#[test]
@@ -370,6 +457,35 @@ fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() {
}
}
/// `ui.pointer` refuses an unknown event kind, a pen value or `space` of the wrong type, or a
/// screen-space event with no canvas, before any of the packet's events runs.
#[test]
fn synthetic_pointer_rejects_an_unknown_kind_before_any_event_runs() {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true);
let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone();
let moves = [json!({"kind": "down", "x": 125, "y": 125}), json!({"kind": "drag", "x": 145, "y": 125}), json!({"kind": "up", "x": 145, "y": 125})];
for (last, error) in [
(json!({"kind": "wiggle", "x": 145, "y": 125}), "unknown pointer kind `wiggle`"),
(json!({"kind": "move", "x": 145, "y": 125, "space": "screen"}), "no canvas yet"),
(json!({"kind": "move", "x": 145, "y": 125, "pressure": "bad"}), "`pressure` must be a number"),
(json!({"kind": "move", "x": 145, "y": 125, "holdMs": "800"}), "`holdMs` must be a number"),
(json!({"kind": "move", "x": 145, "y": 125, "tiltY": true}), "`tiltY` must be a number"),
(json!({"kind": "move", "x": 145, "y": 125, "rotation": "90"}), "`rotation` must be a number"),
(json!({"kind": "move", "x": 145, "y": 125, "space": "screeen"}), "`space` must be doc or screen"),
(json!({"kind": "move", "x": 145, "y": 125, "space": true}), "`space` must be doc or screen"),
] {
let events = moves.iter().cloned().chain([last]).collect::<Vec<_>>();
let r = input_request(&mut app, "ui.pointer", json!({"events": events}));
assert_eq!(r["ok"], false, "{error}: {r}");
assert!(r["error"].as_str().is_some_and(|e| e.contains(error)), "{r}");
assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{error}: the drag does not run");
}
}
/// `ui.pointer` replies with the key object: a click on one of two selected objects makes it
/// the key, and a click on the key again lets it go.
#[test]
+10 -3
View File
@@ -1,8 +1,8 @@
//! DXF Options (Export As → DXF): a preset (Custom, or CNC / CAM, which sets the options below for
//! cutting software and shows Custom again once one is changed), version, scale (1 unit of the
//! art = N drawing units) and lineweights, number of colours, the format of placed images,
//! Preserve Appearance or Maximize Editability, and Export Selected Art Only, Alter Paths for
//! Appearance and Outline Text.
//! art = N drawing units) and lineweights, number of colours, the format of placed images and
//! Include Placed Images, Preserve Appearance or Maximize Editability, and Export Selected Art
//! Only, Alter Paths for Appearance, Outline Text and Include Fill Hatches.
//!
//! Fields: `document.export` params (`format: dxf`, `path?`, the artboard choice) and the DXF
//! options of `document.exportDxf`. OK remembers the options for next time and writes the file
@@ -58,6 +58,8 @@ fn preset_fields(preset: DxfPreset) -> Map<String, Value> {
("scaleLineweights", json!(o.scale_lineweights)),
("colors", json!(o.colors.id())),
("rasterFormat", json!(o.raster.id())),
("includeImages", json!(o.include_images)),
("includeHatches", json!(o.include_hatches)),
("preserve", json!(o.preserve.id())),
("alterPaths", json!(o.alter_paths)),
("outlineText", json!(o.outline_text)),
@@ -140,6 +142,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
}
let rasters: Vec<(&str, &str)> = RasterFormat::ALL.iter().map(|r| (r.id(), r.label())).collect();
choice(ui, d, "rasterFormat", tl!("Raster File Format:"), &rasters);
ui.horizontal(|ui| {
ui.add_space(LABEL + 8.0);
check(ui, d, "includeImages", tl!("Include Placed Images"));
});
ui.add_space(10.0);
widgets::subheader(ui, tl!("Export Option"));
let preserve = Preserve::from_id(&d.str("preserve")).unwrap_or_default();
@@ -162,6 +168,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
if widgets::check(ui, tl!("Outline Text"), appearance || d.bool("outlineText"), !appearance) {
d.fields.insert("outlineText".into(), json!(!d.bool("outlineText")));
}
check(ui, d, "includeHatches", tl!("Include Fill Hatches"));
ui.add_space(8.0);
super::form::caption(
ui,
+2 -1
View File
@@ -103,7 +103,8 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
d.fields.insert("all".into(), json!(all));
}
let mut range = d.str("range");
if ui.add_enabled(!all, egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0)).changed() {
let field = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0).hint_text("1-3, 5");
if ui.add_enabled(!all, field).changed() {
d.fields.insert("range".into(), json!(range));
}
});
@@ -784,8 +784,7 @@ fn save_preset_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
/// ones → the names added
/// (none on the web, where the picked file arrives later and imports through `io::open_bytes`).
pub(crate) fn import_presets(app: &mut VectorcraftApp) -> Result<Vec<String>, String> {
if let Some(f) = app.services.open_async.as_mut() {
f();
if crate::picks::open_async(app) {
return Ok(vec![]);
}
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS)], ..Default::default() };
@@ -197,8 +197,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
}
Action::Import => {
// On the web the picked file arrives later and imports through `io::open_bytes`.
if let Some(f) = app.services.open_async.as_mut() {
f();
if crate::picks::open_async(app) {
return Ok(());
}
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Flattener presets", PRESET_EXTS)], ..Default::default() };
+1 -2
View File
@@ -173,8 +173,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
}
Action::Import => {
// On the web the picked file arrives later and imports through `io::open_bytes`.
if let Some(f) = app.services.open_async.as_mut() {
f();
if crate::picks::open_async(app) {
return Ok(());
}
let pick = crate::FilePick {
@@ -191,8 +191,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current
}
Action::Import => {
// On the web the picked file arrives later and imports through `io::open_bytes`.
if let Some(f) = app.services.open_async.as_mut() {
f();
if crate::picks::open_async(app) {
return Ok(());
}
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Perspective grid presets", PRESET_EXTS)], ..Default::default() };
+43 -6
View File
@@ -341,6 +341,21 @@ fn import_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String>
/// The dialog kind of the approval of a plug-in install.
pub const INSTALL_KIND: &str = "pluginInstall";
/// Who asked for a plug-in install, fixed when the request is made.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InstallOrigin {
/// The person at the keyboard: Install Plug-in…, File › Open or a drop.
Person,
/// A control or MCP request, a frame of synthetic input, or a file dialog that one of them
/// opened ([`VectorcraftApp::automation_asked`]): nothing in the dialog installs it, and the
/// person starts Install Plug-in… to install it.
Automation,
}
/// What [`ask_install`] answers, as `approval`, for a question automation asked: the person has to
/// start Install Plug-in… to install the module.
pub(crate) const PERSON_MUST_START_INSTALL: &str = "personMustStartInstall";
/// A plug-in install waiting for a person's answer.
pub(crate) struct PendingInstall {
/// The question and the lines under it, in the UI language.
@@ -350,6 +365,8 @@ pub(crate) struct PendingInstall {
pub params: Value,
/// What OK approves: the module the question is about.
pub approval: InstallApproval,
/// Who asked; a question automation asked has no OK that installs.
pub origin: InstallOrigin,
/// How long the question has been on screen; [`ask_install`] starts it over.
pub shown: Shown,
}
@@ -439,27 +456,44 @@ pub(super) const INSTALL_SPEC: DialogSpec = DialogSpec {
};
/// Asks a person whether to install what `pending` describes, its question not yet shown, even when
/// it reads as the one it replaces. → `{pending}`.
/// it reads as the one it replaces. → `{pending}`, and `approval: "personMustStartInstall"` when
/// automation asked.
pub(crate) fn ask_install(app: &mut VectorcraftApp, mut pending: PendingInstall) -> Value {
pending.shown = Shown::default();
let automated = pending.origin == InstallOrigin::Automation;
app.pending_plugin_install = Some(pending);
app.ui.dialog = Some(Dialog::new(INSTALL_KIND, json!({})));
if automated {
return json!({ "pending": INSTALL_KIND, "approval": PERSON_MUST_START_INSTALL });
}
json!({ "pending": INSTALL_KIND })
}
/// What the approval says when automation asked for the install; the error of its OK
/// ([`install_confirm`]) is the same text.
fn automation_asked_note() -> &'static str {
tl!("Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself.")
}
/// The question, the lines under it, and OK, which is disabled until the question has been shown
/// for [`APPROVAL_DELAY`] ([`Shown`]), and Cancel, which never waits.
/// for [`APPROVAL_DELAY`] ([`Shown`]), and Cancel, which never waits. When automation asked, a note
/// says so and OK stays disabled.
fn install_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> DialogAction {
let Some(pending) = app.pending_plugin_install.as_mut() else { return DialogAction::Cancel };
let enabled = pending.shown.drawn(ui);
let person = pending.origin == InstallOrigin::Person;
let enabled = pending.shown.drawn(ui) && person;
ui.label(egui::RichText::new(&pending.message).strong());
ui.add_space(8.0);
ui.label(egui::RichText::new(&pending.detail).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
if !person {
ui.add_space(8.0);
ui.label(egui::RichText::new(automation_asked_note()).strong());
}
ui.add_space(16.0);
let mut action = DialogAction::None;
let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y);
ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
if widgets::primary_button_enabled(ui, "OK", enabled).clicked() && pending.shown.ready() {
if widgets::primary_button_enabled(ui, "OK", enabled).clicked() && person && pending.shown.ready() {
action = DialogAction::Confirm;
}
pending.shown.released(ui);
@@ -472,9 +506,12 @@ fn install_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) ->
}
/// OK: installs the module the dialog showed, if a person pressed it; automation is refused and the
/// dialog stays open. Before the question has been shown for [`APPROVAL_DELAY`] it installs nothing
/// and the dialog stays open. → `{pending}`.
/// dialog stays open, and so is any OK of a question automation asked. Before the question has been
/// shown for [`APPROVAL_DELAY`] it installs nothing and the dialog stays open. → `{pending}`.
fn install_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result<Value, String> {
if app.pending_plugin_install.as_ref().is_some_and(|p| p.origin == InstallOrigin::Automation) {
return Err("Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself.".into());
}
if app.automation_is_acting() {
return Err("Only the person at the keyboard can approve installing a plug-in".into());
}
+1 -2
View File
@@ -153,8 +153,7 @@ pub(super) fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current
}
Action::Import => {
// On the web the picked file arrives later and imports through `io::open_bytes`.
if let Some(f) = app.services.open_async.as_mut() {
f();
if crate::picks::open_async(app) {
return Ok(());
}
let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Print presets", PRESET_EXTS)], ..Default::default() };
+163 -26
View File
@@ -7,8 +7,13 @@
//! editable), `path`, `format`, and one field per option (agents set them with `ui.dialog.set`).
//! Native and `.ai` files show their save options (VectorCraft Options after Save As): each
//! artboard to a separate file, with `all` (true: every artboard) or `range`, Include Linked Files,
//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. A native file's Version is a
//! menu of the versions VectorCraft writes (`version`, named by the releases that read each). A
//! Embed ICC Profiles, Create PDF-Compatible File and Use Compression. EPS shows Use Artboards
//! (`useArtboards`, off by default: the bounding box fits the visible art) with the same `all` or
//! `range` under it, then the options Export's EPS Options shows: Preview, Overprints, Flattener
//! preset and PostScript are menus that write the option's value (`previewFormat: "tiffColor"`,
//! `overprints: "preserve"`, `flattenerPreset: "medium"` or a saved preset's name, `level: 3`).
//! A native file's Version is a menu of the versions VectorCraft writes
//! (`version`, named by the releases that read each). A
//! `.ai` file's Version comes first: PDF-compatible, or legacy version 7 (`aiVersion: "7"`, a file
//! per artboard), which takes only Transparent Images (`transparentImages`), Hidden Objects
//! (`hiddenObjects`: a hidden layer, omitted or made visible), Text (`outlineText`: editable or
@@ -18,7 +23,9 @@
use std::sync::OnceLock;
use serde_json::{Map, Value, json};
use vectorcraft_engine::cmd::FlattenOptions;
use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format, FormatOption, SAVE_FORMATS, SaveMode, TEMPLATE_FORMATS};
use vectorcraft_eps::{Level, Overprint, Preview};
use super::{DialogResult, DialogSpec, form};
use crate::state::Dialog;
@@ -76,50 +83,130 @@ fn separates(f: &Format) -> bool {
f.options.iter().any(|o| o.name == "separateArtboards")
}
/// The checkbox that `f`'s All or Range shows under: Save each artboard to a separate file, or
/// for EPS Use Artboards (off: the visible art's bounds).
fn board_switch(f: &Format) -> Option<&'static str> {
if separates(f) {
Some("separateArtboards")
} else if f.id == "eps" {
Some("useArtboards")
} else {
None
}
}
/// The options the dialog shows: arrays and objects are for agents, as is a native file's
/// `precision`, and a page range replaces the single artboard choice; none for a format with its
/// own dialog. A `.ait` template has no Version: Save as Template writes it PDF-compatible only.
fn shown(f: &Format) -> impl Iterator<Item = &'static FormatOption> {
let range = f.options.iter().any(|o| o.name == "range");
let separate = separates(f);
let switched = board_switch(f).is_some();
let options = if own_dialog(f) { &[][..] } else { f.options };
options.iter().filter(move |o| {
!(matches!(o.ty, "array" | "object")
|| o.name == "precision"
|| (range && o.name == "artboard")
|| (separate && o.name == "range")
|| (switched && o.name == "range")
|| (matches!(f.id, "ai" | "ait") && o.name == "useArtboards")
// EPS Save keeps a page and the complete editing document; cropped and
// selected-only output belongs to Export, never this save dialog.
|| (f.id == "eps" && matches!(o.name, "useArtboards" | "selectedOnly"))
// EPS Save writes all the artwork: selected-only output belongs to Export.
|| (f.id == "eps" && o.name == "selectedOnly")
|| (f.id == "ait" && o.name == "aiVersion"))
})
}
/// An option's label: the save options as the reference app's options dialog names them, the
/// others from their names.
/// An option's label: its written label, or for an option without one, its name split into words.
fn label(o: &FormatOption) -> String {
match o.name {
written_label(o).unwrap_or_else(|| form::humanize(o.name))
}
/// The written label of option `o`, translated.
fn written_label(o: &FormatOption) -> Option<String> {
Some(match o.name {
"separateArtboards" => tl!("Save each artboard to a separate file").into(),
"includeLinked" => tl!("Include Linked Files").into(),
"useArtboards" => tl!("Use Artboards").into(),
"includeLinked" | "includeLinkedFiles" => tl!("Include Linked Files").into(),
"embedProfiles" => tl!("Embed ICC Profiles").into(),
"pdfCompatible" => tl!("Create PDF-Compatible File").into(),
"compress" => tl!("Use Compression").into(),
"editingData" => tl!("Include Editing Data for Other Apps").into(),
_ => form::humanize(o.name),
}
"version" | "aiVersion" => tl!("Version:").into(),
"transparentImages" => tl!("Transparent Images:").into(),
"hiddenObjects" => tl!("Hidden Objects:").into(),
"outlineText" => tl!("Text:").into(),
"preview" => tl!("Preview").into(),
"thumbnails" => tl!("Include Document Thumbnails").into(),
"previewFormat" => tl!("Preview:").into(),
"transparentPreview" => tl!("Transparent").into(),
"overprints" => tl!("Overprints:").into(),
"flattenerPreset" => tl!("Flattener preset:").into(),
"embedFonts" => tl!("Embed Fonts (for other applications)").into(),
"cmykPostScript" => tl!("Include CMYK PostScript in RGB Files").into(),
"compatibleGradients" => tl!("Compatible Gradient and Gradient Mesh Printing").into(),
"level" => tl!("PostScript:").into(),
_ => return None,
})
}
/// Every artboard (the All choice under Save each artboard to a separate file): `all` when set,
/// else no range given.
/// The values of an option that takes one of a fixed set, each with the name its menu shows, and
/// `at`, the entry the option's value picks as the save reads it (none when the save would reject
/// the value). The first `builtins` names are VectorCraft's own (translated where they are shown);
/// the others are names the user gave (saved flattener presets), shown as they are.
struct Choices {
values: Vec<Value>,
names: Vec<String>,
builtins: usize,
at: Option<usize>,
}
/// The choices of `f`'s option `o`, whose value is `value`, when it takes one of a fixed set of
/// values: EPS's preview format, overprints, PostScript level and flattener preset (the built-in
/// presets by id, then the saved ones by name).
fn choices(app: &VectorcraftApp, f: &Format, o: &FormatOption, value: &Value) -> Option<Choices> {
if f.id != "eps" {
return None;
}
let text = value.as_str().map_or_else(|| value.to_string(), str::to_string);
let (pairs, builtins, at): (Vec<(Value, String)>, Option<usize>, Option<usize>) = match o.name {
"previewFormat" => (
Preview::ALL.iter().map(|p| (json!(p.id()), p.label().to_string())).collect(),
None,
Preview::from_id(&text).and_then(|p| Preview::ALL.iter().position(|q| *q == p)),
),
"overprints" => (
Overprint::ALL.iter().map(|p| (json!(p.id()), p.label().to_string())).collect(),
None,
Overprint::from_id(&text).and_then(|p| Overprint::ALL.iter().position(|q| *q == p)),
),
// The level is a number in the save options.
"level" => (
Level::ALL.iter().filter_map(|l| Some((json!(l.id().parse::<u64>().ok()?), l.label().to_string()))).collect(),
None,
Level::from_id(&text).and_then(|l| Level::ALL.iter().position(|q| *q == l)),
),
"flattenerPreset" => {
let presets = app.session.flattener_presets();
let id = |name: &str| FlattenOptions::PRESETS.into_iter().find(|id| FlattenOptions::preset_label(id) == Some(name));
let pairs = presets.iter().map(|p| (id(&p.name).map_or_else(|| json!(p.name), |id| json!(id)), p.name.clone())).collect();
let at = app.session.flattener_preset(&text).and_then(|p| presets.iter().position(|q| q.name == p.name));
(pairs, Some(FlattenOptions::builtin_presets().len()), at)
}
_ => return None,
};
let builtins = builtins.unwrap_or(pairs.len());
let (values, names): (Vec<Value>, Vec<String>) = pairs.into_iter().unzip();
Some(Choices { values, names, builtins, at })
}
/// Every artboard (the All choice under Save each artboard to a separate file or Use Artboards):
/// `all` when set, else no range given.
fn all_artboards(d: &Dialog) -> bool {
d.fields.get("all").and_then(Value::as_bool).unwrap_or_else(|| d.str("range").trim().is_empty())
}
/// All or Range, under Save each artboard to a separate file (enabled while it is on).
fn artboard_range(ui: &mut egui::Ui, d: &mut Dialog) {
/// All or Range, under the checkbox `switch` (enabled while it is on).
fn artboard_range(ui: &mut egui::Ui, d: &mut Dialog, switch: &str) {
ui.label("");
ui.add_enabled_ui(d.bool("separateArtboards"), |ui| {
ui.add_enabled_ui(d.bool(switch), |ui| {
ui.horizontal(|ui| {
ui.add_space(22.0);
let mut all = all_artboards(d);
@@ -167,9 +254,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
// Version first; the legacy version takes only its own options.
let legacy = legacy_ai(d);
let mut rows: Vec<&FormatOption> = shown(f).filter(|o| LEGACY_ONLY.contains(&o.name) == legacy || o.name == "aiVersion").collect();
rows.sort_by_key(|o| o.name != "aiVersion");
// EPS's PostScript level comes last, as in Export's EPS Options.
rows.sort_by_key(|o| (o.name != "aiVersion", f.id == "eps" && o.name == "level"));
for o in rows {
option_row(app, ui, d, o);
option_row(app, ui, d, f, o);
}
});
if legacy_ai(d) && app.session.active().is_some_and(|st| st.doc.artboards.len() > 1) {
@@ -330,8 +418,9 @@ fn artboard_picker(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
}
}
/// One option: a checkbox, an artboard menu, a version menu, a number or a text field.
fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &FormatOption) {
/// One option of format `f`: a checkbox, an artboard menu, a version menu, a menu of its
/// [`choices`], a number or a text field.
fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, f: &Format, o: &FormatOption) {
let t = Tokens::get(ui.ctx());
let label = label(o);
let value = d.fields.get(o.name).cloned().unwrap_or(Value::Null);
@@ -383,6 +472,40 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma
ui.end_row();
return;
}
if let Some(c) = choices(app, f, o, &value) {
ui.label(egui::RichText::new(&label).color(t.text_dim)).on_hover_text(o.description);
// A value none of them names shows as it is.
let current = c.at.and_then(|i| c.names.get(i)).cloned().unwrap_or_else(|| value.as_str().map_or_else(|| value.to_string(), str::to_string));
let names: Vec<&str> = c.names.iter().map(String::as_str).collect();
if let Some(i) = super::mixed_dropdown(ui, ("save-option", o.name), &current, &names, 254.0, |k| k < c.builtins) {
choose(d, o, &c, i);
}
ui.end_row();
return;
}
if f.id == "eps" && o.name == "transparentPreview" {
// Only the color preview can keep transparency.
ui.label("");
let color = Preview::from_id(&d.str("previewFormat")) == Some(Preview::TiffColor);
let transparent = value.as_bool().unwrap_or(true);
ui.horizontal(|ui| {
for (name, on) in [(tl!("Transparent"), true), (tl!("Opaque"), false)] {
if widgets::radio(ui, name, color && transparent == on, color) {
d.fields.insert(o.name.into(), json!(on));
}
ui.add_space(12.0);
}
});
ui.end_row();
return;
}
if f.id == "eps" && o.name == "embedFonts" {
// Type is written as glyph outlines, which need no fonts.
ui.label("");
widgets::check_tip(ui, &label, true, false, o.description);
ui.end_row();
return;
}
if o.ty == "boolean" {
ui.label("");
let on = value.as_bool().unwrap_or(false);
@@ -392,8 +515,8 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma
d.fields.insert(o.name.into(), json!(!on));
}
ui.end_row();
if o.name == "separateArtboards" {
artboard_range(ui, d);
if matches!(o.name, "separateArtboards" | "useArtboards") {
artboard_range(ui, d, o.name);
}
return;
}
@@ -421,6 +544,13 @@ fn option_row(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, o: &Forma
ui.end_row();
}
/// Option `o` set to the value of entry `i` of its menu `c`.
fn choose(d: &mut Dialog, o: &FormatOption, c: &Choices, i: usize) {
if let Some(v) = c.values.get(i) {
d.fields.insert(o.name.into(), v.clone());
}
}
/// The native versions VectorCraft writes, newest first, each with the first release that reads
/// it (the format version each release tag writes: 2 in 0.1, 3 from 0.2, 4 from 0.8).
const NATIVE_VERSIONS: [(u32, &str); 4] = [(4, "0.8"), (3, "0.2"), (2, "0.1"), (1, "0.1")];
@@ -505,8 +635,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
if !boards.iter().all(|b| *b) {
options.insert("range".into(), json!(super::export_for_screens::range_text(&boards)));
}
} else if separates(f) {
if !d.bool("separateArtboards") || all_artboards(d) {
} else if let Some(switch) = board_switch(f) {
if switch == "useArtboards" {
// All or Range alone names the artboards: an artboard remembered from an earlier
// save would otherwise turn Use Artboards on, or narrow All to itself.
options.remove("artboard");
options.remove("artboards");
options.insert(switch.into(), json!(d.bool(switch)));
}
if !d.bool(switch) || all_artboards(d) {
options.remove("range");
} else {
// A bad range keeps the dialog open.
@@ -346,19 +346,213 @@ fn save_as_pdf_asks_with_the_save_pdf_dialog_and_remembers_its_options() {
assert_eq!(dialog(&app).str("__save"), "file.saveCopy");
}
/// The `%%BoundingBox` line of an EPS file.
fn bounding_box(eps: &[u8]) -> String {
let ps = std::str::from_utf8(vectorcraft_eps::sections(eps).unwrap().0).unwrap();
ps.lines().find(|l| l.starts_with("%%BoundingBox:")).expect("a bounding box").to_string()
}
#[test]
fn eps_save_as_keeps_page_options_and_writes_eps_without_export_only_switches() {
fn eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard() {
let (mut app, written, _) = desktop("art.eps");
app.run("file.saveAs", json!({})).unwrap();
let names: Vec<_> = shown(fileio::format("eps").unwrap()).map(|option| option.name).collect();
assert!(!names.contains(&"useArtboards") && !names.contains(&"selectedOnly"));
assert!(names.contains(&"useArtboards") && !names.contains(&"selectedOnly") && !names.contains(&"range"), "{names:?}");
assert!(names.contains(&"previewFormat"));
// EPS alone gains the row: the other save formats keep their own checkbox or none.
for id in SAVE_FORMATS.iter().chain(TEMPLATE_FORMATS).filter(|id| **id != "eps") {
let f = fileio::format(id).unwrap();
assert!(!shown(f).any(|o| o.name == "useArtboards") && board_switch(f) != Some("useArtboards"), "{id}");
}
let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx()));
assert!(text.contains("Use Artboards") && text.contains("All") && text.contains("Range:"), "{text}");
assert!(!dialog(&app).bool("useArtboards"), "Use Artboards starts off");
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let saved = written.borrow();
assert_eq!(saved[0].0, "art.eps");
assert!(vectorcraft_eps::native(&saved[0].1).is_some());
{
let saved = written.borrow();
assert_eq!(saved[0].0, "art.eps");
assert!(vectorcraft_eps::native(&saved[0].1).is_some());
// The box Export writes of the visible art, not the artboard.
let exported = app.session.execute("document.export", &json!({"format": "eps"})).unwrap();
let exported = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(bounding_box(&saved[0].1), bounding_box(&exported));
assert_ne!(bounding_box(&saved[0].1), "%%BoundingBox: 0 0 100 80");
}
assert_eq!(app.session.active().unwrap().format, "eps");
// Checked, the artboard is the page, and an artboard remembered from an earlier save doesn't
// narrow All.
app.run("file.saveAs", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("useArtboards".into(), json!(true));
d.fields.insert("artboard".into(), json!(3));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
{
let saved = written.borrow();
assert_eq!(saved.len(), 2, "one artboard: one file");
assert_eq!(bounding_box(&saved[1].1), "%%BoundingBox: 0 0 100 80");
}
// A save that named an artboard without Use Artboards (as document.save {artboard} does) had
// it on: the dialog shows it on, on that artboard, and OK writes the artboard again.
let st = app.session.active_mut().unwrap();
st.save_options.remove("useArtboards");
st.save_options.insert("artboard".into(), json!(0));
app.run("file.saveAs", json!({})).unwrap();
assert!(dialog(&app).bool("useArtboards"));
assert_eq!(dialog(&app).str("range"), "1");
super::super::confirm(&mut app).unwrap();
let saved = written.borrow();
assert_eq!(saved.len(), 3);
assert_eq!(bounding_box(&saved[2].1), "%%BoundingBox: 0 0 100 80");
}
/// Save As › EPS shows the options of Export's EPS Options: Preview, Overprints, Flattener preset
/// and PostScript as menus of readable names (not fields holding `tiffColor`, `preserve` and
/// `medium`), the checkboxes under written labels, and the PostScript level last.
#[test]
fn eps_save_options_are_menus_with_readable_names() {
let (mut app, _, _) = desktop("art.eps");
app.run("file.saveAs", json!({})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx()));
let lines: Vec<&str> = text.lines().collect();
for shown in [
"Preview:",
"TIFF (8-bit Color)",
"Transparent",
"Opaque",
"Overprints:",
"Preserve",
"Flattener preset:",
"Medium Resolution",
"Embed Fonts (for other applications)",
"Include Linked Files",
"Include Document Thumbnails",
"Include CMYK PostScript in RGB Files",
"Compatible Gradient and Gradient Mesh Printing",
"PostScript:",
"Language Level 3",
] {
assert!(lines.contains(&shown), "{shown:?} in {text}");
}
for id in ["tiffColor", "preserve", "medium", "Cmyk Post Script", "Preview Format:", "Level:", "Thumbnails"] {
assert!(!lines.contains(&id), "{id:?} in {text}");
}
let at = |s: &str| lines.iter().position(|l| *l == s).unwrap();
assert!(at("PostScript:") > at("Compatible Gradient and Gradient Mesh Printing"), "{text}");
}
/// Every option the save options dialog shows, in every format it serves, has a written label:
/// none is painted as its name split into words.
#[test]
fn save_options_have_written_labels() {
// The web's Save As and Save as Template dialogs show the options of every format they pick.
let formats = SAVE_FORMATS.iter().map(|id| (*id, "file.saveAs")).chain(TEMPLATE_FORMATS.iter().map(|id| (*id, "file.saveAsTemplate")));
for (id, command) in formats {
let (mut app, _) = web();
app.run(command, json!({})).unwrap();
let mut d = app.ui.dialog.take().unwrap();
switch_format(&mut app, &mut d, id);
app.ui.dialog = Some(d);
assert_eq!((dialog(&app).kind.as_str(), dialog(&app).str("format").as_str()), (KIND, id));
let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx()));
let f = fileio::format(id).unwrap();
for o in shown(f) {
let written = written_label(o);
assert!(written.is_some(), "{id}: {} has no written label", o.name);
let split = form::humanize(o.name);
let split = split.trim_end_matches(':');
assert!(
written.as_deref().map(|w| w.trim_end_matches(':')) == Some(split) || !text.lines().any(|l| l == split),
"{id}: {split:?} in {text}"
);
}
}
}
/// A pick from an EPS menu saves the option's value: the id, the level as a number, a saved
/// flattener preset by its name. The file is written with them.
#[test]
fn picking_eps_menu_items_saves_their_values() {
let (mut app, written, _) = desktop("art.eps");
app.session.prefs.flattener_presets.push(vectorcraft_engine::cmd::FlattenerPreset {
name: "Mine".into(),
options: vectorcraft_engine::cmd::FlattenOptions::preset("low").unwrap(),
});
app.run("file.saveAs", json!({})).unwrap();
let f = fileio::format("eps").unwrap();
let mut d = app.ui.dialog.take().unwrap();
for (name, pick, value) in [
("previewFormat", "None", json!("none")),
("overprints", "Discard", json!("discard")),
("flattenerPreset", "Mine", json!("Mine")),
("level", "Language Level 2", json!(2)),
] {
let o = f.options.iter().find(|o| o.name == name).unwrap();
let c = choices(&app, f, o, &Value::Null).unwrap_or_else(|| panic!("{name} is a menu"));
let i = c.names.iter().position(|n| n == pick).unwrap_or_else(|| panic!("{pick} in {name}: {:?}", c.names));
choose(&mut d, o, &c, i);
assert_eq!(d.fields[name], value, "{name}");
assert_eq!(choices(&app, f, o, &value).unwrap().at, Some(i), "{name}: the menu shows the pick");
}
// The built-in presets come first, by id. A value picks the entry the save reads it as: a
// preset by id or name in any case, a level by its digits, a preview or overprint by id only.
let at = |name: &str, value: Value| {
let o = f.options.iter().find(|o| o.name == name).unwrap();
choices(&app, f, o, &value).unwrap().at
};
let o = f.options.iter().find(|o| o.name == "flattenerPreset").unwrap();
let c = choices(&app, f, o, &Value::Null).unwrap();
assert_eq!(c.values, [json!("high"), json!("medium"), json!("low"), json!("Mine")]);
assert_eq!((c.builtins, c.at), (3, None));
assert_eq!(
(at("flattenerPreset", json!("MEDIUM RESOLUTION")), at("flattenerPreset", json!("mine")), at("flattenerPreset", json!("Other"))),
(Some(1), Some(3), None)
);
assert_eq!((at("level", json!("level2")), at("level", json!(3)), at("level", json!(4))), (Some(0), Some(1), None));
assert_eq!((at("previewFormat", json!("TIFFBW")), at("previewFormat", json!("TIFF (8-bit Color)"))), (Some(1), None));
assert_eq!((at("overprints", json!("Discard")), at("overprints", json!("keep"))), (Some(1), None));
app.ui.dialog = Some(d);
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none(), "saved: {}", app.ui.status);
let saved = &app.session.active().unwrap().save_options;
for (name, value) in [("previewFormat", json!("none")), ("overprints", json!("discard")), ("flattenerPreset", json!("Mine")), ("level", json!(2))]
{
assert_eq!(saved[name], value, "{name}");
}
let bytes = written.borrow()[0].1.clone();
let (ps, preview) = vectorcraft_eps::sections(&bytes).unwrap();
assert!(preview.is_none(), "no preview");
assert!(String::from_utf8_lossy(ps).contains("%%LanguageLevel: 2"));
}
/// Save As › EPS: Transparent and Opaque apply to the color TIFF preview only, and are disabled
/// with any other preview. Embed Fonts shows checked and disabled. A flattener preset that no
/// entry of the menu names shows as it is.
#[test]
fn eps_save_transparency_follows_the_color_preview() {
use crate::widgets::accessibility_tests::{named, role_and_state, tree};
use egui::accesskit::Toggled;
let (mut app, _, _) = desktop("art.eps");
app.run("file.saveAs", json!({})).unwrap();
let set = |app: &mut VectorcraftApp, k: &str, v: Value| {
app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
};
set(&mut app, "previewFormat", json!("tiffColor"));
set(&mut app, "transparentPreview", json!(false));
let t = tree(|ui| super::super::show(&mut app, ui.ctx()));
assert!(!named(&t, "Transparent").is_disabled() && !named(&t, "Opaque").is_disabled());
assert_eq!((role_and_state(&t, "Transparent").1, role_and_state(&t, "Opaque").1), (Some(Toggled::False), Some(Toggled::True)));
let fonts = named(&t, "Embed Fonts (for other applications)");
assert_eq!((fonts.is_disabled(), fonts.toggled()), (true, Some(Toggled::True)));
for preview in ["none", "tiffBw"] {
set(&mut app, "previewFormat", json!(preview));
let t = tree(|ui| super::super::show(&mut app, ui.ctx()));
assert!(named(&t, "Transparent").is_disabled() && named(&t, "Opaque").is_disabled(), "{preview}");
}
set(&mut app, "flattenerPreset", json!("Gone"));
let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx()));
assert!(text.lines().any(|l| l == "Gone"), "{text}");
}
/// #4931: a native file's Version is a menu of the versions VectorCraft writes, the current one
+48 -7
View File
@@ -50,13 +50,15 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() {
frame(&mut app);
let d = app.ui.dialog.as_ref().unwrap();
let fields = |d: &crate::state::Dialog| {
["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText"].map(|k| d.str(k)).join(" ")
["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText", "includeImages", "includeHatches"]
.map(|k| d.str(k))
.join(" ")
};
assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true");
assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false");
// Any change to a field the preset sets shows Custom, and keeps the other fields.
set(&mut app, "colors", json!("true"));
frame(&mut app);
assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2000 Millimeters 1.0 true editability false true");
assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2000 Millimeters 1.0 true editability false true false false");
set(&mut app, "colors", json!("256"));
frame(&mut app);
assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc", "matching every field again");
@@ -70,12 +72,12 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() {
assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc");
set(&mut app, "dxfPreset", json!("custom"));
frame(&mut app);
assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2018 Millimeters 1.0 true appearance false false");
assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2018 Millimeters 1.0 true appearance false false true true");
// A preset the command gives sets the fields it does not give.
app.ui.dialog = None;
app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "cnc", "unit": "Inches"})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!(fields(d), "custom 2000 Inches 1.0 256 editability false true");
assert_eq!(fields(d), "custom 2000 Inches 1.0 256 editability false true false false");
// A preset set and confirmed without drawing (the control channel) sets its fields too.
set(&mut app, "dxfPreset", json!("cnc"));
confirm(&mut app).unwrap();
@@ -84,7 +86,7 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() {
app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "custom"})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
set_field(d, "dxfPreset".into(), json!("cnc"));
assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true");
assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false");
set_field(d, "unit".into(), json!("Inches"));
assert_eq!(d.str("dxfPreset"), "custom");
// Setting the preset again sets its fields again.
@@ -94,12 +96,51 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() {
// Setting Custom while Custom is shown still puts back the defaults.
let mut reset = d.clone();
set_field(&mut reset, "dxfPreset".into(), json!("custom"));
assert_eq!(fields(&reset), "custom 2018 Millimeters 1.0 true appearance false false");
assert_eq!(fields(&reset), "custom 2018 Millimeters 1.0 true appearance false false true true");
confirm(&mut app).unwrap();
let remembered = ["dxfPreset", "version", "unit"].map(|k| app.ui.dxf_options[k].as_str());
assert_eq!(remembered, [Some("custom"), Some("2000"), Some("Inches")]);
}
#[test]
fn include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom() {
let (mut app, written) = app(1);
let shown = |app: &VectorcraftApp| {
let d = app.ui.dialog.as_ref().unwrap();
(d.str("dxfPreset"), d.bool("includeImages"), d.bool("includeHatches"))
};
app.run("ui.dxfOptionsDialog", json!({"path": "/out/a.dxf"})).unwrap();
frame(&mut app);
assert_eq!(shown(&app), ("custom".into(), true, true));
confirm(&mut app).unwrap();
assert!(text(&written.borrow()[0].1).contains("\nHATCH\n"), "Custom keeps the fill's hatch");
app.run("ui.dxfOptionsDialog", json!({"path": "/out/b.dxf"})).unwrap();
set(&mut app, "dxfPreset", json!("cnc"));
frame(&mut app);
assert_eq!(shown(&app), ("cnc".into(), false, false));
// Either checkbox changed shows Custom; both back as the preset sets them show CNC / CAM.
set(&mut app, "includeHatches", json!(true));
frame(&mut app);
assert_eq!(shown(&app), ("custom".into(), false, true));
set(&mut app, "includeHatches", json!(false));
set(&mut app, "includeImages", json!(true));
frame(&mut app);
assert_eq!(shown(&app), ("custom".into(), true, false));
set(&mut app, "includeImages", json!(false));
frame(&mut app);
assert_eq!(shown(&app).0, "cnc");
confirm(&mut app).unwrap();
assert!(!text(&written.borrow()[1].1).contains("\nHATCH\n"), "CNC / CAM writes the fill's outline alone");
let remembered = ["includeImages", "includeHatches"].map(|k| app.ui.dxf_options[k].as_bool());
assert_eq!(remembered, [Some(false), Some(false)]);
// The next DXF Options start from them, and Custom turns both back on.
crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({}));
assert_eq!(shown(&app), ("cnc".into(), false, false));
set(&mut app, "dxfPreset", json!("custom"));
frame(&mut app);
assert_eq!(shown(&app), ("custom".into(), true, true));
}
#[test]
fn bad_dxf_options_keep_the_dialog_open() {
let (mut app, written) = app(1);
@@ -180,6 +180,15 @@ fn a_bad_range_keeps_export_as_open() {
assert!(written.borrow().is_empty());
}
/// An emptied Range field shows an example of the artboard numbers it takes, as Save As's does.
#[test]
fn an_empty_export_as_range_shows_an_example() {
let (mut app, _) = app(2);
app.run("file.exportAs", json!({"useArtboards": true, "range": ""})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.lines().any(|l| l == "1-3, 5"), "{text}");
}
#[test]
fn svg_continues_in_svg_options_and_pdf_art_is_written_directly() {
let (mut app, written) = app(2);
+674
View File
@@ -0,0 +1,674 @@
//! Where the interface thread is in its frame, for the desktop app's hang report (the app's
//! `hang_watch` module).
//!
//! The interface thread marks each stage of a frame (the host's input hook, the app's logic, the
//! interface, and the hand-off to the renderer), a system clipboard call in progress, whether any
//! window's pass had input ([`watch_input`]), and each command it runs. Another thread reads the
//! marks without waiting for the interface thread: the stage and the activity are atomics, and the
//! recent commands and frame times are read with `try_lock`. Marking costs a few atomic stores a
//! frame and one short lock per command and per frame. The web build marks the same way, and
//! nothing reads the marks there.
//!
//! Commands are kept by id only: no parameters, file names or document contents. A command run
//! again moves to the end of the list instead of taking another place, so a panel that runs a
//! query every frame does not push out the commands before it.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};
use vectorcraft_engine::cmd::clipboard::Flavour;
use crate::sysclip::{ClipboardRead, SystemClipboard};
/// How many different command ids [`Beacon::recent_commands`] keeps.
pub const RECENT_COMMANDS: usize = 8;
/// How many frames [`Beacon::recent_frames`] keeps.
pub const RECENT_FRAMES: usize = 16;
/// The longest command id [`Beacon::command`] keeps as it is.
pub const MAX_COMMAND_ID: usize = 64;
/// The marks the desktop app's interface thread writes.
pub static BEACON: Beacon = Beacon::new();
/// The part of a frame the interface thread is in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Stage {
/// Outside the app's own frame code: waiting for input or a repaint, or a frame without input
/// handed to the renderer.
Idle = 0,
/// The host's input hook.
Input = 1,
/// The app's logic: background results, timers, the control channel.
Logic = 2,
/// The interface: input handling, commands, panels and dialogs.
Interface = 3,
/// A frame that had input was handed to the renderer. Drawing and presenting it follow, and
/// then the next frame, which input asks for at once.
Drawing = 4,
}
impl Stage {
fn from_u8(n: u8) -> Stage {
match n {
1 => Stage::Input,
2 => Stage::Logic,
3 => Stage::Interface,
4 => Stage::Drawing,
_ => Stage::Idle,
}
}
/// Whether the interface thread is expected to finish this stage soon.
pub fn busy(self) -> bool {
self != Stage::Idle
}
/// The stage for a report, in English.
pub fn describe(self) -> &'static str {
match self {
Stage::Idle => "between frames",
Stage::Input => "reading the window's input",
Stage::Logic => "running the app's logic (background results, timers, the control channel)",
Stage::Interface => "running the interface (input handling, commands, panels and dialogs)",
Stage::Drawing => {
"after a frame with input went to the renderer: drawing or presenting it, or waiting for the next frame, which the system may hold back while the window is hidden"
}
}
}
}
/// What the interface thread is waiting on inside a stage, where the app knows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Activity {
None = 0,
/// A read of the system clipboard, or a check of what it holds.
ClipboardRead = 1,
/// A write to the system clipboard.
ClipboardWrite = 2,
/// A system file dialog shown in line, which waits for the user and keeps the window
/// answering the system ([`Sample::busy`]).
Dialog = 3,
/// A menu of the system menu bar is open, which waits for the user ([`Sample::busy`]). The
/// host sets it on the sample it reads; the interface thread does not mark it.
Menu = 4,
}
impl Activity {
fn from_u8(n: u8) -> Activity {
match n {
1 => Activity::ClipboardRead,
2 => Activity::ClipboardWrite,
3 => Activity::Dialog,
4 => Activity::Menu,
_ => Activity::None,
}
}
/// Whether the activity waits for the user, so a long one is not a stall.
pub fn waits_for_user(self) -> bool {
matches!(self, Activity::Dialog | Activity::Menu)
}
/// The activity for a report, in English; `None` when there is none.
pub fn describe(self) -> Option<&'static str> {
match self {
Activity::None => None,
Activity::ClipboardRead => Some("reading the system clipboard"),
Activity::ClipboardWrite => Some("writing to the system clipboard"),
Activity::Dialog => Some("a system file dialog, waiting for the user"),
Activity::Menu => Some("a menu of the system menu bar, waiting for the user"),
}
}
}
/// What the interface thread was doing when it was read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Sample {
/// Counts every mark: the same value in two samples means the thread made no mark between them.
pub step: u64,
pub stage: Stage,
pub activity: Activity,
}
impl Sample {
/// Whether the interface thread is expected to move on soon: inside a stage, and not showing a
/// system dialog or menu that waits for the user.
pub fn busy(&self) -> bool {
self.stage.busy() && !self.activity.waits_for_user()
}
}
/// One frame's times, in milliseconds.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameTime {
/// The app's own work: from the input hook to the end of the interface.
pub work_ms: f32,
/// The renderer's measure of the frame before: the app's work and drawing, without waiting for
/// the display. `None` when the host has none.
pub previous_total_ms: Option<f32>,
}
/// The marks: see the module documentation.
pub struct Beacon {
step: AtomicU64,
stage: AtomicU8,
activity: AtomicU8,
documents: AtomicUsize,
/// A pass of some window had input since [`Beacon::take_input`] last ran.
input: AtomicBool,
/// The windows a pass handed to the system since [`Beacon::take_handed_off`] last ran. Only the
/// interface thread uses it.
handed_off: Mutex<Vec<egui::ViewportId>>,
commands: Mutex<VecDeque<String>>,
frames: Mutex<VecDeque<FrameTime>>,
}
impl Default for Beacon {
fn default() -> Self {
Self::new()
}
}
impl Beacon {
pub const fn new() -> Beacon {
Beacon {
step: AtomicU64::new(0),
stage: AtomicU8::new(Stage::Idle as u8),
activity: AtomicU8::new(Activity::None as u8),
documents: AtomicUsize::new(0),
input: AtomicBool::new(false),
handed_off: Mutex::new(Vec::new()),
commands: Mutex::new(VecDeque::new()),
frames: Mutex::new(VecDeque::new()),
}
}
fn bump(&self) {
self.step.fetch_add(1, Ordering::Release);
}
/// The interface thread enters `stage`.
pub fn enter(&self, stage: Stage) {
self.stage.store(stage as u8, Ordering::Relaxed);
self.bump();
}
/// The interface thread enters `stage` of a frame, timed whatever the activity around it, so a
/// frame the system runs while a file dialog waits for the user is timed too. The activity
/// before it applies again when the guard is dropped.
pub fn enter_timed(&self, stage: Stage) -> ActivityGuard<'_> {
self.enter(stage);
self.activity(Activity::None)
}
/// The interface thread starts `activity`; it ends when the guard is dropped, and the activity
/// before it applies again.
pub fn activity(&self, activity: Activity) -> ActivityGuard<'_> {
let before = Activity::from_u8(self.activity.swap(activity as u8, Ordering::Relaxed));
self.bump();
ActivityGuard { beacon: self, before }
}
/// The interface thread runs the command `id`. An id that is not a command id's shape (longer
/// than [`MAX_COMMAND_ID`] characters, or with characters other than ASCII letters, digits, `.`,
/// `_` and `-`) is kept as `(other)`: ids can come from saved files and the control channel. An
/// id already in the list moves to its end.
pub fn command(&self, id: &str) {
self.bump();
let shaped = id.len() <= MAX_COMMAND_ID && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
let kept = if shaped { id } else { "(other)" };
let mut commands = self.commands.lock().unwrap_or_else(PoisonError::into_inner);
if commands.back().is_some_and(|last| last == kept) {
return;
}
let entry = match commands.iter().position(|c| c == kept) {
Some(i) => commands.remove(i).unwrap_or_else(|| kept.to_string()),
None => {
if commands.len() == RECENT_COMMANDS {
commands.pop_front();
}
kept.to_string()
}
};
commands.push_back(entry);
}
/// A pass of some window had input ([`watch_input`]).
pub fn input(&self) {
self.input.store(true, Ordering::Relaxed);
}
/// Whether a pass of some window had input since the last call.
pub fn take_input(&self) -> bool {
self.input.swap(false, Ordering::Relaxed)
}
/// A pass of window `id` sent it commands that hand it to the system ([`hands_off`],
/// [`watch_input`]).
pub fn hand_off(&self, id: egui::ViewportId) {
let mut windows = self.handed_off.lock().unwrap_or_else(PoisonError::into_inner);
if !windows.contains(&id) {
windows.push(id);
}
}
/// The windows a pass handed to the system since the last call.
pub fn take_handed_off(&self) -> Vec<egui::ViewportId> {
std::mem::take(&mut *self.handed_off.lock().unwrap_or_else(PoisonError::into_inner))
}
/// A frame ended with `time`, with `documents` documents open.
pub fn frame(&self, time: FrameTime, documents: usize) {
self.documents.store(documents, Ordering::Relaxed);
let mut frames = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
if frames.len() == RECENT_FRAMES {
frames.pop_front();
}
frames.push_back(time);
}
/// The current marks.
pub fn sample(&self) -> Sample {
let step = self.step.load(Ordering::Acquire);
Sample { step, stage: Stage::from_u8(self.stage.load(Ordering::Relaxed)), activity: Activity::from_u8(self.activity.load(Ordering::Relaxed)) }
}
/// The ids of the last [`RECENT_COMMANDS`] commands, oldest first; `None` while the interface
/// thread is writing them.
pub fn recent_commands(&self) -> Option<Vec<String>> {
let commands = match self.commands.try_lock() {
Ok(c) => c,
Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => return None,
};
Some(commands.iter().cloned().collect())
}
/// The last [`RECENT_FRAMES`] frames' times, oldest first; `None` while the interface thread is
/// writing them.
pub fn recent_frames(&self) -> Option<Vec<FrameTime>> {
let frames = match self.frames.try_lock() {
Ok(f) => f,
Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => return None,
};
Some(frames.iter().copied().collect())
}
/// The documents open at the end of the last frame.
pub fn documents(&self) -> usize {
self.documents.load(Ordering::Relaxed)
}
}
/// Whether a pass's input asks for the next frame at once: events, or files dropped or hovered.
pub fn had_input(raw: &egui::RawInput) -> bool {
!raw.events.is_empty() || !raw.dropped_files.is_empty() || !raw.hovered_files.is_empty()
}
/// Mark on `beacon` every pass of every window of `ctx` that had input ([`had_input`]): the main
/// window's, after the host's input hook added its own, and those of the windows shown in line
/// (floating panels and documents), whose input does not pass through that hook. Mark as well every
/// pass of a window shown in line that sends its window commands that hand it to the system
/// ([`hands_off`]), before egui passes them on; the main window's are read at the frame's end.
pub fn watch_input(beacon: &'static Beacon, ctx: &egui::Context) {
ctx.on_begin_pass(
"VectorCraft hang report input",
std::sync::Arc::new(move |ui| {
if ui.ctx().input(|i| had_input(&i.raw)) {
beacon.input();
}
}),
);
ctx.on_end_pass(
"VectorCraft hang report hand-off",
std::sync::Arc::new(move |ui| {
if ui.ctx().viewport_id() != egui::ViewportId::ROOT && ui.ctx().viewport(|vp| hands_off(&vp.commands)) {
beacon.hand_off(ui.ctx().viewport_id());
}
}),
);
}
/// Whether `commands` minimize or hide their window, or hand it to the system to move or resize:
/// the system may hold back the next frame until the user is done.
pub fn hands_off(commands: &[egui::ViewportCommand]) -> bool {
use egui::ViewportCommand as C;
commands.iter().any(|c| matches!(c, C::Minimized(true) | C::Visible(false) | C::StartDrag | C::BeginResize(_)))
}
/// The window whose end of frame sets the stage ([`after_frame`]): the main window when it is
/// `main_shown`; otherwise a window shown in line (a floating panel or document) that `viewports`
/// (the main window's input) gives as focused and not minimized; otherwise none.
pub fn shown_window(main_shown: bool, viewports: &egui::ViewportIdMap<egui::ViewportInfo>) -> Option<egui::ViewportId> {
if main_shown {
return Some(egui::ViewportId::ROOT);
}
viewports.iter().find(|(id, v)| **id != egui::ViewportId::ROOT && v.focused == Some(true) && v.minimized != Some(true)).map(|(id, _)| *id)
}
/// The stage at the end of a frame: [`Stage::Drawing`] when a pass had `input` and a window is
/// `shown` (focused, not minimized or hidden: [`shown_window`]), since input asks for the next
/// frame at once; otherwise [`Stage::Idle`]. A frame that sends that window `commands` that
/// minimize or hide it, or hand it to the system to move or resize ([`hands_off`]), also ends idle.
pub fn after_frame(input: bool, shown: bool, commands: &[egui::ViewportCommand]) -> Stage {
if input && shown && !hands_off(commands) { Stage::Drawing } else { Stage::Idle }
}
/// Ends an [`Activity`] when dropped ([`Beacon::activity`]).
pub struct ActivityGuard<'a> {
beacon: &'a Beacon,
before: Activity,
}
impl Drop for ActivityGuard<'_> {
fn drop(&mut self) {
self.beacon.activity.store(self.before as u8, Ordering::Relaxed);
self.beacon.bump();
}
}
/// A [`SystemClipboard`] whose calls are marked on [`BEACON`] as clipboard activity. The desktop
/// app wraps the clipboard the interface thread uses; the background probe's own clipboard stays
/// unmarked.
pub struct Marked(pub Box<dyn SystemClipboard>);
impl SystemClipboard for Marked {
fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> {
let _mark = BEACON.activity(Activity::ClipboardWrite);
self.0.write(flavours)
}
fn holds_ours(&mut self) -> bool {
let _mark = BEACON.activity(Activity::ClipboardRead);
self.0.holds_ours()
}
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
let _mark = BEACON.activity(Activity::ClipboardRead);
self.0.read(mimes)
}
fn has(&mut self, mimes: &[&'static str]) -> bool {
let _mark = BEACON.activity(Activity::ClipboardRead);
self.0.has(mimes)
}
fn read_deferred(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let _mark = BEACON.activity(Activity::ClipboardRead);
self.0.read_deferred(mimes)
}
fn change_count(&mut self) -> Option<u64> {
let _mark = BEACON.activity(Activity::ClipboardRead);
self.0.change_count()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_mark_moves_the_step_and_the_stage_reads_back() {
let b = Beacon::new();
let first = b.sample();
assert_eq!((first.stage, first.activity), (Stage::Idle, Activity::None));
b.enter(Stage::Interface);
let s = b.sample();
assert!(s.step > first.step);
assert_eq!(s.stage, Stage::Interface);
b.command("edit.copy");
assert!(b.sample().step > s.step);
b.enter(Stage::Idle);
assert!(!b.sample().stage.busy());
}
#[test]
fn an_activity_ends_with_its_guard_and_restores_the_one_before() {
let b = Beacon::new();
{
let _write = b.activity(Activity::ClipboardWrite);
{
let _read = b.activity(Activity::ClipboardRead);
assert_eq!(b.sample().activity, Activity::ClipboardRead);
}
assert_eq!(b.sample().activity, Activity::ClipboardWrite);
}
assert_eq!(b.sample().activity, Activity::None);
}
#[test]
fn only_the_last_commands_and_frames_are_kept_oldest_first() {
let b = Beacon::new();
for n in 0..RECENT_COMMANDS + 3 {
b.command(&format!("cmd.{n}"));
}
let commands = b.recent_commands().unwrap_or_default();
assert_eq!(commands.len(), RECENT_COMMANDS);
assert_eq!(commands.first().map(String::as_str), Some("cmd.3"));
assert_eq!(commands.last().map(String::as_str), Some("cmd.10"));
for n in 0..RECENT_FRAMES + 2 {
b.frame(FrameTime { work_ms: n as f32, previous_total_ms: None }, 2);
}
let frames = b.recent_frames().unwrap_or_default();
assert_eq!(frames.len(), RECENT_FRAMES);
assert_eq!(frames.first().map(|f| f.work_ms), Some(2.0));
assert_eq!(b.documents(), 2);
}
#[test]
fn a_command_run_every_frame_does_not_push_out_the_ones_before() {
let b = Beacon::new();
for n in 0..RECENT_COMMANDS - 2 {
b.command(&format!("cmd.{n}"));
}
// Two panels that each run a query every frame.
for _ in 0..100 {
b.command("symbol.list");
b.command("swatch.list");
}
b.command("cmd.0");
let commands = b.recent_commands().unwrap_or_default();
let want: Vec<String> = ["cmd.1", "cmd.2", "cmd.3", "cmd.4", "cmd.5", "symbol.list", "swatch.list", "cmd.0"].map(String::from).to_vec();
assert_eq!(commands, want);
}
#[test]
fn a_frame_with_input_ends_drawing_unless_the_window_is_hidden_or_handed_to_the_system() {
use egui::ViewportCommand as C;
assert_eq!(after_frame(true, true, &[]), Stage::Drawing);
assert_eq!(after_frame(true, true, &[C::Focus]), Stage::Drawing);
assert_eq!(after_frame(false, true, &[]), Stage::Idle);
assert_eq!(after_frame(true, false, &[]), Stage::Idle);
for c in [C::Minimized(true), C::Visible(false), C::StartDrag, C::BeginResize(egui::ResizeDirection::East)] {
assert_eq!(after_frame(true, true, std::slice::from_ref(&c)), Stage::Idle, "{c:?}");
}
}
#[test]
fn input_is_events_or_files() {
let mut raw = egui::RawInput::default();
assert!(!had_input(&raw));
raw.hovered_files.push(egui::HoveredFile::default());
assert!(had_input(&raw));
#[derive(Debug)]
struct Dropped;
impl egui::DroppedFile for Dropped {
fn path(&self) -> &std::path::Path {
std::path::Path::new("a.svg")
}
fn bytes(&self) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
}
let mut raw = egui::RawInput::default();
raw.dropped_files.push(std::sync::Arc::new(Dropped));
assert!(had_input(&raw));
let mut raw = egui::RawInput::default();
raw.events.push(egui::Event::PointerGone);
assert!(had_input(&raw));
}
#[test]
fn input_in_a_window_shown_in_line_is_marked() {
static B: Beacon = Beacon::new();
// The host runs a window shown in line as its own pass, with that window's input.
let child_events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let events = child_events.clone();
egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| {
let id = viewport.ids.this;
let viewports = std::iter::once((id, egui::ViewportInfo::default())).collect();
let input = egui::RawInput { viewport_id: id, viewports, events: events.take(), ..Default::default() };
ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear();
});
let ctx = egui::Context::default();
ctx.set_embed_viewports(false);
watch_input(&B, &ctx);
let child = egui::ViewportId::from_hash_of("floating panel");
let frame = |main: Vec<egui::Event>| {
ctx.run_ui(egui::RawInput { events: main, ..Default::default() }, |ui| {
ui.ctx().show_viewport_immediate(child, egui::ViewportBuilder::default(), |_, _| {});
})
.textures_delta
.clear();
};
frame(Vec::new());
assert!(!B.take_input(), "no input anywhere");
child_events.replace(vec![egui::Event::PointerGone]);
frame(Vec::new());
assert!(B.take_input(), "the floating window's input");
assert!(!B.take_input(), "taken");
frame(vec![egui::Event::PointerGone]);
assert!(B.take_input(), "the main window's input");
}
#[test]
fn a_frame_run_while_a_dialog_waits_is_timed() {
let b = Beacon::new();
let _dialog = b.activity(Activity::Dialog);
assert!(!b.sample().busy(), "the dialog waits for the user");
{
let _timed = b.enter_timed(Stage::Interface);
assert!(b.sample().busy(), "a frame inside the dialog's wait");
b.enter(Stage::Drawing);
}
assert_eq!(b.sample().activity, Activity::Dialog, "the dialog again");
assert!(!b.sample().busy());
}
#[test]
fn a_window_shown_in_line_handed_to_the_system_is_marked() {
static B: Beacon = Beacon::new();
egui::Context::set_immediate_viewport_renderer(|ctx, mut viewport| {
let id = viewport.ids.this;
let viewports = std::iter::once((id, egui::ViewportInfo::default())).collect();
let input = egui::RawInput { viewport_id: id, viewports, ..Default::default() };
ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear();
});
let ctx = egui::Context::default();
ctx.set_embed_viewports(false);
watch_input(&B, &ctx);
let child = egui::ViewportId::from_hash_of("floating panel");
let frame = |command: Option<egui::ViewportCommand>, main: Option<egui::ViewportCommand>| {
ctx.run_ui(egui::RawInput::default(), |ui| {
ui.ctx().show_viewport_immediate(child, egui::ViewportBuilder::default(), |ui, _| {
if let Some(c) = command.clone() {
ui.ctx().send_viewport_cmd(c);
}
});
if let Some(c) = main.clone() {
ui.ctx().send_viewport_cmd(c);
}
})
.textures_delta
.clear();
};
frame(None, None);
assert!(B.take_handed_off().is_empty(), "nothing handed off");
frame(Some(egui::ViewportCommand::StartDrag), None);
assert_eq!(B.take_handed_off(), [child], "the floating window starts a move");
assert!(B.take_handed_off().is_empty(), "taken");
frame(Some(egui::ViewportCommand::Focus), None);
assert!(B.take_handed_off().is_empty(), "another command");
frame(None, Some(egui::ViewportCommand::StartDrag));
assert!(B.take_handed_off().is_empty(), "the main window's commands are read at the frame's end");
}
#[test]
fn a_focused_window_shown_in_line_is_the_shown_window() {
use egui::{ViewportId, ViewportIdMap, ViewportInfo};
let child = ViewportId::from_hash_of("document window");
let info = |focused: bool, minimized: bool| ViewportInfo { focused: Some(focused), minimized: Some(minimized), ..Default::default() };
let map = |root: ViewportInfo, window: ViewportInfo| -> ViewportIdMap<ViewportInfo> {
[(ViewportId::ROOT, root), (child, window)].into_iter().collect()
};
assert_eq!(shown_window(true, &map(info(true, false), info(false, false))), Some(ViewportId::ROOT));
assert_eq!(shown_window(false, &map(info(false, false), info(true, false))), Some(child), "the document window has the focus");
assert_eq!(shown_window(false, &map(info(false, false), info(true, true))), None, "minimized");
assert_eq!(shown_window(false, &map(info(false, false), info(false, false))), None, "no window has the focus");
assert_eq!(shown_window(false, &map(info(true, false), info(false, false))), None, "the main window is not shown");
}
#[test]
fn the_marked_clipboard_marks_its_calls() {
type Seen = std::sync::Arc<Mutex<Vec<Activity>>>;
struct Probe(Seen);
impl Probe {
fn see(&self) {
self.0.lock().unwrap().push(BEACON.sample().activity);
}
}
impl SystemClipboard for Probe {
fn write(&mut self, _: &[Flavour]) -> Result<(), String> {
self.see();
Ok(())
}
fn holds_ours(&mut self) -> bool {
self.see();
false
}
fn read(&mut self, _: &[&'static str]) -> Option<Flavour> {
self.see();
None
}
fn has(&mut self, _: &[&'static str]) -> bool {
self.see();
false
}
}
let seen = Seen::default();
let mut m = Marked(Box::new(Probe(seen.clone())));
let _ = m.write(&[]);
let _ = m.read(&[]);
let _ = m.has(&[]);
let _ = m.holds_ours();
assert_eq!(BEACON.sample().activity, Activity::None);
assert_eq!(*seen.lock().unwrap(), vec![Activity::ClipboardWrite, Activity::ClipboardRead, Activity::ClipboardRead, Activity::ClipboardRead]);
}
#[test]
fn ids_that_are_not_command_ids_are_kept_as_other() {
let b = Beacon::new();
b.command("file.open");
b.command("/home/someone/private plan.vectorcraft");
b.command(&"y".repeat(MAX_COMMAND_ID));
b.command(&"x".repeat(MAX_COMMAND_ID + 1));
let commands = b.recent_commands().unwrap_or_default();
// Both are `(other)`, which moves to the end the second time.
assert_eq!(commands, vec!["file.open".to_string(), "y".repeat(MAX_COMMAND_ID), "(other)".into()]);
}
#[test]
fn a_reader_does_not_wait_while_the_commands_are_being_written() {
let b = Beacon::new();
b.command("edit.paste");
let held = b.commands.lock().unwrap_or_else(PoisonError::into_inner);
assert_eq!(b.recent_commands(), None);
drop(held);
assert_eq!(b.recent_commands(), Some(vec!["edit.paste".to_string()]));
}
}
+14
View File
@@ -2282,6 +2282,7 @@ font-technology Variable Променливи
Options for Selection… Опции за селектиране…
Options: Опции:
Options… Опции…
Organic Fades Органични преливания
or more spaces with a tab или повече интервала с табулация
Order: Ред:
Ordinals Поредни номера
@@ -2473,6 +2474,7 @@ font-technology Variable Променливи
Presets: Предварителни настройки:
Press Натиснете
Preview Преглед
Preview: Преглед:
Preview All Layers Преглед на всички слоеве
Preview in Browser Преглед в браузър
Preview in Browser needs the desktop app (the web downloads files instead) Прегледът в браузър изисква настолното приложение (уеб версията изтегля файловете вместо това)
@@ -2565,6 +2567,8 @@ digits Malayalam Малаялам
Range: Диапазон:
Raster Effects Растерен ефект
Raster File Format: Растерен файлов формат:
Include Placed Images Включване на поставените изображения
Include Fill Hatches Включване на щриховките на запълванията
Raster Sample Size: Растерен размер на пробата:
Raster/Vector Balance: Баланс растер/вектор:
Rasterize Растеризиране
@@ -2745,6 +2749,10 @@ digits Malayalam Малаялам
Replace Font Замяна на шрифт
Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Заменете го с друг файл или го игнорирайте: неговите изображения ще продължат да показват записания с документа преглед.
Replace Spine Замяна на оста
Create Spine Създаване на ос
Create Spine: Създаване на ос:
Always Винаги
Never Никога
Replace Symbol Замяна на символ
Reset Transformation Нулиране на трансформацията
Replace With Font Замяна с шрифт
@@ -5889,6 +5897,7 @@ axis Y Axis Y ос
Version: {version} Версия: {version}
Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID.
Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Автоматизация поиска инсталирането на тази приставка. За да я инсталирате, изберете Обект › Приставки › Инсталиране на приставка… сами.
File SHA-256: {hash} SHA-256 на файла: {hash}
Read the objects it is given Четене на обектите, които получава
Change, add and delete objects in the document Промяна, добавяне и изтриване на обекти в документа
@@ -6560,6 +6569,11 @@ breakText Glyphs Глифи
No importer plug-ins installed Няма инсталирани плъгини за импортиране
Read files you open in its format and make documents from them Четене на файлове, които отваряте в неговия формат, и създаване на документи от тях
# Copy Troubleshooting Info
Copy Troubleshooting Info Копиране на информация за отстраняване на проблеми
@msg Copied the troubleshooting info Информацията за отстраняване на проблеми е копирана
@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Последната сесия на VectorCraft спря да отговаря, преди да се затвори. Помощ › Копиране на информация за отстраняване на проблеми копира подробностите за доклад за грешка
# Safe Mode
Safe Mode… Безопасен режим…
Safe Mode Безопасен режим
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -256,6 +256,10 @@
Blend Options… Opcije stapanja…
Expand Proširi
Replace Spine Zamijeni kičmu
Create Spine Kreiraj kičmu
Create Spine: Kreiraj kičmu:
Always Uvijek
Never Nikad
Reverse Spine Obrni kičmu
Reverse Front to Back Obrni od naprijed prema nazad
Envelope Distort Izobličenje omotnicom
@@ -556,6 +560,7 @@
Gaussian Blur… Gaussovo zamućenje…
View Prikaz
Preview Pregled
Preview: Pregled:
Overprint Preview Pregled pretiska
Pixel Preview Pregled piksela
Trim View Prikaz obrezivanja
@@ -826,6 +831,7 @@
Spectrum Gradients Gradijenti spektra
Sky Gradients Gradijenti neba
Neutral Gradients Neutralni gradijenti
Organic Fades Organski prelazi
Duotone Gradients Duoton gradijenti
Radial Glows Radijalni sjajevi
Save Swatch Library… Sačuvaj biblioteku uzoraka boja…
@@ -2360,6 +2366,8 @@ digits Malayalam Malajalam
Export Selected Art Only Izvezi samo odabrani crtež
Number of Colors: Broj boja:
Raster File Format: Format rasterske datoteke:
Include Placed Images Uključi postavljene slike
Include Fill Hatches Uključi šrafure ispuna
True colour needs version 2004 or later: the nearest of 256 colours is written. Prava boja zahtijeva verziju 2004 ili noviju: zapisuje se najbliža od 256 boja.
Type becomes outlines, and strokes a CAD line can't draw become filled shapes. Tekst postaje obrisi, a potezi koje CAD linija ne može nacrtati postaju ispunjeni oblici.
Type stays text, and every stroke is a line with its lineweight and dashes. Tekst ostaje tekst, a svaki potez je linija sa svojom debljinom i crticama.
@@ -5910,6 +5918,8 @@ axis Y Axis Y osa
Version: {version} Verzija: {version}
Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID.
Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatizacija je zatražila instalaciju ovog dodatka. Da biste ga instalirali, izaberite Objekat › Dodaci › Instaliraj dodatak… sami.
@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatizacija je zatražila instalaciju ovog dodatka. Da biste ga instalirali, izaberite Objekat › Dodaci › Instaliraj dodatak… sami.
@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees „{name}” je drugi modul od dodatka s ID-om {_1} i dobio bi postavke i predmemoriju sačuvane za njega: instalirajte ga s `replace: true` kada korisnik pristane
File SHA-256: {hash} SHA-256 datoteke: {hash}
Read the objects it is given Čitati objekte koje dobije
@@ -6611,6 +6621,11 @@ shape Open Otvoren
No importer plug-ins installed Nisu instalirani dodaci za uvoz
Read files you open in its format and make documents from them Čitati datoteke koje otvarate u njegovom formatu i od njih praviti dokumente
# Copy Troubleshooting Info
Copy Troubleshooting Info Kopiraj informacije za rješavanje problema
@msg Copied the troubleshooting info Informacije za rješavanje problema kopirane
@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report Posljednja sesija VectorCrafta prestala je odgovarati prije zatvaranja. Pomoć › Kopiraj informacije za rješavanje problema kopira detalje za prijavu greške
# Safe Mode
Safe Mode… Sigurni način rada…
Safe Mode Sigurni način rada
Can't render this file because it contains an unexpected character in line 2 and column 73.
+21
View File
@@ -2917,6 +2917,7 @@ digits Malayalam Malaiàlam
Options for Selection… Opcions per a la selecció…
Options: Opcions:
Options… Opcions…
Organic Fades Esvaïments orgànics
or more spaces with a tab o més espais amb un tabulador
Orange Taronja
Order: Ordre:
@@ -3207,6 +3208,7 @@ digits Malayalam Malaiàlam
Press Quality Qualitat d’impressió
Pressure Pressió
Preview Previsualització
Preview: Previsualització:
Preview (1 inch on the page) Previsualització (1 polzada a la pàgina)
Preview All Layers Previsualitza totes les capes
Preview in Browser Previsualitza al navegador
@@ -3308,6 +3310,8 @@ digits Malayalam Malaiàlam
Range: Interval:
Raster Effects Efectes de ràster
Raster File Format: Format de fitxer de ràster:
Include Placed Images Inclou les imatges col·locades
Include Fill Hatches Inclou les trames dels emplenaments
Raster Sample Size: Mida de mostra de ràster:
Raster/Vector Balance: Equilibri ràster/vector:
Rasterize Rasteritza
@@ -3494,6 +3498,10 @@ digits Malayalam Malaiàlam
Replace Font Reemplaça el tipus de lletra
Replace it with another file, or ignore it: its images keep showing the preview saved with the document. Reemplaça’l per un altre fitxer o ignora’l: les seves imatges continuaran mostrant la previsualització desada amb el document.
Replace Spine Reemplaça l’espina
Create Spine Crea l’espina
Create Spine: Crea l’espina:
Always Sempre
Never Mai
Replace Symbol Reemplaça el símbol
Reset Transformation Restableix la transformació
Replace With Font Reemplaça per un tipus de lletra
@@ -6122,6 +6130,8 @@ digits Malayalam Malaiàlam
Version: {version} Versió: {version}
Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID?
This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID.
Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatització ha demanat d’instal·lar aquest complement. Per instal·lar-lo, tria Objecte › Complements › Instal·la el complement… tu mateix.
@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Una automatització ha demanat d’instal·lar aquest complement. Per instal·lar-lo, tria Objecte › Complements › Instal·la el complement… tu mateix.
@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees «{name}» és un mòdul diferent del complement amb l’ID {_1} i rebria la configuració i la memòria cau desades per a aquest: instal·la’l amb `replace: true` quan l’usuari hi estigui d’acord
File SHA-256: {hash} SHA-256 del fitxer: {hash}
Read the objects it is given Llegir els objectes que rep
@@ -6184,6 +6194,12 @@ digits Malayalam Malaiàlam
@msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles
@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra
@msg command {name}: {e} ordre {name}: {e}
@msg manifest: {e} manifest: {e}
@msg manifest: {e} at line {line} column {column} manifest: {e} (línia {line}, columna {column})
@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` ha de ser una llista d’ordres, cadascuna amb `id` i `label`
@msg command {name} must be an object with an `id` and a `label` l’ordre {name} ha de ser un objecte amb `id` i `label`
@msg missing field `{key}` falta el camp `{key}`
@msg duplicate field `{key}` el camp `{key}` està repetit
@msg only a filter or a live effect declares `commands` només un filtre o un efecte dinàmic declara `commands`
@msg “{name}” › {label}: {e} «{name}» › {label}: {e}
@msg the module doesn't have the SHA-256 `hash` gives: nothing was installed el mòdul no té el SHA-256 que indica `hash`: no s’ha instal·lat res
@@ -6831,6 +6847,11 @@ breakText Glyphs Glifs
@msg only an exporter or an importer declares `extensions` només un exportador o un importador declara `extensions`
@msg an importer always gets an import's budget: leave `budget` out un importador sempre rep el pressupost d’una importació: ometeu `budget`
# Copy Troubleshooting Info
Copy Troubleshooting Info Copia la informació de resolució de problemes
@msg Copied the troubleshooting info S’ha copiat la informació de resolució de problemes
@msg The last session of VectorCraft stopped responding before it closed. Help › Copy Troubleshooting Info copies the details for a bug report La darrera sessió del VectorCraft va deixar de respondre abans de tancar-se. Ajuda › Copia la informació de resolució de problemes copia els detalls per a un informe d’error
# Safe Mode
Safe Mode… Mode segur…
Safe Mode Mode segur
Can't render this file because it contains an unexpected character in line 2 and column 73.
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more