Merge main into feat/scripts-api-d8c-rasterize-capture

This commit is contained in:
dotCooCoo
2026-11-30 15:27:15 -08:00
107 changed files with 9529 additions and 661 deletions
+5 -6
View File
@@ -1,11 +1,10 @@
name: Cache prune
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
# not run again. The entry it replaced would stay until the next main run, and with it the cache
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg
# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once
# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions
# actions/cache-prune).
on:
workflow_run:
workflows: [CI]
+2 -28
View File
@@ -50,8 +50,8 @@ jobs:
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
# builds everything from source.
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
# nothing and builds everything from source.
cache-workspace-crates: true
cold-build: ${{ github.event_name == 'schedule' }}
packages: >-
@@ -59,32 +59,6 @@ jobs:
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
libgl1-mesa-dev
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
cache-prune:
name: cache prune
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 170
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@main
continue-on-error: true
with:
watch: true
watch-minutes: 160
saving-jobs: |
^gate( / cache warm \(.*\))?$
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
Generated
+1
View File
@@ -9049,6 +9049,7 @@ dependencies = [
"vectorcraft-effects",
"vectorcraft-geom 0.25.1",
"vectorcraft-pathops 0.25.1",
"vectorcraft-render",
"vectorcraft-testkit",
"vectorcraft-text",
]
+11
View File
@@ -48,3 +48,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
tempfile = "3"
vectorcraft-testkit = { workspace = true }
serde_json = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"apps/vectorcraft/src/mac_fonts.rs",
"apps/vectorcraft/src/prefs_dir.rs",
"apps/vectorcraft/src/profile.rs",
"apps/vectorcraft/src/system_fonts.rs",
"apps/vectorcraft/src/windows_cores.rs",
"crates/plugins/tests/fixtures/desaturate.wasm",
]
+53 -11
View File
@@ -1,4 +1,4 @@
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
#[cfg(feature = "wgpu")]
use super::gpu;
use super::nightly_session;
use super::prefs::{flush, save_tick};
@@ -44,7 +44,7 @@ impl eframe::App for App {
if let Some(window_frame) = self.window_frame.as_mut() {
window_frame();
}
// The characters Alt + keypad codes typed (#5108).
// The keypad digits of Alt + keypad codes leave the frame (#5108).
#[cfg(windows)]
super::windows_alt_codes::raw_input_hook(raw);
// Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil).
@@ -107,7 +107,7 @@ impl eframe::App for App {
// Plug-ins still loading end before the launch marker does (the macOS exit below skips
// dropping the app).
self.app.session.cancel_plugin_loads();
end_before_teardown(self.frames);
end_before_teardown(self.frames, self.graphics_loss.happened());
}
}
@@ -202,16 +202,58 @@ impl App {
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
/// On every platform, the process also ends here when the window's graphics device was lost
/// (`device_lost`, #6374). A frame the lost device could not present stays acquired, and releasing
/// the window's surface as eframe tears it down then panics in wgpu (gfx-rs/wgpu#9277).
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
/// failure then starts the app again on another adapter (#651).
#[allow(unused_variables)]
fn end_before_teardown(frames: u64) {
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
if frames >= gpu::STARTUP_FRAMES {
safe_mode::end_launch();
log::info!("quitting");
log::logger().flush();
std::process::exit(0);
fn end_before_teardown(frames: u64, device_lost: bool) {
if !ends_before_teardown(frames, device_lost) {
return;
}
if device_lost {
log::info!("the graphics device was lost: quitting before the window's graphics are torn down");
}
// `main` does these after the window, which this exit skips.
#[cfg(not(target_os = "macos"))]
single_instance::resign();
safe_mode::end_launch();
log::info!("quitting");
log::logger().flush();
std::process::exit(0);
}
/// Whether [`end_before_teardown`] ends the process: after the window's start-up, on macOS with
/// accessibility, or once the graphics device was lost.
#[cfg(feature = "wgpu")]
fn ends_before_teardown(frames: u64, device_lost: bool) -> bool {
frames >= gpu::STARTUP_FRAMES && (device_lost || cfg!(all(target_os = "macos", feature = "accessibility")))
}
/// Without wgpu there is no device-lost report, and the window is torn down as usual.
#[cfg(not(feature = "wgpu"))]
fn ends_before_teardown(_frames: u64, _device_lost: bool) -> bool {
false
}
#[cfg(all(test, feature = "wgpu"))]
mod tests {
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use super::*;
/// A device lost while the app runs ends the process before eframe releases the window's
/// surface, on every platform; before the window has started, the start-up restart takes over.
#[test]
fn a_lost_graphics_device_ends_the_process_before_teardown() {
let always = cfg!(all(target_os = "macos", feature = "accessibility"));
let (loss, ctx) = (GraphicsLoss::default(), egui::Context::default());
assert_eq!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), always, "no loss: the usual teardown");
let (l, c) = (loss.clone(), ctx.clone());
std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap();
assert!(loss.take().is_some(), "a frame handles the report");
assert!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), "after a loss the window is not torn down");
assert!(!ends_before_teardown(gpu::STARTUP_FRAMES - 1, loss.happened()), "during start-up the adapter restart runs");
}
}
+117 -16
View File
@@ -32,6 +32,12 @@
//! that adapter, as the next one in the order would be tried. Each restart leaves out one more
//! adapter, so it ends when none is left.
//!
//! When no adapter is picked at all, because none is left or no graphics backend started (wgpu
//! needs Vulkan, OpenGL 3.3 or OpenGL ES 3.0, and the driver of Intel's Ironlake graphics offers
//! none of them, so the window's surface failed "for any enabled backend" with no backend listed,
//! #2654), Linux and the BSDs start once more on Mesa's software renderer ([`Software`]); after
//! that, the error that ends the app says what the graphics driver needs.
//!
//! An adapter can also hang instead of failing: on a hybrid laptop with High Performance chosen,
//! the discrete GPU never put the window's first frame on the screen, with no error and no panic,
//! and the app stayed in the background without a window (#964). [`watch_first_frame`] gives the
@@ -853,7 +859,7 @@ pub fn watch_first_frame(startup: Arc<Startup>) {
// The new app records its own start.
startup.ended();
skip.push(failed.to_string());
match restart(&skip.join(",")) {
match restart(&skip.join(","), false) {
Ok(()) => std::process::exit(0),
Err(e) => {
log::error!("starting again failed: {e}");
@@ -950,6 +956,94 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st
picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p))
}
/// Whether a start whose window no graphics adapter could show may start again on Mesa's software
/// renderer, which draws OpenGL on the CPU (llvmpipe).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Software {
/// Linux and the BSDs, where Mesa provides OpenGL, and this start isn't on it yet.
Possible,
/// This start already draws on it: the app started again with [`SOFTWARE_ENV`], or the user
/// set `LIBGL_ALWAYS_SOFTWARE`.
Tried,
/// Windows and macOS, or a start that `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` chooses.
Unavailable,
}
impl Software {
/// This start's [`Software`], from the platform and the environment.
pub fn from_env() -> Self {
if cfg!(any(windows, target_os = "macos")) || explicit_choice() {
Software::Unavailable
} else if software_start() || std::env::var_os("LIBGL_ALWAYS_SOFTWARE").is_some() {
Software::Tried
} else {
Software::Possible
}
}
}
/// Set by the app when it starts again on Mesa's software renderer because no graphics adapter
/// could show the window (#2654).
pub const SOFTWARE_ENV: &str = "VECTORCRAFT_GPU_SOFTWARE";
/// Whether this start is the one the app made on Mesa's software renderer ([`SOFTWARE_ENV`]).
pub fn software_start() -> bool {
std::env::var_os(SOFTWARE_ENV).is_some()
}
/// The graphics APIs the window can draw with on this platform, for the error that ends the app
/// when no adapter can show it and for the note of a start on Mesa's software renderer.
pub const NEEDS: &str = if cfg!(windows) {
"Direct3D 12, OpenGL 3.3 or OpenGL ES 3.0"
} else if cfg!(target_os = "macos") {
"Metal"
} else {
"Vulkan, OpenGL 3.3 or OpenGL ES 3.0"
};
/// What follows the window's run ([`next`]).
#[derive(Debug, PartialEq, Eq)]
enum Next {
/// The window closed normally.
Done,
/// Start again without the adapters in `skip`, on Mesa's software renderer when `software`.
Restart { skip: Vec<String>, software: bool },
/// End the app with this error.
Stop(String),
}
/// What follows the window's run: `why` it failed (`None` when it closed normally), whether the
/// graphics failed, the `frames` the UI ran, the adapter `picked`, those left out (`skip`) and
/// whether the software renderer is still to try. A failure on an adapter while starting up starts
/// again without it. When no adapter was picked, because none can show the window or no graphics
/// backend started at all (an old GPU whose driver offers neither Vulkan nor OpenGL 3.3 or OpenGL
/// ES 3.0, such as Intel's Ironlake graphics, #2654), Linux and the BSDs start once more on Mesa's
/// software renderer, and after that the error says what the window needs.
fn next(why: Option<String>, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec<String>, software: Software) -> Next {
let Some(why) = why else { return Next::Done };
if let Some(failed) = restart_without(graphics_failed, frames, picked, &skip) {
log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it");
skip.push(failed.to_string());
return Next::Restart { skip, software: false };
}
if !graphics_failed {
return Next::Stop(why);
}
if picked.is_some() || frames >= STARTUP_FRAMES {
return Next::Stop(format!("{why} ({HELP})"));
}
match software {
Software::Possible => {
log::error!("no graphics adapter could show the window ({why}): starting again on Mesa's software renderer, which draws on the CPU");
Next::Restart { skip, software: true }
}
Software::Tried => Next::Stop(format!(
"{why}: no graphics adapter could show the window, not even Mesa's software renderer (the graphics driver needs {NEEDS}; {HELP})"
)),
Software::Unavailable => Next::Stop(format!("{why}: no graphics adapter could show the window (the graphics driver needs {NEEDS}; {HELP})")),
}
}
/// After the window's run: `Ok` when it closed normally or the app started again (see the module
/// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that
/// ended it.
@@ -957,28 +1051,35 @@ pub fn finish(outcome: Result<eframe::Result, String>, startup: &Startup) -> Res
// Whatever follows, this start didn't crash; a new app records its own start.
startup.ended();
let (why, graphics_failed) = match outcome {
Ok(Ok(())) => return Ok(()),
Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true),
Ok(Err(e)) => (e.to_string(), false),
Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)),
Ok(Ok(())) => (None, false),
Ok(Err(e @ eframe::Error::Wgpu(_))) => (Some(e.to_string()), true),
Ok(Err(e)) => (Some(e.to_string()), false),
Err(panic) => (Some(panic), GRAPHICS_PANIC.load(Ordering::Relaxed)),
};
let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr);
let mut skip = skipped();
let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else {
return Err(if graphics_failed { format!("{why} ({HELP})") } else { why });
};
log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it");
skip.push(failed.to_string());
restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}"))
let picked = startup.adapter.get().map(String::as_str);
match next(why.clone(), graphics_failed, frames, picked, skipped(), Software::from_env()) {
Next::Done => Ok(()),
Next::Stop(e) => Err(e),
Next::Restart { skip, software } => {
let why = why.unwrap_or_default();
restart(&skip.join(","), software).map_err(|e| format!("{why}; starting again failed: {e}"))
}
}
}
/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the
/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and
/// this returns only on failure; on Windows it starts beside this one, which then exits.
fn restart(skip: &str) -> std::io::Result<()> {
/// Start the app again with the same arguments, leaving out the adapters in `skip`, and on Mesa's
/// software renderer when `software` (`LIBGL_ALWAYS_SOFTWARE`, with [`SOFTWARE_ENV`] so it is
/// tried once). On Unix the new app replaces this process (same process id, so an AppImage keeps
/// its files mounted), and this returns only on failure; on Windows it starts beside this one,
/// which then exits.
fn restart(skip: &str, software: bool) -> std::io::Result<()> {
log::logger().flush();
let mut c = std::process::Command::new(std::env::current_exe()?);
c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip);
if software {
c.env("LIBGL_ALWAYS_SOFTWARE", "1").env(SOFTWARE_ENV, "1");
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt as _;
+43 -6
View File
@@ -602,15 +602,52 @@ fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() {
fn a_normal_exit_or_another_failure_does_not_restart() {
let startup = Startup::default();
assert_eq!(finish(Ok(Ok(())), &startup), Ok(()));
// No adapter was picked (none can show the window): the error is returned, nothing restarts.
let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into()));
assert_eq!(
finish(Ok(Err(none)), &startup),
Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})"))
);
let _ = startup.adapter.set("Vulkan:1002:164e".into());
GRAPHICS_PANIC.store(false, Ordering::Relaxed);
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
// The same, decided without starting anything.
let amd = Some("Vulkan:1002:164e");
for software in [Software::Possible, Software::Tried, Software::Unavailable] {
assert_eq!(next(None, false, 0, amd, vec![], software), Next::Done);
assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], software), Next::Stop("a bug".into()));
// A failure after start-up, or on an adapter already left out, is not the start's.
assert_eq!(next(Some("lost".into()), true, STARTUP_FRAMES, amd, vec![], software), Next::Stop(format!("lost ({HELP})")));
let skip = vec!["Vulkan:1002:164e".to_string()];
assert_eq!(next(Some("lost".into()), true, 0, amd, skip, software), Next::Stop(format!("lost ({HELP})")));
}
// An adapter that failed while starting up is left out, never with the software renderer.
assert_eq!(
next(Some("lost".into()), true, 0, amd, vec!["Gl:8086:0046".into()], Software::Possible),
Next::Restart { skip: vec!["Gl:8086:0046".into(), "Vulkan:1002:164e".into()], software: false }
);
}
/// #2654: on a ThinkPad T510 with Intel's Ironlake graphics, whose driver offers neither Vulkan
/// nor OpenGL 3.3 or OpenGL ES 3.0, wgpu started no backend, so the window's surface failed before
/// any adapter was listed and the app ended; started with `LIBGL_ALWAYS_SOFTWARE=1`, it ran on
/// llvmpipe. With no adapter picked, Linux starts once more on Mesa's software renderer, keeping
/// the adapters already left out, and the error after that says what the driver needs.
#[test]
fn a_start_no_adapter_can_show_tries_the_software_renderer_once() {
let surface = "WGPU error: Failed to create surface for any enabled backend: {}";
let skip = vec!["Vulkan:8086:0046".to_string()];
assert_eq!(next(Some(surface.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true });
// No adapter left that can show the window, after restarts without each.
let none = "WGPU error: Adapter selection failed: no graphics adapter can show the window";
assert_eq!(next(Some(none.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true });
// Already on the software renderer: the app ends, saying what the window needs.
let Next::Stop(tried) = next(Some(surface.into()), true, 0, None, skip.clone(), Software::Tried) else {
panic!("a start already on the software renderer starts again")
};
assert!(tried.starts_with(surface), "{tried}");
assert!(tried.contains("not even Mesa's software renderer") && tried.contains(NEEDS) && tried.contains(HELP), "{tried}");
// Windows, macOS or a backend the user chose: no software renderer to start on.
let Next::Stop(unavailable) = next(Some(surface.into()), true, 0, None, skip, Software::Unavailable) else {
panic!("a start without the software renderer starts again")
};
assert!(unavailable.contains(NEEDS) && unavailable.contains(HELP) && !unavailable.contains("Mesa"), "{unavailable}");
// A failure outside the graphics never starts again.
assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], Software::Possible), Next::Stop("a bug".into()));
}
/// A log folder of its own for each test.
+34 -7
View File
@@ -396,15 +396,36 @@ fn read_command_line(
/// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`).
#[cfg(target_os = "linux")]
fn opens_through_xwayland(pref: Option<&str>) -> bool {
if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
use xwayland::Choice;
let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached);
// On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there.
match &choice {
Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {}
Choice::NoXDisplay { x11: true } => {
log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland")
}
Choice::NoXDisplay { x11: false } => log::info!(
"opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland"
),
Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"),
Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"),
Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"),
}
if !choice.xwayland() {
return false;
}
if !xwayland::x11_libraries_found() {
log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland");
if let Choice::Pen(name) = &choice {
log::warn!(
"pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it"
);
} else {
log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland");
}
return false;
}
if pref != Some("x11") {
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
if let Choice::Pen(name) = &choice {
log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
} else {
log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)");
}
@@ -722,14 +743,14 @@ fn main() -> std::process::ExitCode {
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
// is down; the message hook notes each pointer contact and whether it starts with the barrel
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
// characters Alt + keypad codes type (`windows_alt_codes`).
// keypad digits of Alt + keypad codes (`windows_alt_codes`).
#[cfg(windows)]
let options = {
use winit::platform::windows::EventLoopBuilderExtWindows as _;
let mut options = options;
options.event_loop_builder = Some(Box::new(|builder| {
builder.with_msg_hook(|msg| {
// Alt + keypad codes (#5108), which winit drops; neither hook consumes a message.
// Alt + keypad codes (#5108); neither hook consumes a message.
windows_alt_codes::msg_hook(msg);
windows_stylus::msg_hook(msg)
});
@@ -920,7 +941,13 @@ fn main() -> std::process::ExitCode {
let summary = adapter_summary(&rs.adapter.get_info());
log::info!("rendering with {summary} (power preference {power:?})");
created.created(&cc.egui_ctx);
if !gpu::skipped().is_empty() {
if gpu::software_start() {
// No graphics processor could show the window, so Mesa draws it on the CPU (#2654).
app.status(format!(
"No graphics processor could show the window, so VectorCraft started again on {summary}, which draws on the CPU and is slower. Showing it on the graphics processor needs a driver with {}",
gpu::NEEDS
));
} else if !gpu::skipped().is_empty() {
// A processor chosen in Settings can be the one that can't show the window.
if chosen_gpu {
app.status(format!(
+68 -3
View File
@@ -41,7 +41,7 @@
//! the rotation's range is 0°, and an axis a pen lacks reads nothing.
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use craft::behavior::PointerSample;
use craft::ui::runtime::pen::PenSource;
@@ -189,6 +189,8 @@ enum Update {
struct Pens {
devices: HashMap<u16, Device>,
last: HashMap<u16, [Option<f32>; 5]>,
/// The pens an event has come from, for the log.
heard: HashSet<u16>,
}
impl Pens {
@@ -197,10 +199,37 @@ impl Pens {
/// same id starts without them.
fn set_devices(&mut self, devices: impl IntoIterator<Item = Device>) {
let devices: HashMap<u16, Device> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)));
let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d));
self.last.retain(|id, _| unchanged(id));
self.heard.retain(|id| unchanged(id));
self.devices = devices;
}
/// The names of the pens listed, by device id, for the log.
fn pen_names(&self) -> Vec<&str> {
let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect();
pens.sort_by_key(|d| d.id);
pens.into_iter().map(|d| d.name.as_str()).collect()
}
/// The pens listed, as the log line says it: under XWayland on a Wayland session this tells
/// whether XWayland lists the pen at all (#5622).
fn summary(&self) -> String {
let names = self.pen_names();
if names.is_empty() {
"the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string()
} else {
format!("pens listed: {}", names.join(", "))
}
}
/// The name of pen `id` when this is the first event from it since it was listed, for the log:
/// it tells whether the pen's events reach the app at all.
fn first_event(&mut self, id: u16) -> Option<&str> {
let device = self.devices.get(&id).filter(|d| d.is_pen())?;
self.heard.insert(id).then_some(device.name.as_str())
}
/// A raw motion or button event of device `id`, with the valuators that changed.
fn handle(&mut self, id: u16, valuators: impl IntoIterator<Item = (u16, f64)>) -> Update {
let Some(device) = self.devices.get(&id) else { return Update::Keep };
@@ -231,6 +260,9 @@ impl Pens {
/// A raw event as the X server sends it: its valuator mask and the values of the valuators
/// set in it. A pen's sample or another pointer's `None` goes into `pen`.
fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) {
if let Some(name) = self.first_event(id) {
log::info!("tablet: events arrive from the pen {name:?}");
}
if let Update::Set(sample) = self.handle(id, valuators(mask, values)) {
pen.set(sample);
}
@@ -304,6 +336,7 @@ mod x11 {
.map_err(|e| format!("XISelectEvents failed: {e}"))?;
let mut pens = Pens::default();
pens.set_devices(query_devices(&conn));
log::info!("tablet: {}", pens.summary());
std::thread::Builder::new()
.name("vectorcraft-tablet-x11".into())
.spawn(move || run(&conn, &mut pens, &pen))
@@ -321,7 +354,14 @@ mod x11 {
let values: Vec<f64> = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect();
pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values);
}
Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)),
Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => {
let before = pens.summary();
pens.set_devices(query_devices(conn));
let after = pens.summary();
if after != before {
log::info!("tablet: {after}");
}
}
_ => {}
}
}
@@ -623,6 +663,31 @@ mod tests {
assert!(s.pressure < 0.001, "{}", s.pressure);
}
/// #5622: the log names the pens the X server lists (XWayland's included) and the first event
/// from each, once, again after the pen is listed anew, and never for a mouse.
#[test]
fn the_log_names_the_pens_listed_and_the_first_event_from_each() {
let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators());
let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators());
let mut pens = Pens::default();
assert!(pens.summary().contains("lists no pen"), "{}", pens.summary());
pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]);
assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16");
assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16"));
assert_eq!(pens.first_event(11), None, "once");
assert_eq!(pens.first_event(4), None, "a mouse");
assert_eq!(pens.first_event(99), None, "a device not listed");
// Listed again unchanged: still heard. Another device under the same id: heard anew.
pens.set_devices([eraser.clone(), mouse(4), stylus]);
assert_eq!(pens.first_event(11), None);
pens.set_devices([eraser, mouse(4), pen(11)]);
assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus"));
// The events go into the feed as before.
let source = PenSource::default();
pens.raw_event(&source, 12, &[0b100], &[65535.0]);
assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0)));
}
#[test]
fn fixed_point_values() {
assert_eq!(fp3232(3, 1 << 31), 3.5);
+62 -113
View File
@@ -4,14 +4,12 @@
//! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a
//! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code
//! with a leading 0, else its OEM code page), the convention every Windows text field follows
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit
//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which
//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees
//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes
//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed
//! text, so the Type tool (or a panel's text field) types it like any other character, in the
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
//! so they don't run a shortcut bound to Alt and a digit.
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit reports
//! that character as a key press of its own with the character as its text (storytold/winit W36),
//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives
//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message
//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad
//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame.
//!
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
@@ -29,11 +27,11 @@ use std::cell::RefCell;
use egui::{Event, Key};
#[cfg(windows)]
const WM_KEYDOWN: u32 = 0x0100;
const WM_KEYUP: u32 = 0x0101;
const WM_CHAR: u32 = 0x0102;
const WM_SYSKEYDOWN: u32 = 0x0104;
const WM_SYSKEYUP: u32 = 0x0105;
#[cfg(windows)]
const WM_SYSCHAR: u32 = 0x0106;
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
const VK_NUMPAD0: usize = 0x60;
@@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
/// keypad (the keypad's own keys clear it).
const EXTENDED_KEY: isize = 1 << 24;
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
thread_local! {
/// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it.
static CODES: RefCell<AltCodes> = RefCell::new(AltCodes::default());
}
/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue.
/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue.
#[derive(Default)]
struct AltCodes {
/// Keypad digits typed while Alt has been held.
digits: usize,
/// Alt came up after keypad digits: the next character message is the code's character.
armed: bool,
/// A high surrogate waiting for its low half.
high: Option<u16>,
/// Characters the codes typed, for the next frame.
typed: String,
/// The digits of the keypad presses and releases with Alt held since the last frame, which
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
/// out of the frame.
@@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
impl AltCodes {
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
/// and `lparam` (its flags).
/// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system
/// key.
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
let keypad = match message {
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
_ => None,
};
if let Some(d) = keypad {
// Windows sends a key pressed with Alt held as a system key.
if message == WM_SYSKEYDOWN {
self.digits += 1;
self.armed = false;
}
if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP)
&& let Some(d) = keypad_digit(wparam, lparam)
{
self.keypad_events.push(d);
return;
}
match message {
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
// Any other key ends the sequence and keeps its own meaning.
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => {
self.armed = self.digits > 0;
self.digits = 0;
}
WM_CHAR | WM_SYSCHAR if self.armed => {
let unit = (wparam & 0xffff) as u16;
if (0xd800..0xdc00).contains(&unit) {
self.high = Some(unit);
return;
}
let units: Vec<u16> = self.high.take().into_iter().chain([unit]).collect();
self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control()));
self.armed = false;
}
_ => {}
}
}
fn reset(&mut self) {
self.digits = 0;
self.armed = false;
self.high = None;
}
/// Hand the frame `events` the characters typed since the last frame, as typed text, and take
/// out the keypad digits typed with Alt held.
/// Take out of the frame `events` the keypad digits typed with Alt held since the last frame.
/// The character a code types comes from winit, as typed text.
fn drain(&mut self, events: &mut Vec<Event>) {
let mut keypad = std::mem::take(&mut self.keypad_events);
if !keypad.is_empty() {
events.retain(|e| {
let Event::Key { key, modifiers, .. } = e else {
return true;
};
if !modifiers.alt {
return true;
}
// The first keypad key still to take out that egui reports as `key`.
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
match keypad.iter().position(stands_for) {
Some(i) => {
keypad.remove(i);
false
}
None => true,
}
});
}
if !self.typed.is_empty() {
events.push(Event::Text(std::mem::take(&mut self.typed)));
if keypad.is_empty() {
return;
}
events.retain(|e| {
let Event::Key { key, modifiers, .. } = e else {
return true;
};
if !modifiers.alt {
return true;
}
// The first keypad key still to take out that egui reports as `key`.
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
match keypad.iter().position(stands_for) {
Some(i) => {
keypad.remove(i);
false
}
None => true,
}
});
}
}
/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type,
/// and hands each message to `windows_symbol_chars`. It never consumes the message.
/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands
/// each message to `windows_symbol_chars`. It never consumes the message.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn msg_hook(msg: *const std::ffi::c_void) {
@@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) {
}
}
/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text.
/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out.
pub fn raw_input_hook(raw: &mut egui::RawInput) {
CODES.with(|c| {
if let Ok(mut c) = c.try_borrow_mut() {
@@ -196,6 +149,9 @@ mod tests {
use super::*;
const ALT: usize = 0x12;
const WM_KEYDOWN: u32 = 0x0100;
const WM_KEYUP: u32 = 0x0101;
const WM_CHAR: u32 = 0x0102;
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
@@ -215,59 +171,53 @@ mod tests {
}
#[test]
fn an_alt_code_types_its_character_when_alt_comes_up() {
fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() {
let mut c = AltCodes::default();
alt_code(&mut c, "0176", 0xB0);
alt_code(&mut c, "0151", 0x2014);
let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)];
// winit reports each code's character as typed text.
let mut events = vec![
key(Key::Num0, true, true),
key(Key::Num0, true, false),
key(Key::Num1, false, true),
Event::Text("°".into()),
Event::Text("—".into()),
];
c.drain(&mut events);
// The keypad digits typed with Alt are gone (eight presses and eight releases, two here);
// the digit typed without Alt stays, and the characters follow.
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]);
// the digit typed without Alt stays, and each character stays once.
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]);
let mut events = vec![key(Key::Num0, true, true)];
c.drain(&mut events);
assert_eq!(events.len(), 1, "counts don't carry over to a later frame");
}
#[test]
fn a_character_without_a_code_before_it_is_left_to_winit() {
fn characters_are_left_to_winit() {
let mut c = AltCodes::default();
// A plain key press's character (winit types it), and Alt pressed and released alone.
// A plain key press's character, Alt pressed and released alone, and a code's character.
c.message(WM_KEYDOWN, 0x41, 0);
c.message(WM_CHAR, usize::from(b'a'), 0);
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, usize::from(b'b'), 0);
alt_code(&mut c, "0176", 0xB0);
let mut events = vec![];
c.drain(&mut events);
assert!(events.is_empty(), "{events:?}");
}
#[test]
fn another_key_while_alt_is_held_cancels_the_code() {
fn alt_with_another_key_keeps_its_shortcut() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
// Alt+F: a shortcut, not a code.
c.message(WM_SYSKEYDOWN, 0x46, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0x41, 0);
let mut events = vec![];
let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)];
c.drain(&mut events);
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
}
#[test]
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0xD83D, 0);
c.message(WM_CHAR, 0xDE00, 0);
let mut events = vec![];
c.drain(&mut events);
assert_eq!(events, vec![Event::Text("😀".into())]);
assert_eq!(events, vec![key(Key::F, true, true)]);
}
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
@@ -284,7 +234,7 @@ mod tests {
}
#[test]
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() {
let mut c = AltCodes::default();
alt_code_numlock_off(&mut c, "0176", 0xB0);
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
@@ -296,7 +246,7 @@ mod tests {
}
events.push(key(Key::Home, false, true));
c.drain(&mut events);
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
assert_eq!(events, vec![key(Key::Home, false, true)]);
}
#[test]
@@ -309,11 +259,11 @@ mod tests {
let mut events =
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
c.drain(&mut events);
assert_eq!(events, vec![Event::Text("—ê".into())]);
assert!(events.is_empty(), "{events:?}");
}
#[test]
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
fn the_separate_navigation_keys_still_move_the_caret() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT, 0);
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
@@ -322,7 +272,6 @@ mod tests {
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
c.message(WM_KEYUP, ALT, 0);
c.message(WM_CHAR, 0x41, 0);
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
c.drain(&mut events);
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
+110 -20
View File
@@ -22,18 +22,61 @@ use std::path::{Path, PathBuf};
const X11_LIBS: &[&str] =
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or
/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and
/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after
/// the other checks.
pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
/// What the pen check found: the name of the first pen, `None` when there is none, or why the
/// device list could not be read.
pub type PenProbe = Result<Option<String>, String>;
/// Where the window opens, and why, as [`choose`] decides it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Choice {
/// Not a Wayland session: the window opens where winit opens it.
NotWayland,
/// XWayland, because Linux Display Server is X11 (XWayland).
Chosen,
/// XWayland, because the pen of this name is attached.
Pen(String),
/// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland
/// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen.
NoXDisplay { x11: bool },
/// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there.
NativeWayland,
/// Wayland: no pen is attached.
NoPen,
/// Wayland: the input devices could not be listed, for this reason.
NoDeviceList(String),
}
impl Choice {
/// Whether the window opens through XWayland.
pub fn xwayland(&self) -> bool {
matches!(self, Self::Chosen | Self::Pen(_))
}
}
/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11`
/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen
/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland
/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs
/// only after the other checks.
pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> PenProbe) -> Choice {
let set = |name: &str| var(name).is_some_and(|v| !v.is_empty());
let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY");
let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0");
match pref {
Some("x11") => session,
_ => session && !native_wayland && pen(),
if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") {
return Choice::NotWayland;
}
let x11 = pref == Some("x11");
if !set("DISPLAY") {
return Choice::NoXDisplay { x11 };
}
if x11 {
return Choice::Chosen;
}
if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") {
return Choice::NativeWayland;
}
match pen() {
Ok(Some(name)) => Choice::Pen(name),
Ok(None) => Choice::NoPen,
Err(e) => Choice::NoDeviceList(e),
}
}
@@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140;
const ABS_X: u32 = 0x00;
const ABS_Y: u32 = 0x01;
/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen.
pub fn pen_attached() -> bool {
std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices))
/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read.
pub fn pen_attached() -> PenProbe {
std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}"))
}
/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose
/// Is a pen among the input devices `/proc/bus/input/devices` lists?
#[cfg(test)]
fn has_pen(devices: &str) -> bool {
find_pen(devices).is_some()
}
/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its
/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose
/// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as
/// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code,
/// `BTN_TOOL_PEN` included, but has no absolute axes.
fn has_pen(devices: &str) -> bool {
devices.split("\n\n").any(|device| {
let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name));
bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN))
&& bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y))
fn find_pen(devices: &str) -> Option<String> {
devices.split("\n\n").find_map(|device| {
let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name));
let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN))
&& field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y));
pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string()))
})
}
@@ -147,6 +198,11 @@ mod tests {
panic!("the pen check ran")
}
/// [`choose`] as a yes or no, with a pen check that finds a pen or none.
fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland()
}
#[test]
fn xwayland_only_when_chosen_on_wayland_with_an_x_display() {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
@@ -183,6 +239,40 @@ mod tests {
assert!(wanted(Some("x11"), &native, no_probe));
}
/// #5622: the choice names why the window stays on Wayland, where the pen does not reach it,
/// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen
/// that is not listed or a device list that can't be read.
#[test]
fn the_choice_says_why_the_window_stays_on_wayland() {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]);
let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]);
let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string()));
let never = || -> PenProbe { panic!("the pen check ran") };
assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland);
assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false });
assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true });
assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen);
assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland);
assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string()));
assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen);
let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string()));
assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string()));
for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] {
assert!(!stays.xwayland(), "{stays:?}");
}
assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland());
}
/// The pen check names the pen it found, for the log.
#[test]
fn the_pen_check_names_the_pen() {
assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen"));
let without = WITH_PEN.split("\n\n").take(2).collect::<Vec<_>>().join("\n\n");
assert_eq!(find_pen(&without), None);
assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line");
}
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
/// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests.
const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\
+4
View File
@@ -24,3 +24,7 @@ craft-image-codecs = { workspace = true }
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
vectorcraft-affinity = { path = ".", features = ["synth"] }
# The files of other crates that this crate's tests compile or read, for CI's test selection.
[package.metadata.craft]
reads = ["xtask/affinity-corpus.sha256", "xtask/src/sha256.rs"]
+8 -6
View File
@@ -394,9 +394,11 @@ pub enum DimensionSource {
/// it is vertical. Versions without this source do not open the file.
Extent {
node: NodeId,
/// Placed with Use Preview Bounds on: the points are moved out to the outside of the
/// strokes the path paints ([`preview_extents`]), the width or height that W and H show.
/// Versions without it measure between the outermost points themselves.
/// The points are moved out to the outside of the strokes the path paints
/// ([`preview_extents`]), the width or height that W and H show with Use Preview Bounds on.
/// The Dimension tool sets it on every dimension of a whole path it places. Without it,
/// as in files saved before the tool set it and in versions without it, the dimension
/// measures between the outermost points themselves.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
preview: bool,
},
@@ -431,9 +433,9 @@ impl DimensionSource {
}
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
/// A node without a path, or missing from both, counts as changed. For a dimension of a whole
/// path placed with Use Preview Bounds on, so does a change to the strokes the path paints
/// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw
/// on it, and the path being made into a guide or released from one.
/// path measured to the outside of its strokes (`preview`), so does a change to the strokes the
/// path paints ([`stroked_by`]): their appearance, the node they come from, or which arrowheads
/// they draw on it, and the path being made into a guide or released from one.
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
let strokes = matches!(self, Self::Extent { preview: true, .. });
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
+27 -10
View File
@@ -600,9 +600,9 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
}
let (parts, bounds) = solid_parts(shapes, b);
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
return built_solids(id, p, &parts, bounds, object_face_limit()).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None)
let built = built_solids_cast(id, p, &parts, bounds, object_face_limit(), true, false, None)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
@@ -1025,13 +1025,30 @@ thread_local! {
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
/// ([`cast_shadow`]) count too.
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The limit [`object_face_limit`] gives on this thread: [`MAX_OBJECT_FACES`] unless a test sets
/// a lower one, so that a test of the limit builds small solids.
pub(crate) static OBJECT_FACE_LIMIT: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_OBJECT_FACES) };
}
/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together:
/// [`MAX_OBJECT_FACES`].
#[cfg(not(test))]
fn object_face_limit() -> usize {
MAX_OBJECT_FACES
}
/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together:
/// [`MAX_OBJECT_FACES`], or the lower limit a test set in [`OBJECT_FACE_LIMIT`].
#[cfg(test)]
fn object_face_limit() -> usize {
OBJECT_FACE_LIMIT.with(std::cell::Cell::get)
}
/// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from
/// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as
/// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its
/// faces not counted); a fill's is an error. The faces of the solids kept count together: once they
/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and
/// pass `limit` ([`object_face_limit`] for the art) the result is an error, and
/// no later part is built. An error ends the iterator.
fn built_solids<'a>(
id: &'a str,
@@ -1211,7 +1228,7 @@ fn rects_overlap(a: Rect, b: Rect) -> bool {
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as
/// [`object_face_limit`] and the copies within the allowance, each added face counted as
/// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint.
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
let per_face = items
@@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, p
.unwrap_or(0)
.max(1);
let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face;
MAX_OBJECT_FACES.saturating_sub(faces).min(affordable)
object_face_limit().saturating_sub(faces).min(affordable)
}
/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a
@@ -2403,7 +2420,7 @@ fn surfaces_with(
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
let mut layouts: Vec<SolidLayout> = vec![];
let mut surfaces_before = 0usize;
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier);
let made = built_solids_cast(&fx.id, &p, &parts, bounds, object_face_limit(), cast, membrane, carrier);
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
let item: &AppearanceItem = item;
let layout = map_art.as_ref().map(|_| {
@@ -2471,7 +2488,7 @@ fn surfaces_with(
if solids.iter().any(|s| ordered(s.4)) {
// A stroke face that passes through a fill wall or another stroke's face is cut where it
// does. The pieces count against the limits as the faces did: cutting stops before the
// faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that
// faces pass object_face_limit() or their paint copies pass the allowance, so an effect that
// draws uncut still draws.
let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect();
let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes);
@@ -2940,7 +2957,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
// their handles. A stroke left out places none of its own. When a fill's solid can't be
// built, or the solids together pass the limit, the art draws its source and no piece
// places a handle.
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None)
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None)
.collect::<Result<Vec<_>, String>>()
.map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect())
.unwrap_or_default();
@@ -3065,7 +3082,7 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option<usize>, in
let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default();
let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default();
kept = kept.saturating_add(facets.len());
if kept > MAX_OBJECT_FACES {
if kept > object_face_limit() {
return None;
}
listed(&surfaces, &facets, &mut out);
@@ -3309,7 +3326,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
Err(e) => return Err(e),
};
kept = kept.saturating_add(solid.facets.len());
if kept > MAX_OBJECT_FACES {
if kept > object_face_limit() {
return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string());
}
match solid.mesh() {
+28 -6
View File
@@ -1642,17 +1642,36 @@ fn polygon_node(id: u64, corners: usize) -> Node {
Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0))
}
/// Sets the faces the solids of one object keep together ([`OBJECT_FACE_LIMIT`]) to a lower limit
/// on this thread, and sets [`MAX_OBJECT_FACES`] again when dropped, so that a test of the limit
/// builds small solids.
struct FaceLimit(usize);
impl FaceLimit {
fn set(limit: usize) -> Self {
Self(OBJECT_FACE_LIMIT.with(|l| l.replace(limit)))
}
}
impl Drop for FaceLimit {
fn drop(&mut self) {
OBJECT_FACE_LIMIT.with(|l| l.set(self.0));
}
}
/// A group whose members' solids each fit, but not all of them together, draws its source art, and
/// the commands that check the effect report the error, as do its mesh and its wireframe; one
/// member fewer, within the limit, draws.
/// member fewer, exactly at the limit, draws. The limit is lowered to three members' faces.
#[test]
fn a_groups_solids_together_past_the_limit_draw_the_source() {
let member = polygon_node(1, 16_384);
let member = polygon_node(1, 64);
let mut alone = member.clone();
alone.appearance.effects.push(fx(EXTRUDE, json!({})));
let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") };
let limit = 3 * each;
let _limit = FaceLimit::set(limit);
// Members stacked in one place each build the same solid.
let fits = MAX_OBJECT_FACES / each;
let fits = limit / each;
let group = |count: usize| {
let members = (0..count)
.map(|k| {
@@ -1703,16 +1722,19 @@ fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() {
}
/// A fill and strokes whose solids each fit, but not all of them together, draw the source art,
/// and the strokes after the one past the limit are not left out to make room.
/// and the strokes after the one past the limit are not left out to make room. The limit is
/// lowered to the fill's faces and three strokes'.
#[test]
fn a_fill_and_strokes_together_past_the_limit_draw_the_source() {
let mut n = polygon_node(1, 16_384);
let mut n = polygon_node(1, 64);
n.appearance.effects.push(fx(EXTRUDE, json!({})));
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0));
n.appearance.items.push(stroke.clone());
// Strokes alike each build the same solid.
let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") };
let fits = (MAX_OBJECT_FACES - fill) / each;
let limit = fill + 3 * each;
let _limit = FaceLimit::set(limit);
let fits = (limit - fill) / each;
assert!(fits >= 2, "{fill} + {fits} × {each}");
n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1));
assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}");
+3 -3
View File
@@ -12,8 +12,8 @@ use vectorcraft_three_d::Facet;
use super::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane,
is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts,
union_bounds,
is_three_d, label_of, members, object_face_limit, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources,
solid_parts, union_bounds,
};
use crate::{GeomContext, is_geometry};
@@ -258,7 +258,7 @@ pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFac
}
let (parts, bounds) = solid_parts(shapes, b);
// The solids the art draws, each past the limits of the object's solids together as it is.
for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) {
for f in built_solids(&fx.id, &p, &parts, bounds, object_face_limit()) {
out.extend(f?.iter().flatten().map(face));
}
Ok(out)
+12 -1
View File
@@ -117,7 +117,7 @@ zune-core = { workspace = true }
# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs).
craft-jxl = { workspace = true }
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
# tests/group3_reference.rs compares it with.
# tests/it/group3_reference.rs compares it with.
hayro-ccitt = { workspace = true }
craft-stream-codecs = { workspace = true }
vectorcraft-affinity = { workspace = true, features = ["synth"] }
@@ -144,3 +144,14 @@ ruzstd = { workspace = true }
vectorcraft-js = { workspace = true }
# A bundled font's own glyph boxes, for the glyph bounds tests.
skrifa = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"crates/affinity/tests/support/corpus.rs",
"crates/affinity/tests/support/text_fixture.rs",
"crates/apischema/src/conformance.rs",
"crates/plugins/tests/fixtures/desaturate.wasm",
"xtask/affinity-corpus.sha256",
"xtask/src/sha256.rs",
]
+17 -1
View File
@@ -679,8 +679,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option<Affine> {
}
/// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1),
/// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`).
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`),
/// and for a color with a component too large to store ([`color_is_finite`]).
pub fn color_value(v: &Value) -> Option<Color> {
given_color(v).filter(color_is_finite)
}
/// Is every component of `c` finite? A number past `f32::MAX`, such as `{"c": 1e300}`, is stored
/// as an infinity.
pub fn color_is_finite(c: &Color) -> bool {
match *c {
Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|x| x.is_finite()),
Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|x| x.is_finite()),
Color::Gray { k } => k.is_finite(),
}
}
/// The color `v` gives, as [`color_value`] reads it, with its components unchecked.
fn given_color(v: &Value) -> Option<Color> {
match v {
Value::String(s) if hex_with_alpha(s) => None,
// A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours).
@@ -3,7 +3,7 @@
//! the bridges connect, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
@@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
has_selection,
bridge
)]
@@ -61,17 +61,30 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
return Err(bad(C, "select at most 2000 circles to bridge"));
}
let circles: Vec<(NodeId, pt::Circle)> = {
// The circles, and why the first object that is not one is refused.
let (circles, why): (Vec<(NodeId, pt::Circle)>, Option<&str>) = {
let d = &s.doc()?.doc;
let editable = d.editable();
d.paint_order(roots.iter().copied())
let mut why = None;
let circles = d
.paint_order(roots.iter().copied())
.into_iter()
.filter_map(|id| match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)),
_ => None,
.filter_map(|id| {
let found = match &d.node(id)?.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => pt::circle_of(path).map(|c| (id, c)),
_ => None,
};
if found.is_none() && why.is_none() {
why = Some(not_a_circle(d, id, editable(id)));
}
found
})
.collect()
.collect();
(circles, why)
};
if let Some(why) = why {
return Err(bad(C, format!("select two or more circles to bridge: {why}")));
}
if circles.len() != roots.len() || circles.len() < 2 {
return Err(bad(C, "select two or more circles to bridge"));
}
@@ -117,7 +130,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
}
beside.finish(d)?;
} else {
// Each shape's topmost circle becomes its outline (a plain path now) and the others go.
// Each shape's topmost circle becomes its outline (a plain path now) and the others go,
// with each group they leave empty.
let mut gone = vec![];
for (members, outline) in shapes {
let Some((&top, rest)) = members.split_last() else { continue };
@@ -128,7 +142,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
made.push(top);
gone.extend_from_slice(rest);
}
let parents: Vec<NodeId> = gone.iter().filter_map(|id| d.parent_of(*id)).collect();
remove_each(d, &gone)?;
remove_emptied(d, parents)?;
}
sel.set(made.iter().chain(&alone).copied());
Ok(made)
@@ -156,6 +172,44 @@ fn members(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out
}
/// Why object `id`, which is not a circle the command bridges, is refused; `editable` says whether it can be
/// edited (not hidden or locked).
fn not_a_circle(d: &Document, id: NodeId, editable: bool) -> &'static str {
// A pie spanning the whole turn, or none of it, is the whole ellipse.
let whole = |(start, end): (f64, f64)| {
let span = (end - start).rem_euclid(360.0);
span < 1e-9 || 360.0 - span < 1e-9
};
match d.node(id).map(|n| &n.kind) {
_ if !editable => "a selected object is hidden or locked",
// A transform that stretches an ellipse leaves its stored width and height as they were, so one stored with
// equal width and height gets the general message.
Some(NodeKind::Path { live: Some(live), guide: false, clipping: false, .. }) if matches!(**live, LiveShape::Ellipse { w, h, pie, .. } if whole(pie) && w != h) => {
"an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height"
}
Some(NodeKind::Compound { .. }) => "a compound path is not a circle: release it first",
_ => "a selected object is not a circle",
}
}
/// Remove each of `parents` that is left with nothing in it, and then each group above it left with
/// nothing in it in turn. Layers stay.
fn remove_emptied(d: &mut Document, parents: Vec<NodeId>) -> Result<()> {
for parent in parents {
let mut at = Some(parent);
while let Some(id) = at {
match d.node(id) {
Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => {
at = d.parent_of(id);
d.remove(id)?;
}
_ => break,
}
}
}
Ok(())
}
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
@@ -2,7 +2,7 @@
//! gap, many circles joined to their neighbors within reach, and what it refuses.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::kurbo::Shape;
use crate::Session;
@@ -173,6 +173,50 @@ fn far_apart_nested_and_other_objects_are_refused() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
}
#[test]
fn a_refusal_says_why_an_object_is_not_a_circle() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
// A hand-drawn ellipse 1 pt taller than wide.
let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 80, "width": 40, "height": 41})).unwrap()["id"].as_u64().unwrap());
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let stretched = circle(&mut s, 300.0, 100.0, 20.0);
s.execute("object.transform", &json!({"ids": [stretched.0], "matrix": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let e = err(&mut s, json!({"ids": [a.0, oval.0]}));
assert!(
e.ends_with(
"select two or more circles to bridge: an ellipse whose width and height differ is not a circle: draw it with Shift held, or give it equal width and height"
),
"{e}"
);
let e = err(&mut s, json!({"ids": [a.0, square.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}");
// A circle stretched by a transform keeps its equal stored width and height, so it is not called unequal.
let equal = match s.doc().unwrap().doc.node(stretched).map(|n| &n.kind) {
Some(NodeKind::Path { live: Some(live), .. }) => matches!(**live, LiveShape::Ellipse { w, h, .. } if w == h),
_ => false,
};
assert!(equal, "the stretched circle keeps a live ellipse of equal width and height");
let e = err(&mut s, json!({"ids": [a.0, stretched.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is not a circle"), "{e}");
let e = err(&mut s, json!({"ids": [a.0]}));
assert!(e.ends_with("select two or more circles to bridge"), "one circle: {e}");
select(&mut s, &[b]);
s.execute("object.hide", &json!({})).unwrap();
let e = err(&mut s, json!({"ids": [a.0, b.0]}));
assert!(e.ends_with("select two or more circles to bridge: a selected object is hidden or locked"), "{e}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step for a refusal");
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = circle(&mut s, 300.0, 200.0, 20.0);
let e = err(&mut s, json!({"ids": [compound.0, c.0]}));
assert!(e.ends_with("select two or more circles to bridge: a compound path is not a circle: release it first"), "{e}");
}
/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100).
fn grid(s: &mut Session) -> Vec<NodeId> {
(0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect()
@@ -329,6 +373,118 @@ fn an_id_given_twice_is_one_circle() {
assert_eq!(top_level(&s), [b]);
}
/// The objects directly inside `id`.
fn inside(s: &Session, id: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
}
fn make(s: &mut Session, command: &str, ids: &[NodeId]) -> NodeId {
select(s, ids);
NodeId(s.execute(command, &json!({})).unwrap()["id"].as_u64().unwrap())
}
#[test]
fn a_group_the_bridged_circles_leave_empty_goes_in_the_same_undo_step() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let ga = make(&mut s, "object.group", &[a]);
let gb = make(&mut s, "object.group", &[b]);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(r["id"], json!(b.0));
assert_eq!(top_level(&s), [gb], "the lower circle's group, left empty, goes");
assert_eq!(inside(&s, gb), [b], "the outline stays in the upper circle's group");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(top_level(&s), [ga, gb]);
assert_eq!((inside(&s, ga), inside(&s, gb)), (vec![a], vec![b]));
// Kept circles leave their groups as they are.
s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap();
assert_eq!(top_level(&s), [ga, gb]);
assert_eq!(inside(&s, ga), [a]);
}
#[test]
fn groups_above_an_emptied_group_go_in_turn_and_a_group_with_other_objects_stays() {
let mut s = session();
// a in a group that is all of another group; c in a group with a square; b on the layer.
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 150.0, 100.0, 20.0);
let c = circle(&mut s, 200.0, 100.0, 20.0);
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let inner = make(&mut s, "object.group", &[a]);
let outer = make(&mut s, "object.group", &[inner]);
let gc = make(&mut s, "object.group", &[square, c]);
let layer = s.doc().unwrap().doc.layers[0].id;
let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap();
assert_eq!(ids(&r["ids"]), [c], "one shape, in the topmost circle's place");
assert_eq!(top_level(&s), [gc], "both groups around a go, b goes from the layer");
assert_eq!(inside(&s, gc), [c, square], "the group with the square stays");
let d = &s.doc().unwrap().doc;
assert!(d.node(inner).is_none() && d.node(outer).is_none());
assert!(d.node(layer).is_some(), "the layer stays");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(inside(&s, outer), [inner]);
assert_eq!(inside(&s, inner), [a]);
}
#[test]
fn a_compound_path_the_bridged_circles_leave_empty_goes() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let compound = make(&mut s, "object.compoundPath.make", &[a]);
assert_eq!(inside(&s, compound), [a]);
s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(top_level(&s), [b]);
assert!(s.doc().unwrap().doc.node(compound).is_none());
}
#[test]
fn a_selected_group_of_grouped_circles_keeps_only_the_outlines_group() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let ga = make(&mut s, "object.group", &[a]);
let gb = make(&mut s, "object.group", &[b]);
let outer = make(&mut s, "object.group", &[ga, gb]);
select(&mut s, &[outer]);
s.execute(BRIDGE, &json!({})).unwrap();
assert_eq!(top_level(&s), [outer]);
assert_eq!(inside(&s, outer), [gb], "the lower circle's group goes, the outline's stays");
assert_eq!(inside(&s, gb), [b]);
}
#[test]
fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let b = circle(&mut s, 160.0, 100.0, 20.0);
let c = circle(&mut s, 220.0, 100.0, 20.0);
// a below in the first layer, b and c in the sublayer: c's shape takes a's and b's places.
s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.layers.iter().any(|l| l.id != upper && l.children().is_some_and(|c| c.is_empty())), "the emptied layer stays");
assert_eq!(inside(&s, sub), [c]);
// The sublayer left with nothing in it stays too.
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
let b = circle(&mut s, 160.0, 100.0, 20.0);
s.execute("layer.setCurrent", &json!({"id": upper.0})).unwrap();
let c = circle(&mut s, 220.0, 100.0, 20.0);
s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap();
assert_eq!(inside(&s, sub), Vec::<NodeId>::new(), "the emptied sublayer stays");
assert_eq!(inside(&s, upper), [sub, c]);
}
#[test]
fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() {
let mut s = session();
+127 -5
View File
@@ -1,17 +1,19 @@
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by
//! Link Status selects the images and placed documents whose file is linked, embedded, missing or
//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins
//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's.
//! modified (#5526), saying which ones it had to leave out and why. Edit Points Only narrows the
//! selection to the anchor points selected in it, dropping selected segments and objects without
//! anchor points. Its submenu (Object › Plug-ins › Selection Tools), the Links panel's menu items
//! and the dialogs are the UI's.
#[cfg(test)]
mod tests;
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use serde_json::{Value, json};
use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use vectorcraft_doc::{AnchorRef, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point};
use super::super::links::{Status, statuses};
use super::super::panelcmds::listed_artboards;
@@ -47,6 +49,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
by_link_status
),
cmd!(
"addon.select.editPointsOnly",
"Edit Points Only",
["Object", "Plug-ins", "Selection Tools"],
None,
"{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step. In the desktop dialog, a successful preview or OK clears only that dialog's preview error if it is still the current status message → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}",
has_doc,
edit_points_only
),
]
}
@@ -193,3 +204,114 @@ fn by_link_status(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(out)
}
/// The anchor points of `path` that `refs` names, leaving out references to points it does not have.
fn on_path(path: &PathData, refs: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> {
refs.iter().copied().filter(|&(si, ai)| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())).collect()
}
/// The points at the ends of the segments `segments` of `path`.
fn segment_ends(path: &PathData, segments: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> {
let mut ends = BTreeSet::new();
for &(si, seg) in segments {
if let Some(sp) = path.subpaths.get(si) {
ends.extend([(si, seg), (si, (seg + 1) % sp.anchors.len().max(1))]);
}
}
ends
}
/// The paths inside container `n` with at least one anchor point, depth first, through the groups
/// and compound paths in it: hidden and locked objects (and what they hold), a Shaper Group's
/// original shapes, and paths made into guides while `guides_locked`, are left out.
fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) {
let originals = usize::from(n.extras().shaper.is_some());
for c in n.children().into_iter().flatten().skip(originals) {
if !c.visible || c.locked {
continue;
}
match &c.kind {
NodeKind::Path { guide: true, .. } if guides_locked => {}
NodeKind::Path { path, .. } if path.anchors().next().is_some() => out.push(c),
NodeKind::Group { .. } | NodeKind::Compound { .. } => paths_inside(c, guides_locked, out),
_ => {}
}
}
}
/// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it.
fn edit_points_only(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.select.editPointsOnly";
let keep_ends = match p.get("segmentEnds") {
None => false,
Some(value) => value.as_bool().ok_or_else(|| bad(C, "`segmentEnds` must be true or false"))?,
};
let guides_locked = s.menu.guides_locked;
let st = s.doc()?;
let (doc, sel) = (&st.doc, &st.selection);
if sel.objects.is_empty() {
return Err(bad(C, "select anchor points or segments first"));
}
// Each path once, in selection order, with its points kept: `None` for all of them.
let mut seen = HashSet::new();
let explicit: HashSet<NodeId> = sel.objects.iter().copied().filter(|id| sel.anchors.contains_key(id)).collect();
let mut kept: Vec<(NodeId, usize, Option<BTreeSet<AnchorRef>>)> = vec![];
for id in &sel.objects {
let Some(n) = doc.node(*id) else { continue };
if !doc.ancestry(*id).is_some_and(|ancestors| ancestors.iter().all(|id| doc.node(*id).is_some_and(|n| n.visible && !n.locked))) {
continue;
}
match &n.kind {
NodeKind::Path { path, .. } => {
let Some(refs) = sel.anchors.get(id) else {
let count = path.anchors().count();
if count > 0 && seen.insert(*id) {
kept.push((*id, count, None));
}
continue;
};
let mut picked = on_path(path, refs);
if let Some(segments) = sel.segments.get(id)
&& !keep_ends
{
let ends = segment_ends(path, segments);
picked.retain(|r| !ends.contains(r));
}
if !picked.is_empty() && seen.insert(*id) {
kept.push((*id, picked.len(), Some(picked)));
}
}
NodeKind::Group { .. } | NodeKind::Compound { .. } => {
let mut inside = vec![];
paths_inside(n, guides_locked, &mut inside);
for c in inside {
if explicit.contains(&c.id) {
continue;
}
if seen.insert(c.id) {
kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None));
}
}
}
_ => {}
}
}
let points: usize = kept.iter().map(|(_, n, _)| n).sum();
let objects: Vec<NodeId> = kept.iter().map(|(id, ..)| *id).collect();
let anchors: BTreeMap<NodeId, BTreeSet<AnchorRef>> = kept.into_iter().filter_map(|(id, _, set)| Some((id, set?))).collect();
if objects.is_empty() {
return Err(bad(C, "no anchor points are selected"));
}
let changed = objects != sel.objects || anchors != sel.anchors || !sel.segments.is_empty() || !sel.guides.is_empty();
let count = objects.len();
if changed {
s.select(|_, sel| {
let (key, key_anchor) = (sel.key.filter(|k| objects.contains(k)), sel.key_anchor);
sel.set(objects);
sel.anchors = anchors;
sel.key = key;
sel.key_anchor = key_anchor;
})?;
}
Ok(json!({ "changed": changed, "count": count, "points": points }))
}
@@ -337,3 +337,320 @@ mod by_link_status {
assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err());
}
}
/// Edit Points Only.
mod edit_points_only {
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use super::rect;
use crate::Session;
const C: &str = "addon.select.editPointsOnly";
/// A document with two rectangles, `a` and `b` (four anchors each, anchor 0 first).
fn two() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
let b = rect(&mut s, 100.0, 10.0, 50.0, 50.0);
(s, a, b)
}
/// Anchors 0 and 1 of `a`, anchor 3 of `b`, and then segment 1 of `b` (its ends are anchors 1 and 2).
fn mixed(s: &mut Session, a: NodeId, b: NodeId) {
let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]);
s.execute("select.anchorsMany", &json!({"items": items})).unwrap();
s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
}
fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
v.iter().copied().collect()
}
/// Selected objects, with the selected anchors of those selected in part.
type Picked = (Vec<NodeId>, BTreeMap<NodeId, BTreeSet<(usize, usize)>>);
/// The selected objects and their selected anchors.
fn picked(s: &Session) -> Picked {
let sel = &s.doc().unwrap().selection;
(sel.objects.clone(), sel.anchors.clone())
}
#[test]
fn selected_segments_drop_out_and_the_anchor_points_stay() {
let (mut s, a, b) = two();
mixed(&mut s, a, b);
let before = s.doc().unwrap().selection.clone();
assert_eq!(before.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)]), "a segment's ends move with it");
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r, json!({"changed": true, "count": 2, "points": 3}));
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![a, b]);
assert_eq!(sel.anchors[&a], refs(&[(0, 0), (0, 1)]));
assert_eq!(sel.anchors[&b], refs(&[(0, 3)]), "the segment's ends leave the selection");
assert!(sel.segments.is_empty(), "no segment stays selected");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes");
}
#[test]
fn segment_ends_stay_as_anchor_points_when_asked() {
let (mut s, a, b) = two();
mixed(&mut s, a, b);
let r = s.execute(C, &json!({"segmentEnds": true})).unwrap();
assert_eq!(r, json!({"changed": true, "count": 2, "points": 5}));
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)]));
assert!(sel.segments.is_empty());
// With the default, a path holding only a selected segment leaves the selection.
s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0]]})).unwrap();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
let r = s.execute(C, &json!({"segmentEnds": false})).unwrap();
assert_eq!(r, json!({"changed": true, "count": 1, "points": 1}));
assert_eq!(picked(&s), (vec![a], BTreeMap::from([(a, refs(&[(0, 2)]))])));
}
#[test]
fn a_selection_of_anchor_points_alone_is_left_as_it_is() {
let (mut s, a, b) = two();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]]})).unwrap();
let before = picked(&s);
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 1, "points": 2}));
assert_eq!(picked(&s), before);
// Paths selected whole keep all their points.
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 2, "points": 8}));
assert_eq!(picked(&s), (vec![a, b], BTreeMap::new()));
}
#[test]
fn explicit_anchor_picks_override_group_expansion_in_either_order() {
for group_first in [true, false] {
let (mut s, a, b) = two();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| {
sel.set(if group_first { vec![group, a] } else { vec![a, group] });
sel.anchors.insert(a, refs(&[(0, 0)]));
})
.unwrap();
let before = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().clone();
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 2, "points": 5}));
assert_eq!(s.doc().unwrap().selection.anchors[&a], refs(&[(0, 0)]));
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
let after = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap();
for ((_, i, old), (_, _, new)) in before.anchors().zip(after.anchors()) {
if i == 0 {
assert_ne!(new.p, old.p);
} else {
assert_eq!(new.p, old.p, "unselected anchors stay in place");
}
}
}
}
#[test]
fn hidden_or_locked_selected_nodes_and_their_ancestors_are_left_out() {
for locked in [false, true] {
for target in ["path", "group", "ancestor", "layer"] {
let (mut s, a, b) = two();
let good = rect(&mut s, 200.0, 10.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let blocked = match target {
"path" => a,
"layer" => s.doc().unwrap().doc.layers[0].id,
_ => group,
};
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let node = doc.node_mut(blocked).unwrap();
if locked {
node.locked = true;
} else {
node.visible = false;
}
let selected = if matches!(target, "path" | "ancestor") { a } else { group };
s.execute("select.set", &json!({"ids": [good.0, selected.0]})).unwrap();
if target == "layer" {
let before = s.doc().unwrap().selection.clone();
assert!(s.execute(C, &json!({})).is_err());
assert_eq!(s.doc().unwrap().selection, before);
} else {
s.execute(C, &json!({})).unwrap();
assert_eq!(picked(&s), (vec![good], BTreeMap::new()), "{target}, locked: {locked}");
}
}
}
}
#[test]
fn group_expansion_selects_each_descendant_path() {
let (mut s, _, _) = two();
let mut groups = vec![];
let mut paths = vec![];
for x in [10.0, 100.0, 200.0] {
let a = rect(&mut s, x, 100.0, 20.0, 20.0);
let b = rect(&mut s, x, 150.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
groups.push(NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()));
paths.extend([a, b]);
}
s.select(|_, sel| sel.set(groups)).unwrap();
s.execute(C, &json!({})).unwrap();
assert_eq!(picked(&s), (paths, BTreeMap::new()));
}
#[test]
fn appearance_row_commands_survive_preview_replacement_and_cancel() {
for index in [json!(1), Value::Null] {
for selection_preview in [false, true] {
let (mut s, a, b) = two();
mixed(&mut s, a, b);
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap();
s.begin_interaction("Drag").unwrap();
s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = !selection_preview;
if selection_preview {
s.preview(C, &json!({})).unwrap();
assert_eq!(s.appearance_item(), None);
} else {
s.preview("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
}
s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap();
let expected = index.as_u64().map(|i| i as usize);
s.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
assert_eq!(s.appearance_item(), expected, "replacement preserves the explicit row command");
s.cancel_interaction().unwrap();
assert_eq!(s.appearance_item(), expected, "cancel preserves the explicit row command");
}
}
}
#[test]
fn cancel_preserves_an_appearance_row_command_without_another_preview() {
for index in [json!(1), Value::Null] {
let (mut s, a, b) = two();
mixed(&mut s, a, b);
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap();
s.begin_interaction("Drag").unwrap();
s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = true;
s.preview(C, &json!({})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap();
s.cancel_interaction().unwrap();
assert_eq!(s.appearance_item(), index.as_u64().map(|i| i as usize));
}
}
#[test]
fn canceling_a_selection_preview_restores_the_active_appearance_item() {
let (mut s, a, b) = two();
mixed(&mut s, a, b);
s.execute("appearance.addFill", &json!({})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap();
let before = s.doc().unwrap().doc.node(a).unwrap().appearance.items.clone();
s.begin_interaction("Edit Points Only").unwrap();
s.preview(C, &json!({})).unwrap();
assert_eq!(s.appearance_item(), None);
s.preview(C, &json!({"segmentEnds": true})).unwrap();
assert_eq!(s.appearance_item(), None);
s.cancel_interaction().unwrap();
assert_eq!(s.appearance_item(), Some(0));
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let after = &s.doc().unwrap().doc.node(a).unwrap().appearance.items;
assert_ne!(after[0], before[0]);
assert_eq!(&after[1..], &before[1..]);
}
#[test]
fn whole_paths_keep_object_transforms_and_stroke_scaling() {
let (mut s, a, _) = two();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
let before = s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
s.execute(C, &json!({})).unwrap();
assert!(!s.doc().unwrap().selection.anchors.contains_key(&a));
s.execute("object.transform", &json!({"matrix": [2, 0, 0, 2, 0, 0], "strokes": true})).unwrap();
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width() > before);
}
#[test]
fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() {
let (mut s, a, b) = two();
let c = rect(&mut s, 200.0, 10.0, 20.0, 20.0);
let hidden = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [b.0, c.0, hidden.0, text.0]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
let d = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, d.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.doc().unwrap().selection.objects.clone();
assert_eq!(compound.len(), 1);
let members: Vec<NodeId> = s.doc().unwrap().doc.node(compound[0]).unwrap().children().unwrap().iter().map(|m| m.id).collect();
assert_eq!(members.len(), 2);
s.execute("select.set", &json!({"ids": [compound[0].0, group]})).unwrap();
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r, json!({"changed": true, "count": 4, "points": 16}), "{r}");
let mut want = members;
want.extend([b, c]);
assert_eq!(picked(&s), (want, BTreeMap::new()), "the hidden path and the type are left out");
}
#[test]
fn guide_paths_in_a_group_are_left_out_while_guides_are_locked() {
let (mut s, a, b) = two();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [b.0, text.0]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
s.execute("select.set", &json!({"ids": [group]})).unwrap();
let before = s.doc().unwrap().selection.clone();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("no anchor points are selected"), "{e}");
assert_eq!(s.doc().unwrap().selection, before);
s.execute("select.set", &json!({"ids": [a.0, group]})).unwrap();
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4}));
assert_eq!(picked(&s), (vec![a], BTreeMap::new()));
// Unlocked, the guide path is a path like any other.
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
s.execute("select.set", &json!({"ids": [group]})).unwrap();
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4}));
assert_eq!(picked(&s), (vec![b], BTreeMap::new()));
}
#[test]
fn nothing_to_keep_is_an_error_that_leaves_the_selection() {
let (mut s, a, b) = two();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute(C, &json!({})).is_err(), "nothing selected");
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]]})).unwrap();
s.execute("select.add", &json!({"ids": [text.0]})).unwrap();
let before = s.doc().unwrap().selection.clone();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("no anchor points are selected"), "{e}");
assert_eq!(s.doc().unwrap().selection, before);
for p in [
json!({"segmentEnds": null}),
json!({"segmentEnds": "yes"}),
json!({"segmentEnds": 1}),
json!({"segmentEnds": [true]}),
json!({"segmentEnd": true}),
] {
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap();
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap();
let before = s.doc().unwrap().selection.clone();
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().selection, before, "{p}");
}
assert!(Session::new().execute(C, &Value::Null).is_err(), "without a document");
}
}
+15 -2
View File
@@ -139,7 +139,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Appearance Item",
[],
None,
"{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it → {index}",
"{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it. A row set or cleared outside a drag's preview stays set or cleared when the preview is replaced or canceled → {index}",
has_selection,
set_active_item
),
@@ -174,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// The Appearance panel's active row, remembered for the selection it was chosen in.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ActiveItem {
doc: u64,
objects: Vec<NodeId>,
@@ -956,6 +956,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
let index = match p.get("index") {
Some(Value::Null) => {
s.active_appearance_item = None;
clear_preview_item(s);
return Ok(json!({ "index": Value::Null }));
}
Some(_) => index_param(p, "index", C)?,
@@ -968,9 +969,21 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
let doc = st.uid;
s.fill_active = fill;
s.active_appearance_item = Some(ActiveItem { doc, objects, index });
clear_preview_item(s);
Ok(json!({ "index": index }))
}
fn clear_preview_item(s: &mut Session) {
if !s.previewing {
if let Some(it) = s.active_mut().and_then(|st| st.interaction.as_mut()) {
it.active_appearance_item = None;
}
if let Some(held) = &mut s.held_interaction {
held.interaction.active_appearance_item = None;
}
}
}
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
let mut ids = row_targets(s, p, cmd)?;
+29
View File
@@ -39,6 +39,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_move
),
cmd!(
"document.setSaved",
"Set Saved State",
[],
None,
"{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is",
has_doc,
doc_set_saved
),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
@@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
}
fn doc_set_saved(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.setSaved";
let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
let saved = match p.get("saved") {
None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")),
Some(Value::Bool(b)) => *b,
Some(_) => return Err(bad(C, "`saved` must be true or false")),
};
let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?;
let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?;
if st.is_dirty() == saved {
if saved {
st.mark_saved();
} else {
st.mark_unsaved();
}
}
ok()
}
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
let n = s.documents().len();
let from = match p.get("from") {
+9
View File
@@ -125,6 +125,13 @@ pub use screens::{
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
preset_rows as screen_preset_rows,
};
pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing};
/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file,
/// which holds the artboards its own options pick? An unknown version counts as one.
pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool {
format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true))
}
pub use svg::options_map as svg_options;
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
/// file it replaces), for the apps' own writers too.
@@ -141,6 +148,8 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
+30 -1
View File
@@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)
}
/// The most a file read during a script command holds, the limit an importer reads.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`].
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
may_read(path)?;
// A device or pipe may never end: only a regular file is read to its end.
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
return Err(EngineError::Other(format!("{path}: not a file")));
}
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
if crate::file_access::in_script_command() {
let max = SCRIPT_OPEN_MAX_BYTES;
let read = || -> std::io::Result<Vec<u8>> {
let file = std::fs::File::open(path)?;
let meta = file.metadata()?;
if !meta.is_file() {
return Err(std::io::Error::other("not a file"));
}
if meta.len() > max as u64 {
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
}
let mut bytes = Vec::new();
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max {
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
}
Ok(bytes)
};
read().map_err(|e| EngineError::Other(format!("{path}: {e}")))
} else {
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
}
/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a
+16 -1
View File
@@ -818,7 +818,7 @@ pub fn read_for_open_asking(
(linked_pages(name, bytes, path.as_deref(), &opts)?, None)
} else {
match super::importer::pick(name, bytes, p)? {
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None),
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
// The color mode `p` asks for converts the colors after the policies did, through the
// profiles the document keeps.
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
@@ -1096,6 +1096,21 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
source(p, "document.open")?
}
};
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"]));
if crate::file_access::in_script_command() && (options || aliases) {
// An importer plug-in receives only the params, so it cannot apply the pages or the crop
// box; `linkPages` reads the file with the built-in reader before any importer.
let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true);
let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none();
let pdf = built_in
&& (!options
|| (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait"))
&& !vectorcraft_pdf::is_postscript(&src.bytes)));
if !pdf {
return Err(bad("document.open", "PDF open options require a PDF file"));
}
}
// A relative path is the file in the working directory: its folder is where relative links
// are found (a bare file name has no folder of its own).
let path = src.path.map(super::absolute_path);
+7 -3
View File
@@ -22,6 +22,8 @@ pub struct LoadOptions {
pub pages: Option<String>,
/// The box each page's artboard (or placed frame) gets.
pub crop: CropTo,
/// Whether the options explicitly request the crop box.
pub explicit_crop_box: bool,
/// The password of an encrypted PDF.
pub password: Option<String>,
/// The colour mode the document opens in, its colours converted as Document Color Mode does
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
Self {
pages: None,
crop: CropTo::default(),
explicit_crop_box: false,
password: None,
color_mode: None,
grays: Grays::default(),
@@ -147,6 +150,7 @@ impl LoadOptions {
Ok(Self {
pages,
crop,
explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(),
password,
color_mode,
grays,
@@ -173,14 +177,14 @@ impl LoadOptions {
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
/// with the bleed around them. An explicit crop-box request uses its crop box.
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
let pages = match &self.pages {
None => None,
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
};
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data();
Ok(ImportOptions {
pages,
crop: if is_ai { CropTo::Trim } else { self.crop },
+27 -15
View File
@@ -602,6 +602,7 @@ pub struct SaveJob {
stamped: Option<i64>,
/// The artboards also saved to files of their own (`separateArtboards`).
boards: Vec<usize>,
redact_paths: bool,
}
/// Writes the file at a path with what the filler it is given writes into it
@@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
}
impl SaveJob {
@@ -1071,21 +1072,31 @@ impl SaveJob {
return Ok(stopped);
}
// Every path is checked against the file access in force before the first file is
// written. A refused file goes to `write` first, which refuses it with the error the
// caller gives (naming the path as the caller does), so none of the files is written.
// written. A refused file is not handed to `write`, so a writer that does not check the
// file access writes none of the files; the error is the file access's own refusal, as
// the writers that check it give.
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1
&& let Some(refused) = files
.iter()
.find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }))
{
return Err(refused);
}
// An existing destination that is a folder or a read-only file is refused before any file
// is written too.
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1 {
for (p, bytes) in &files {
if super::may_write(p).is_err() {
write(p, bytes)?;
} else if let Ok(meta) = std::fs::metadata(p) {
if meta.is_dir() {
return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file")));
}
if meta.is_file() && meta.permissions().readonly() {
return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)));
}
}
for (p, _) in &files {
let Ok(meta) = std::fs::metadata(p) else { continue };
let refused = if meta.is_dir() {
crate::EngineError::Other(format!("{p}: is a folder, not a file"))
} else if meta.is_file() && meta.permissions().readonly() {
super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))
} else {
continue;
};
return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused });
}
}
for (i, (p, bytes)) in files.iter().enumerate() {
@@ -1248,9 +1259,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
/// A save command: plan, then write with the file system (a native file as it is encoded).
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
let plan = save_plan(s, mode, p)?;
let job = save_job(s, plan)?;
let mut job = save_job(s, plan)?;
let uid = s.doc()?.uid;
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
job.redact_paths = !given;
// Without a path, the files written are the document's own file and those beside it.
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
+8 -3
View File
@@ -172,14 +172,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
/// Editing Capabilities).
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
let n = doc.artboards.len();
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
(n > 1 && !preserved).then(|| {
(n > 1 && !preserves_editing(doc, p)).then(|| {
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
})
}
/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native
/// document (Preserve Editing Capabilities), which keeps every artboard.
pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool {
plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing)
}
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
+6 -6
View File
@@ -43,7 +43,7 @@ use std::sync::OnceLock;
use serde_json::Value;
use vectorcraft_apischema::shown_key;
use super::{bad, command_specs, find_command};
use super::{bad, color_is_finite, command_specs, find_command};
use crate::Result;
/// What a params description says about the keys of the params object.
@@ -608,16 +608,16 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
/// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`,
/// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers
/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its
/// default color for any other value, except that an array of three or more entries draws an
/// entry that isn't a number as 0.
/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`), with no component too
/// large to store ([`color_is_finite`])? The effect draws its default color for any other value,
/// except that an array of three or more entries draws an entry that isn't a number as 0.
///
/// [`Color::from_hex`]: vectorcraft_color::Color::from_hex
fn is_effect_color(v: &Value) -> bool {
match v {
Value::String(s) => vectorcraft_color::Color::from_hex(s).is_some(),
Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number),
Value::Object(_) => serde_json::from_value::<vectorcraft_color::Color>(v.clone()).is_ok(),
Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|n| n.as_f64().is_some_and(|n| (n as f32).is_finite())),
Value::Object(_) => serde_json::from_value::<vectorcraft_color::Color>(v.clone()).is_ok_and(|c| color_is_finite(&c)),
_ => false,
}
}
@@ -83,6 +83,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.pen.segment",
"addon.pen.togglePoint",
"addon.select.byArtboards",
"addon.select.editPointsOnly",
"addon.shapes.box3d",
"addon.shapes.configure",
"addon.shapes.ellipse",
+2 -2
View File
@@ -122,8 +122,8 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[
/// Does command `id`, run on its own, first apply the edit the active tool is computing on
/// another thread and the input held for it ([`Session::finish_tool_edit`])? Every command that
/// can edit, select, save or give a document a new revision does; queries that only read do not
/// (`commands_that_do_not_wait_for_a_tool_edit_change_no_document` in the command sweep checks
/// them). A frontend that adds params from
/// (`every_command_with_junk_params` and `commands_that_do_not_wait_for_a_tool_edit_change_no_document`
/// in the command sweep check them). A frontend that adds params from
/// its own state (the active artboard) applies them first itself.
pub fn waits_for_tool_edit(id: &str) -> bool {
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
+5 -2
View File
@@ -1211,14 +1211,17 @@ mod tests {
};
let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg")));
let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok()));
// The open document's file is the only grant: no folder scope covers it.
let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() };
let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok());
assert_eq!(check(&kept), (true, true));
assert!(document_write(), "an open document's file is written");
let mut perms = std::fs::metadata(&out).unwrap().permissions();
perms.set_readonly(true);
std::fs::set_permissions(&out, perms.clone()).unwrap();
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
assert!(check(&fresh).0, "a new file next to it is written");
let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() };
assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file");
assert!(!document_write(), "also when it is an open document's file");
#[allow(clippy::permissions_set_readonly_false)]
perms.set_readonly(false);
std::fs::set_permissions(&out, perms).unwrap();
+7
View File
@@ -10,6 +10,7 @@ pub struct Interaction {
pub doc: Arc<Document>,
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
pub(crate) active_appearance_item: Option<PreviewAppearanceItem>,
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
/// revision, and this value stays the same until the interaction ends.
pub revision: u64,
@@ -62,6 +63,12 @@ impl Interaction {
}
}
#[derive(Clone, Debug)]
pub(crate) struct PreviewAppearanceItem {
pub(crate) before: Option<crate::cmd::appearance::ActiveItem>,
pub(crate) after: Option<crate::cmd::appearance::ActiveItem>,
}
/// An interaction that a command from outside the tool set aside while it runs
/// ([`crate::Session::outside_interaction`]).
#[derive(Debug)]
+2 -3
View File
@@ -3022,11 +3022,10 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document
.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "close"].into_iter().map(|m| later(l, "Document", m)));
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
document.extend(save_open::document_members(l));
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
document.extend(save_open::document_members(l));
document.extend(raster_capture::document_members(l));
classes.push(class("Document", None, document, None));
classes.push(class(
+421 -39
View File
@@ -1,5 +1,6 @@
//! Saving, exporting and opening documents in the script object model: `Document.saveAs`,
//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the
//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`,
//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/>,
@@ -28,10 +29,34 @@
//! and when one of those files may not be written, none of them is.
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
//! the default its help page gives and throws an error that says it is not available yet at any
//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a
//! `PDFSaveOptions` option still at a new object's default keeps the preset's value.
//! other value; a property the help pages do not list throws an error that names it, unless it is
//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
//! keeps the preset's value. A `pDFPreset` in square brackets names the built-in preset of the
//! name inside them; the default preset's name and `[PDF/X-4:2008]` name VectorCraft Default and
//! PDF/X-4:2010.
//! - `artboardRange` is a string, or a number read as `String(number)`. With
//! `saveMultipleArtboards` true, a `.ai` save also writes each artboard of the range (all when it
//! is empty) to a file of its own, `<name>-<artboard name>.ai`. An EPS save of a range of two or
//! more artboards writes the file at the path and `<name>_<artboard name>.eps` for each of them, and an EPS
//! save of one artboard writes only the file at the path, holding that artboard. Without
//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of
//! artboard numbers throws.
//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no
//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
//! `fullName` and `path` of a document whose file the automation read roots do not allow throw
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
//! Assigning its current value runs no command.
//! - `Document.close` with unsaved changes closes without them with
//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with
//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or
//! recovered one included). `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws, since a
//! script cannot show the prompt.
//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record:
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only.
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property
//! but `typename` and `parent` throws the same error, unless it is `undefined`.
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
//! commands a script runs never show a dialog, so the level does not change what they do, and it
//! never allows a file the script's grants do not.
@@ -43,8 +68,8 @@ use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
use super::{
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, given, method, named, num,
on_doc, property, returns, text, this_doc, typed, whole,
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
num, on_doc, property, returns, text, this_doc, typed, whole,
};
/// The most a scale factor of an export takes, in percent.
@@ -85,6 +110,77 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]),
("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]),
("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]),
("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]),
// The enumerations of the options that keep their defaults (`Default::Member`).
("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]),
(
"CompressionQuality",
&[
"AUTOMATICJPEG2000HIGH",
"AUTOMATICJPEG2000LOSSLESS",
"AUTOMATICJPEG2000LOW",
"AUTOMATICJPEG2000MAXIMUM",
"AUTOMATICJPEG2000MEDIUM",
"AUTOMATICJPEG2000MINIMUM",
"AUTOMATICJPEGHIGH",
"AUTOMATICJPEGLOW",
"AUTOMATICJPEGMAXIMUM",
"AUTOMATICJPEGMEDIUM",
"AUTOMATICJPEGMINIMUM",
"JPEG2000HIGH",
"JPEG2000LOSSLESS",
"JPEG2000LOW",
"JPEG2000MAXIMUM",
"JPEG2000MEDIUM",
"JPEG2000MINIMUM",
"JPEGHIGH",
"JPEGLOW",
"JPEGMAXIMUM",
"JPEGMEDIUM",
"JPEGMINIMUM",
"None",
"ZIP4BIT",
"ZIP8BIT",
],
),
("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]),
(
"ColorDestination",
&[
"COLORDESTINATIONDOCCMYK",
"COLORDESTINATIONDOCRGB",
"COLORDESTINATIONPROFILE",
"COLORDESTINATIONWORKINGCMYK",
"COLORDESTINATIONWORKINGRGB",
"None",
],
),
("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]),
("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]),
("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]),
("PageMarksTypes", &["Japanese", "Roman"]),
(
"PDFChangesAllowedEnum",
&[
"CHANGE128ANYCHANGES",
"CHANGE128COMMENTING",
"CHANGE128EDITPAGE",
"CHANGE128FILLFORM",
"CHANGE128NONE",
"CHANGE40ANYCHANGES",
"CHANGE40COMMENTING",
"CHANGE40NONE",
"CHANGE40PAGELAYOUT",
],
),
("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]),
("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]),
("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]),
("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]),
("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]),
("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]),
("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]),
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
];
const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS";
@@ -132,6 +228,11 @@ fn not_available(class: &str, name: &str) -> HostError {
HostError::Error(format!("{class}.{name} is not available yet"))
}
/// The error a property that the help page of `class` does not list throws.
fn not_an_option(class: &str, name: &str) -> HostError {
HostError::Error(format!("{class} has no option {name}"))
}
fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result<u64, HostError> {
match d {
Data::Number(n) => {
@@ -159,9 +260,17 @@ fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> {
}
}
/// An artboard range: a string, given to the command as `range` unless it is empty.
/// An artboard range: a string, or a whole number from 1 read as `String(number)` reads it, given to
/// the command as `range` unless it is empty. Any other number throws.
fn range(d: &Data, what: &str, p: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
let s = match d {
Data::String(s) => s.clone(),
Data::Number(n) => {
whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?;
vectorcraft_js::number_to_string(*n)
}
_ => return Err(HostError::Type(format!("{what} must be a string or a number"))),
};
if s.len() > MAX_TEXT_BYTES {
return Err(HostError::Range(format!("{what} is too long")));
}
@@ -183,26 +292,82 @@ fn ai_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Resu
compatibility("IllustratorSaveOptions", d)?;
None
}
"artboardRange" | "saveMultipleArtboards" => return artboards_map("IllustratorSaveOptions", name, d, p),
_ => return Ok(false),
};
Ok(true)
}
/// `artboardRange` and `saveMultipleArtboards` of a `.ai` or EPS save, as `range` and
/// [`MULTIPLE`] until [`artboard_files`] reads them together.
fn artboards_map(class: &str, name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
let what = format!("{class}.{name}");
if name == "artboardRange" {
range(d, &what, p)?;
} else {
p.insert(MULTIPLE.into(), json!(boolean(d, &what)?));
}
Ok(true)
}
/// The key [`artboards_map`] keeps `saveMultipleArtboards` under.
const MULTIPLE: &str = "_multiple";
/// The params of a `.ai` (`format` `ai`) or EPS save for `saveMultipleArtboards` and
/// `artboardRange`: with `saveMultipleArtboards` true, the range (all when it is empty) goes to
/// `separateArtboards` of a `.ai` save or `useArtboards` of an EPS save, which write the artboards'
/// files; otherwise the range is not used, as the help pages say, but one that is not written as a
/// range ([`written_as_range`]) still throws.
fn artboard_files(format: &str, q: &mut Map<String, Value>) -> std::result::Result<(), HostError> {
let multiple = q.remove(MULTIPLE).and_then(|v| v.as_bool()).unwrap_or(false);
if !multiple {
if let Some(Value::String(r)) = q.remove("range")
&& !r.trim().eq_ignore_ascii_case("all")
&& !written_as_range(&r)
{
return Err(HostError::Range(format!("artboardRange `{r}` is not a range of artboard numbers")));
}
} else if format == "ai" {
q.insert("separateArtboards".into(), json!(true));
} else {
q.insert("useArtboards".into(), json!(true));
}
Ok(())
}
/// Whether `r` is written as an artboard range, whatever artboards a document has: one or more
/// parts separated by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out
/// and the first no greater than the second.
fn written_as_range(r: &str) -> bool {
// A number of digits alone, from 1; past `u64` it counts as the largest.
let num = |t: &str| -> Option<Option<u64>> {
let t = t.trim();
if t.is_empty() {
return Some(None);
}
let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::<u64>().unwrap_or(u64::MAX))?;
(n >= 1).then_some(Some(n))
};
let mut parts = r.split(',').map(str::trim).filter(|p| !p.is_empty()).peekable();
parts.peek().is_some()
&& parts.all(|part| match part.replace('\u{2013}', "-").split_once('-') {
Some((a, b)) => match (num(a), num(b)) {
(Some(Some(a)), Some(Some(b))) => a <= b,
(Some(a), Some(b)) => a.is_some() || b.is_some(),
_ => false,
},
None => matches!(num(part), Some(Some(_))),
})
}
const AI_KEPT: &[(&str, Default)] = &[
("artboardRange", Default::Text("")),
("embedLinkedFiles", Default::Bool(false)),
("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")),
("fontSubsetThreshold", Default::Num(100.0)),
("saveMultipleArtboards", Default::Bool(false)),
];
fn ai_starts() -> Vec<(&'static str, Data)> {
vec![
("compatibility", text("Compatibility.ILLUSTRATOR19")),
("compressed", Data::Bool(true)),
("pdfCompatible", Data::Bool(true)),
("embedICCProfile", Data::Bool(false)),
]
vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))]
}
fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
@@ -235,18 +400,17 @@ fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" }));
}
"compatibility" => compatibility("EPSSaveOptions", d)?,
"artboardRange" | "saveMultipleArtboards" => return artboards_map("EPSSaveOptions", name, d, p),
_ => return Ok(false),
}
Ok(true)
}
const EPS_KEPT: &[(&str, Default)] = &[
("artboardRange", Default::Text("")),
("compatibleGradientPrinting", Default::Bool(false)),
("embedAllFonts", Default::Bool(false)),
("embedLinkedFiles", Default::Unset),
("flattenOuput", Default::Unset),
("saveMultipleArtboards", Default::Bool(false)),
];
fn eps_starts() -> Vec<(&'static str, Data)> {
@@ -528,7 +692,7 @@ fn options_params(class: &OptionClass, d: &Data) -> std::result::Result<Map<Stri
match class.kept.iter().find(|(n, _)| n == k) {
Some((_, default)) if default.matches(v) => {}
Some(_) => return Err(not_available(class.name, k)),
None => {}
None => return Err(not_an_option(class.name, k)),
}
}
Ok(p)
@@ -572,6 +736,7 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
r
}
/// Writes each warning in a command's answer `result` to the console after `method`'s name.
pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
if let Data::Object(items) = result {
for (key, value) in items {
@@ -589,9 +754,44 @@ pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
}
}
/// The path to give a command for the real path `real`.
fn plain(real: std::path::PathBuf) -> String {
crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()
/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s
/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or
/// a linked image an open could not read. → the command's answer.
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
let (answer, value) = super::super::command_value(h, id, p)?;
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
Ok(answer)
}
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
}
/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the
/// preset each one names here (`Default` is VectorCraft's default preset, as
/// [`vectorcraft_pdf::builtin_preset`] reads it).
const PRESET_ALIASES: &[(&str, &str)] = &[
("Illustrator Default", "Default"), // brand-ok: the preset name scripts use
("PDF/X-4:2008", "PDF/X-4:2010"),
];
/// A `pDFPreset` in square brackets (`[Smallest File Size]`) names the built-in preset of the name
/// inside the brackets, or the one [`PRESET_ALIASES`] gives for it. A preset the name already
/// names, a saved preset called `[Name]` included, is left as it is, and any other name is left for
/// the save to refuse.
fn builtin_preset_name(h: &Host, q: &mut Map<String, Value>) {
let Some(name) = q.get("preset").and_then(Value::as_str) else { return };
let s = h.session.borrow();
if crate::cmd::fileio::pdf::find_preset(name, &s.prefs.pdf_presets).is_some() {
return;
}
let Some(inside) = name.trim().strip_prefix('[').and_then(|n| n.strip_suffix(']')) else { return };
let inside = PRESET_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(inside.trim())).map_or(inside, |(_, to)| to);
let Some(builtin) = vectorcraft_pdf::builtin_preset(inside, vectorcraft_pdf::APP) else { return };
q.insert("preset".into(), json!(builtin.name));
}
/// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options'
@@ -600,7 +800,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = file_path(arg(a, 1), "saveAs")?;
let mut p = Map::new();
let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null));
let given_options = given(arg(a, 2));
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
// object of that format's class holds.
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
@@ -610,22 +810,25 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into()));
};
let q = options_params(class, o)?;
let mut q = options_params(class, o)?;
if *format == "pdf" {
builtin_preset_name(h, &mut q);
} else {
artboard_files(format, &mut q)?;
}
p.insert("format".into(), json!(format));
if *format == "ai" {
p.extend(q);
} else if !q.is_empty() {
p.insert("options".into(), Value::Object(q));
}
}
if !p.contains_key("format") {
} else {
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
p.insert("format".into(), json!(format));
}
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
p.insert("path".into(), json!(plain(real)));
let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
command_warnings(h, "saveAs", &r);
p.insert("path".into(), json!(plain(real)?));
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?;
Ok(Data::Undefined)
}
@@ -646,13 +849,14 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
let path = file_path(arg(a, 1), "exportFile")?;
let kind = export_kind(arg(a, 2))?;
// Without options, an export takes the defaults a new options object of its class holds.
let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
let mut p = match given(arg(a, 3)) {
None => match kind.options {
Some(class) => options_params(class, &fresh(class))?,
None => Map::new(),
},
Some(o) => match kind.options {
Some(class) => options_params(class, o)?,
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
},
};
@@ -678,9 +882,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
}
let named = with_extension(path, &kind, svgz);
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
p.insert("path".into(), json!(plain(real)));
let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
command_warnings(h, "exportFile", &r);
p.insert("path".into(), json!(plain(real)?));
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?;
Ok(Data::Undefined)
}
@@ -689,16 +892,19 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
fn app_open(h: &Host, a: &[Data]) -> Answer {
let path = file_path(arg(a, 1), "open")?;
let mut p = Map::new();
if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) {
if let Some(d) = given(arg(a, 2)) {
let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" };
p.insert("colorMode".into(), json!(mode));
}
if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
if let Some(o) = given(arg(a, 3)) {
let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) };
if typename(o).is_some_and(|t| t != "PDFFileOptions") {
return Err(HostError::Type("open's options must be a PDFFileOptions record".into()));
}
for (k, v) in items {
if matches!(v, Data::Undefined) {
continue;
}
match k.as_str() {
"pageToOpen" => {
p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?));
@@ -715,13 +921,20 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
};
p.insert("cropTo".into(), json!(crop));
}
_ => {}
// The read-only members the help page lists.
"typename" | "parent" => {}
_ => return Err(not_an_option("PDFFileOptions", k)),
}
}
}
if p.contains_key("cropTo") {
p.insert("editingData".into(), json!(false));
}
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
p.insert("path".into(), json!(plain(real)));
let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?;
plain(real)?;
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?;
let index = match &r {
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
@@ -729,12 +942,177 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
}),
_ => None,
};
command_warnings(h, "open", &r);
let s = h.session.borrow();
let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
Ok(doc_ref(h, st.uid))
}
/// The document's file, `None` for a document that has none, or `Script file access denied` with
/// the document's name when the automation read roots do not allow the file to be named
/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them.
fn shown_file(st: &crate::DocState) -> std::result::Result<Option<String>, HostError> {
let path = st.path.as_deref().map(absolute_file).transpose()?;
match path.as_deref() {
Some(p) if crate::file_access::check_read(p).is_err() => {
Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title())))
}
_ => Ok(path),
}
}
fn absolute_file(path: &str) -> std::result::Result<String, HostError> {
let path = std::path::Path::new(path);
if path.is_absolute() {
Ok(path.to_string_lossy().into_owned())
} else {
let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?;
Ok(cwd.join(path).to_string_lossy().into_owned())
}
}
/// `document.fullName`: a `File` for the document's file, or, for a document that has none, a
/// `File` for its name in `Folder.current`.
fn doc_full_name(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
super::with_doc(h, doc, |_, st| {
Ok(match shown_file(st)? {
Some(p) => vectorcraft_js::file_ref(&p),
None => vectorcraft_js::file_ref(&st.title()),
})
})
}
/// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a
/// document that has none.
fn doc_path(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let folder = super::with_doc(h, doc, |_, st| {
Ok(shown_file(st)?.and_then(|p| {
let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned();
(!parent.is_empty()).then_some(parent)
}))
})?;
Ok(folder.map_or_else(|| text(""), |f| vectorcraft_js::folder_ref(&f)))
}
/// `document.saved`: whether the document has no changes since it was opened or last saved.
fn doc_saved(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(Data::Bool(super::with_doc(h, doc, |_, st| !st.is_dirty())))
}
/// `document.saved = value`: `document.setSaved`, which records the document as saved or as having
/// unsaved changes without saving it.
fn doc_set_saved(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let saved = boolean(arg(a, 1), "Document.saved")?;
if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) {
return Ok(Data::Undefined);
}
command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?;
Ok(Data::Undefined)
}
/// The error `close` gives for a document with unsaved changes with
/// `SaveOptions.PROMPTTOSAVECHANGES`.
const UNSAVED_CHANGES: &str =
"the document has unsaved changes: save them first, or close with SaveOptions.SAVECHANGES or SaveOptions.DONOTSAVECHANGES";
/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes that has
/// no file to save to.
const NO_FILE_TO_SAVE: &str =
"the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose
/// save would keep only some of its artboards.
const SAVES_SOME_ARTBOARDS: &str =
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
/// Whether the file that saving `st` with its remembered options writes would omit artboards. A
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai`
/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its
/// `range` names only the separate files. An EPS file embeds the whole document in its main file,
/// so its `artboardRange` never omits an artboard from what reopens.
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
if st.format == "eps" {
return false;
}
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
let svg = matches!(st.format, "svg" | "svgz");
if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
return true;
}
if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) {
return true;
}
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
return false;
}
let count = st.doc.artboards.len();
// A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is
// left for the save to refuse).
let modern_ai = matches!(st.format, "ai" | "ait") && !legacy;
let mut effective = options.clone();
if let (true, Value::Object(o)) = (modern_ai, &mut effective)
&& o.get("range").is_none_or(|r| r.is_string() || r.is_null())
{
o.insert("range".into(), json!("all"));
}
let resolved = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count));
// Such a `.ai` file, and an SVG file that carries the native document, keep every artboard;
// a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick).
if modern_ai {
return resolved.is_err();
}
if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) {
return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err();
}
match resolved {
Ok(None) => false,
Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)),
Err(_) => true,
}
}
/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved
/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES`
/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with
/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of
/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`]
/// for a document that has no file, a converted or recovered one included, and
/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and
/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script
/// cannot show the prompt.
fn doc_close(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let how = match given(arg(a, 1)) {
Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?,
None => "PROMPTTOSAVECHANGES",
};
let (dirty, file, format, picked) =
super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st)));
if dirty {
match how {
"DONOTSAVECHANGES" => {}
"SAVECHANGES" => {
let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?;
if picked {
return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into()));
}
// A refusal names the document, as `fullName` does when the read roots hide its file.
let name = super::with_doc(h, doc, |_, st| st.title());
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
let p = json!({"path": plain(real)?, "format": format});
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?;
}
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
}
}
command(h, "file.close", &json!({"index": doc.index}))?;
Ok(Data::Undefined)
}
fn app_interaction(h: &Host, _: &[Data]) -> Answer {
Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY }))
}
@@ -758,6 +1136,10 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
named(vec![
("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])),
("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])),
("fullName", get(l, doc_full_name), typed("File")),
("path", get(l, doc_path), typed("Folder|string")),
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
])
}
+2 -3
View File
@@ -474,9 +474,8 @@ impl Disk {
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`, but not the files its `File` objects hold open for writing.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
// A save, export or open of a `File` the script names reads and writes as its `File` would;
// the linked files stay readable, so the art that shows them still draws.
let documents = if self.exact { Vec::new() } else { documents };
// A save, export or open of a `File` the script names reads and writes as its `File` would.
let (documents, linked) = if self.exact { (Vec::new(), Default::default()) } else { (documents, linked) };
let held = self.open.values().filter_map(|o| o.target.clone()).collect();
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None }
}
+16
View File
@@ -545,6 +545,7 @@ impl Session {
effect: None,
doc: st.doc.clone(),
selection: Arc::new(st.selection.clone()),
active_appearance_item: None,
revision: st.revision,
preview: None,
tool: false,
@@ -573,6 +574,8 @@ impl Session {
if self.script_running() {
return Err(EngineError::Busy);
}
self.restore_preview_appearance_item();
let before_item = self.active_appearance_item.clone();
// While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the
// Shape Builder), paint previews of that kind change only the colors it paints with, so each
// preview starts from the colors the interaction began with; so does a preview with
@@ -639,8 +642,11 @@ impl Session {
}
let params = self.noted(params);
let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone());
let after_item = self.active_appearance_item.clone();
let st = self.doc_mut()?;
if let Some(it) = &mut st.interaction {
it.active_appearance_item =
(before_item != after_item).then_some(crate::interaction::PreviewAppearanceItem { before: before_item, after: after_item });
it.used_defaults_only |= ran_defaults_only;
// A failed preview leaves the document at the snapshot, so nothing is left to commit
// (not even an earlier successful preview, which the reset above already undid).
@@ -758,8 +764,18 @@ impl Session {
}
}
fn restore_preview_appearance_item(&mut self) {
let changed = self.active_mut().and_then(|st| st.interaction.as_mut()).and_then(|it| it.active_appearance_item.take());
if let Some(changed) = changed
&& self.active_appearance_item == changed.after
{
self.active_appearance_item = changed.before;
}
}
pub fn cancel_interaction(&mut self) -> Result<()> {
self.put_back_interaction();
self.restore_preview_appearance_item();
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
self.pending_paint = None;
+46
View File
@@ -266,6 +266,52 @@ fn a_color_with_an_alpha_part_is_refused() {
s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap();
}
/// A color param with a component too large to store (past `f32::MAX`, which would be stored as an
/// infinity) is refused and changes nothing, in every form a color is given in: CMYK, `[r, g, b]`,
/// Gray, Lab and a color object. The ends of each range still set the color.
#[test]
fn a_color_with_a_component_too_large_to_store_is_refused() {
let mut s = session();
let id = rect(&mut s);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for bad in [
json!({"c": f64::MAX, "m": 0, "y": 0, "k": 0}),
json!({"c": 0, "m": 0, "y": 0, "k": 1e308}),
json!([1e300, 0, 0]),
json!([0, 0, -1e300]),
json!({"gray": 1e300}),
json!({"l": 1e300, "a": 0, "b": 0}),
json!({"l": 50, "a": 0, "b": -1e300}),
json!({"model": "rgb", "r": 1e300, "g": 0, "b": 0}),
json!({"model": "cmyk", "c": 0, "m": 1e300, "y": 0, "k": 0}),
] {
for (cmd, p) in [
("artboard.setProps", json!({"index": 0, "color": bad})),
("artboard.new", json!({"color": bad})),
("paint.setFill", json!({"ids": [id.0], "color": bad})),
("paint.setStroke", json!({"ids": [id.0], "color": bad})),
("swatch.new", json!({"name": "Far", "color": bad})),
("swatch.new", json!({"colors": ["#00ff00", bad]})),
("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})),
] {
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
}
}
assert_eq!(*s.doc().unwrap().doc, *before, "a color too large to store changes nothing");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step");
let fill = |s: &Session| node(s, id).appearance.fill_paint().color();
s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
assert_eq!(fill(&s), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
s.execute("paint.setFill", &json!({"ids": [id.0], "color": [1, 0, 0]})).unwrap();
assert_eq!(fill(&s).map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"gray": 100}})).unwrap();
assert_eq!(fill(&s), Some(Color::gray(1.0)));
s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"l": 100, "a": -128, "b": 127}})).unwrap();
assert_eq!(fill(&s), Some(Color::lab(100.0, -128.0, 127.0)));
}
/// The native format writes an artboard's background color and reads it back. An artboard without
/// one is written as before, with no `color` key.
#[test]
File diff suppressed because it is too large Load Diff
+44 -18
View File
@@ -30,17 +30,27 @@ fn no_panic(r: Result<Value, vectorcraft_engine::EngineError>) -> Result<Value,
/// Run one call; returns a failure description or None.
fn probe(fx: Fixture, id: &str, params: &Value) -> Option<String> {
probe_and_compare(fx, id, params, false).0
}
/// Run one call as [`probe`] does, returning its failure description, and with `compare`, also
/// `id params [fixture]` when the call changed the session's [`tool_edit_state`], panic or not.
fn probe_and_compare(fx: Fixture, id: &str, params: &Value, compare: bool) -> (Option<String>, Option<String>) {
let mut s = fx.session();
let before = compare.then(|| tool_edit_state(&s));
let r = catch_quiet(|| no_panic(s.execute(id, params)));
match r {
let changed = before.filter(|b| tool_edit_state(&s) != *b).map(|_| format!("{id} {params} [{fx:?}]"));
let failure = match r {
Err(msg) => Some(format!("PANIC {id} {params} [{fx:?}]: {msg}")),
Ok(_) => {
if s.in_interaction() {
return Some(format!("{id} {params} [{fx:?}]: left an interaction open"));
Some(format!("{id} {params} [{fx:?}]: left an interaction open"))
} else {
check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}"))
}
check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}"))
}
}
};
(failure, changed)
}
#[test]
@@ -223,31 +233,43 @@ fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
cases
}
/// Every command with every junk case in every fixture: no panic, no interaction left open and no
/// broken invariant ([`probe`]). In `Single` and `Multi`, every command that runs at once while the
/// active tool computes an edit on another thread (it does not `waits_for_tool_edit`) also leaves
/// the documents' revisions and selections, the active document and the current paint as they were
/// ([`tool_edit_state`]), as `commands_that_do_not_wait_for_a_tool_edit_change_no_document` checks
/// for the cases that turn each option on and off.
#[test]
fn every_command_with_junk_params() {
let dir = vectorcraft_testkit::TempDir::new("sweep");
let path = safe_path(&dir);
let mut failures = vec![];
let mut changed = vec![];
let mut calls = 0usize;
for fx in Fixture::ALL {
for c in command_specs() {
let compare = matches!(fx, Fixture::Single | Fixture::Multi) && !vectorcraft_engine::waits_for_tool_edit(c.id);
let cases = junk_cases(c, &path);
for p in &cases {
calls += 1;
if let Some(f) = probe(fx, c.id, p) {
failures.push(f);
}
let (failure, change) = probe_and_compare(fx, c.id, p, compare);
failures.extend(failure);
changed.extend(change);
}
}
}
assert!(calls > 5_000, "only {calls} calls");
failures.sort();
failures.dedup();
changed.sort();
changed.dedup_by(|a, b| a.split(' ').next() == b.split(' ').next());
assert!(
failures.is_empty(),
"{} failures (of {calls} calls):\n{}",
failures.is_empty() && changed.is_empty(),
"{} failures (of {calls} calls):\n{}\n{} commands change a document without waiting for a tool edit:\n{}",
failures.len(),
failures.iter().take(60).cloned().collect::<Vec<_>>().join("\n")
failures.iter().take(60).cloned().collect::<Vec<_>>().join("\n"),
changed.len(),
changed.join("\n")
);
}
@@ -262,10 +284,11 @@ fn tool_edit_state(s: &Session) -> ToolEditState {
(docs, s.active_index(), s.paint.clone())
}
/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and
/// off, with a string under a file or folder key replaced by a location inside `path`'s folder.
fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
let mut cases = junk_cases(c, path);
/// The params the tool-edit sweep sends `c` beyond its junk cases, which the junk sweep checks:
/// each documented key turned on and off, with a string under a file or folder key replaced by a
/// location inside `path`'s folder.
fn option_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value> {
let mut cases = vec![];
for k in command_param_keys(c) {
for v in [json!(true), json!(false), json!(1), json!("on")] {
cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) }));
@@ -333,7 +356,7 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() {
}
}
let mut cases = junk_params_for_command(c, &path);
cases.extend(tool_edit_cases(c, &path));
cases.extend(option_cases(c, &path));
cases.extend(serializable_cases(c, &path));
for p in &cases {
let Some(o) = p.as_object() else { continue };
@@ -485,8 +508,9 @@ fn sweep_cases_send_the_file_keys_of_the_command_catalog() {
/// Every command that runs at once while the active tool computes an edit on another thread (a
/// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the
/// documents' revisions and selections, the active document and the current paint as they were,
/// with `{}`, junk params and params that turn its options on and off: the edit, computed for the
/// document as it was, still applies after it.
/// with params that turn its options on and off ([`option_cases`]; `every_command_with_junk_params`
/// checks the same with the junk cases): the edit, computed for the document as it was, still
/// applies after it.
#[test]
fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() {
let dir = vectorcraft_testkit::TempDir::new("sweep");
@@ -494,7 +518,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() {
let mut failures = vec![];
for fx in [Fixture::Single, Fixture::Multi] {
for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) {
let cases = tool_edit_cases(c, &path);
let cases = option_cases(c, &path);
for p in &cases {
let mut s = fx.session();
let before = tool_edit_state(&s);
@@ -538,6 +562,8 @@ fn structured_junk() {
("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})),
("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})),
("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})),
("addon.select.editPointsOnly", json!({"segmentEnds": "yes"})),
("addon.select.editPointsOnly", json!({"segmentEnds": [true], "ids": [2, u64::MAX]})),
("links.relink", json!({"scope": "each", "paths": [{"ids": [2, u64::MAX, -1, "x"], "path": ""}, null, 7, {"path": [1]}]})),
("links.relink", json!({"scope": ["all"], "path": "/no/such/file.png", "ids": {"a": 1}})),
("links.relink", json!({"scope": "missingInFolder", "path": "", "folder": [], "paths": "x"})),
@@ -1,5 +1,4 @@
//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
@@ -1,5 +1,4 @@
//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId};
@@ -1,5 +1,4 @@
//! Ellipse arrow keys edit the anchor count of the shape actually being dragged.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeId};
@@ -1,6 +1,4 @@
//! Fill-only open-path Eraser regressions through the public engine and CPU renderer.
// Integration tests may unwrap and panic on failure (AGENTS.md).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
+9
View File
@@ -12,13 +12,18 @@ mod affinity_local;
mod align_automatic_reference;
mod artboard_click;
mod beyond_canvas;
mod blend_render_consistency;
mod clear_commands;
mod compound_attributes;
mod copy_direct_selection;
mod delete_path_pieces;
mod dimensions;
mod direct_handle_mirror;
mod ellipse_drag_anchors;
mod eraser_open_fill;
mod eyedropper_sources;
mod find_replace_paras;
mod group3_reference;
mod inline_text;
mod js_lexer_vs_scriptcheck;
mod known_bugs;
@@ -27,12 +32,16 @@ mod model_based;
mod param_keys;
mod paste_many;
mod pasted_clipping_path;
mod path_fill_hits;
mod pen_click_after_smooth;
mod pen_endpoint_picking;
mod pen_rubber_band;
mod pen_space_handle;
mod preflight;
mod ruler_guide_nodes;
mod ruler_guide_perf;
mod ruler_origin;
mod scissors_snap;
mod script_host_vs_scriptcheck;
mod selection_commands;
mod several_handles;
+12 -2
View File
@@ -170,7 +170,8 @@ fn effect_params_no_longer_taken_still_replay_and_open() {
}
/// An effect's `color` that the effect can't read (a string `Color::from_hex` doesn't read, an
/// `[r, g, b]` without three numbers, an object that isn't a color, `null`) is refused by
/// `[r, g, b]` without three numbers, an object that isn't a color, `null`, a color with a component
/// too large to store) is refused by
/// `effect.apply`, `appearance.addEffect` and `effect.setParams` themselves, not only by the check,
/// and the document and its undo history stay as they were. The forms the effect reads pass. A
/// document saved with an unreadable color still opens with it.
@@ -186,7 +187,16 @@ fn an_effect_color_it_cannot_draw_is_refused() {
};
let before = state(&s);
let why = "`color` must be a #rrggbb color";
for bad in [json!("not-a-color"), json!("#ff00"), json!([1, 0]), json!(["#ff0000", 0, 0]), json!({"gray": 50}), json!(null)] {
for bad in [
json!("not-a-color"),
json!("#ff00"),
json!([1, 0]),
json!(["#ff0000", 0, 0]),
json!({"gray": 50}),
json!(null),
json!([1e300, 0, 0]),
json!({"model": "rgb", "r": 0, "g": 1e300, "b": 0}),
] {
for (cmd, params) in [
("effect.setParams", json!({"index": 0, "params": {"color": bad}})),
("effect.apply", json!({"effect": "stylize.outerGlow", "params": {"color": bad}})),
@@ -1,5 +1,4 @@
//! Path fill hit testing follows the visible paint stack while transparent paint remains selectable.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
@@ -1,6 +1,4 @@
//! Pen lends Direct Selection for one handle gesture; Space repositions that handle's owner.
// Integration tests may unwrap and panic (AGENTS.md, Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::json;
use vectorcraft_doc::NodeId;
@@ -1,5 +1,3 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
//! Production preflight must find actual delivery problems and clear them after repairs.
use serde_json::{Value, json};
@@ -1,5 +1,4 @@
//! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::json;
use vectorcraft_doc::NodeId;
@@ -37,18 +37,20 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"),
("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"),
("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
];
/// The names the host adds that stay inside the document and the run, by the object that has them.
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
/// the open documents; `Document.close` throws "not available yet". `app.open` reads the file it is
/// given.
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
/// `Document.path` only name its file and folder. `app.open` reads the file it is given.
const INSIDE: &[(&str, &str)] = &[
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
("Window.", "alert confirm length prompt prototype"),
@@ -111,14 +113,14 @@ const INSIDE: &[(&str, &str)] = &[
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
"activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
rulerOrigin= rulerUnits saveAs scaleFactor selection selection= stories swatches swatches= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
@@ -189,7 +191,44 @@ const INSIDE: &[(&str, &str)] = &[
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
// The enumerations of saving, exporting and opening.
("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"),
(
"",
"ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \
EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
),
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
(
"ColorDestination.",
"COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \
COLORDESTINATIONWORKINGRGB None",
),
("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"),
(
"CompressionQuality.",
"AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \
AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \
JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \
JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT",
),
("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"),
("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"),
("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"),
(
"PDFChangesAllowedEnum.",
"CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \
CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT",
),
("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"),
("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"),
("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"),
("PageMarksTypes.", "Japanese Roman"),
("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"),
("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"),
("SVGDocumentEncoding.", "ASCII UTF16 UTF8"),
("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"),
("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"),
(
"Compatibility.",
"ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \
@@ -201,6 +240,7 @@ const INSIDE: &[(&str, &str)] = &[
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
// The enumerations of rasterizing and the document's rasterize and window capture methods.
("", "AntiAliasingMethod RasterizationColorModel"),
+7 -28
View File
@@ -533,7 +533,8 @@ fn seams_against_supersampled(d: &Document, image: &vectorcraft_render::Rendered
/// opacity once over the surface. Inflate seen straight on, one layer of facets, has no alpha off, and
/// in opaque fills no RGB channel more than 3 levels off. Inflate turned so facets narrow to slivers
/// at the edges, and Revolve with a cap over its body, draw facets over other facets, and have no
/// alpha off.
/// alpha off. In the turned Inflate's opaque solid fill, each facet and its seam cover an edge pixel
/// once together, so at most one RGB channel is more than 3 levels off, by no more than 4.
#[test]
fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() {
let lights = json!([
@@ -556,20 +557,21 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() {
let (mut s, _) = setup("threeD.inflate");
let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":rotation.0,"rotationY":rotation.1}});
s.execute("effect.setParams", &change).unwrap();
cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0)));
cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0), rotation == (50, 35)));
}
let (mut s, _) = capped_profile();
s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap();
cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false));
cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false, false));
let mut failures = vec![];
for (name, mut s, fills, one_layer) in cases {
for (name, mut s, fills, one_layer, turned) in cases {
for fill in fills {
s.execute("paint.setFill", &fill).unwrap();
let image = render(doc(&s));
let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image);
assert!(measured > 2_000, "{name} {fill}: {measured} pixels inside");
let opaque = !fill.to_string().contains("opacity");
if holes > 0 || (one_layer && opaque && color > 0) {
let edges_once = turned && fill.get("color").is_some();
if holes > 0 || (one_layer && opaque && color > 0) || (edges_once && (color > 1 || max > 4)) {
failures.push(format!(
"{name} {fill}: of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}"
));
@@ -579,29 +581,6 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() {
assert!(failures.is_empty(), "{failures:#?}");
}
/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two
/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its
/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by
/// no more than 4, and no alpha is off.
#[test]
fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() {
let lights = json!([
{"color":"#ff0000","rotation":135,"height":35,"intensity":70},
{"color":"#0000ff","rotation":-35,"height":25,"intensity":65}
]);
let (mut s, _) = setup("threeD.inflate");
let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}});
s.execute("effect.setParams", &change).unwrap();
s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap();
let image = render(doc(&s));
let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image);
assert!(measured > 2_000, "{measured} pixels inside");
assert!(
holes == 0 && color <= 1 && max <= 4,
"of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}"
);
}
/// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at
/// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the
/// live art.
+60
View File
@@ -88,6 +88,66 @@ fn path_of(p: &std::path::Path) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn scripted_open_converts_importer_output_to_the_requested_color_space() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT));
let dir = tmp_dir("scriptcolorspace");
s.attach_script_data(dir.join("settings/Script Data"));
let file = dir.join("drawing.tscmyk");
std::fs::write(&file, b"importer input").unwrap();
let script = dir.join("main.jsx");
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
for (argument, mode) in [
("", vectorcraft_doc::ColorMode::Rgb),
(", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk),
(", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb),
] {
std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap();
let count = s.documents().len();
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap();
assert_eq!(s.documents().len(), count + 1);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.color_mode, mode, "{argument}: {out}");
let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap();
if mode == vectorcraft_doc::ColorMode::Cmyk {
assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}");
assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"]));
} else {
assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}");
assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"]));
}
}
let _ = std::fs::remove_dir_all(dir);
}
/// A script's PDF open options are refused for a file the named importer reads, which is given
/// only the params, even when the file's extension is a PDF one.
#[test]
fn scripted_pdf_open_options_are_refused_for_an_importer() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT));
let dir = tmp_dir("scriptpdfoptions");
s.attach_script_data(dir.join("settings/Script Data"));
let file = dir.join("x.ai");
std::fs::write(&file, b"importer input").unwrap();
let script = dir.join("main.jsx");
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] {
std::fs::write(
&script,
format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"),
)
.unwrap();
let count = s.documents().len();
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()}));
let text = format!("{out:?}");
assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}");
assert_eq!(s.documents().len(), count, "{option}");
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
let mut s = Session::new();
+36 -3
View File
@@ -49,6 +49,39 @@ impl Classes {
}
}
/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in
/// the host's platform form as its value. A plain object a script made that carries the key is
/// refused.
pub const FOLDER_REF_KEY: &str = "\u{0}folderRef";
/// What a host gives for a `File` at `path`, in the host's platform form ([`crate::FILE_REF_KEY`]):
/// the script receives a `File` object for it.
pub fn file_ref(path: &str) -> crate::Data {
crate::Data::Object(vec![(crate::FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
}
/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a
/// `Folder` object for it.
pub fn folder_ref(path: &str) -> crate::Data {
crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
}
impl Interp {
/// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form
/// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from
/// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there.
pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult<Value> {
let c = classes(self)?;
let proto = if folder { c.folder_proto } else { c.file_proto };
let text = Value::str(path);
let fs = self.rooted(std::slice::from_ref(&text), |i| {
let p = parse_text(i, text.clone(), true)?;
i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))
})?;
instance(self, proto, fs)
}
}
/// The path of `o` when the `File` or `Folder` class made it.
fn own_path(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
Ok(match &i.object(o)?.class {
@@ -113,9 +146,9 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
})
}
/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose
/// path is in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an object made with
/// `Object.create(File.prototype)` included.
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
/// object made with `Object.create(File.prototype)` included.
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
let Some(c) = &i.files else { return Ok(None) };
if i.object(id)?.proto != Some(c.file_proto) {
+10 -1
View File
@@ -275,6 +275,7 @@ impl Interp {
if r.ancestors.len() >= r.limits.depth {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
// A `File` reads as its path ([`crate::FILE_REF_KEY`]).
if r.hosted
&& let Some(path) = crate::file_classes::file_path(self, id)?
{
@@ -349,7 +350,7 @@ impl Interp {
self.use_fuel()?;
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
let name = String::from_utf16_lossy(&k);
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) {
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) {
return Err(self.data_error(r, ErrorType::Type, "is not plain data"));
}
r.path.push(Step::Name(k));
@@ -373,6 +374,14 @@ impl Interp {
if depth > self.data_limits.depth {
return Err(self.throw(ErrorType::Range, "a host value is nested too deep"));
}
// A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]).
if self.write_hosted
&& let Data::Object(items) = &d
&& let [(k, Data::String(path))] = items.as_slice()
&& (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY)
{
return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY);
}
Ok(match d {
Data::Undefined => Value::Undefined,
Data::Null => Value::Null,
+1
View File
@@ -168,6 +168,7 @@ pub use ast::{
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use file_classes::{FOLDER_REF_KEY, file_ref, folder_ref};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
+4
View File
@@ -33,3 +33,7 @@ craft-image-codecs = { workspace = true }
vectorcraft-testkit = { workspace = true }
proptest = { workspace = true }
socket2 = { workspace = true }
# The files of other crates that this crate's tests compile, for CI's test selection.
[package.metadata.craft]
reads = ["crates/apischema/src/conformance.rs"]
+9 -1
View File
@@ -246,8 +246,13 @@ impl<'a> Device<'a> for Builder<'_> {
// replaces DeviceCMYK, so it is cached apart from the same image drawn where one does.
let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false);
// Inside an alpha mask the same image is read again, white (its own cache key).
let key = craft::pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 };
let st = r.stream();
// An inline image (no object of its own) is keyed by its samples too: the
// interpreter keys an image by its dictionary, the same for inline images of one
// size and encoding (#9247).
let inline = if st.dict().obj_id().is_none() { crate::import_scan::hash128(&*st.raw_data()) } else { 0 };
let key =
craft::pdf::interpret::CacheKey::cache_key(&r) ^ inline ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 };
let (w, h) = (r.width(), r.height());
// CMYK images keep their samples (read once per image).
let known = !white && self.cmyk_keys.contains(&key);
@@ -370,6 +375,9 @@ impl<'a> Device<'a> for Builder<'_> {
None,
);
let Some((px, w, h, sf)) = decoded else { return };
// Keyed by its pixels too, as an inline raster image is by its samples: a stencil
// doesn't show its stream, and inline ones of one size share a dictionary (#9247).
let key = key ^ crate::import_scan::hash128(&px);
let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64);
match colorize {
// Its own key: its pixels are the gray ones, whatever color paints it.
+33
View File
@@ -507,6 +507,39 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() {
assert_eq!(walk.fonts.len(), 1);
}
/// Inline images with the same dictionary but other samples come in with their own pixels: the
/// stencil glyphs of a Type 3 font (#9247) and raster images on the page.
#[test]
fn inline_images_with_the_same_dictionary_keep_their_own_pixels() {
let n = first_extra(1);
let glyph = |hex: &str| {
stream("", &format!("1000 0 0 0 1000 1000 d1 q 1000 0 0 1000 0 0 cm BI /IM true /W 8 /H 8 /BPC 1 /D [1 0] /F /AHx ID\n{hex}>\nEI Q"))
};
let objects = [
format!(
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>",
n + 1,
n + 2
),
glyph("1818181818181818"),
glyph("000000FFFF000000"),
];
let raster = |hex: &str| format!("q 10 0 0 10 0 0 cm BI /W 2 /H 1 /CS /RGB /BPC 8 /F /AHx ID\n{hex}>\nEI Q ");
let content = format!("BT /T3 24 Tf 10 30 Td (ab) Tj ET {}{}", raster("FF000000FF00"), raster("0000FFFFFFFF"));
let extra: Vec<&str> = objects.iter().map(String::as_str).collect();
let d = open(&one_page(&content, &format!("/Font << /T3 {n} 0 R >>"), &extra));
let blobs: Vec<Arc<Vec<u8>>> = all(&d)
.iter()
.filter_map(|n| match &n.kind {
NodeKind::Image(im) => Some(d.images[&im.key].bytes.clone()),
_ => None,
})
.collect();
assert_eq!(blobs.len(), 4, "two glyphs and two raster images");
let distinct: std::collections::HashSet<&Arc<Vec<u8>>> = blobs.iter().collect();
assert_eq!(distinct.len(), blobs.len(), "each image has its own pixels");
}
/// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its
/// resources, has its glyph procedures read once for the document. Each page still maps the font's
/// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs
+4
View File
@@ -44,3 +44,7 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] }
[features]
# `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only).
test-steady = []
# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate.
[package.metadata.craft]
reads-every-member = true
+212 -1
View File
@@ -277,6 +277,65 @@ struct Assign {
after_new: bool,
}
/// `name = {`: an object literal assigned to a variable.
struct ObjectValue {
name: String,
/// The bracket depth inside its `{`.
depth: usize,
/// The document methods writing a file that it defines with a single function expression as the
/// key's whole value, a bit each ([`Analyzer::writers`]).
bits: u8,
/// It is the value of the first name a `var` statement declares, and the statement is directly
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or
/// a loop's parentheses: only then does the variable hold `bits` after it.
whole: bool,
/// The bit of the method whose value is being read, and how far that value has been read.
value: Option<(u8, Value)>,
}
/// How far the value of an object literal's key that names a document method writing a file has been
/// read, by the tokens directly inside the literal's braces.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Value {
/// `function`.
Function,
/// The function expression's name.
Name,
/// The `(` of its parameters.
Params,
/// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes
/// next.
Body,
/// Anything else, or anything after the body.
Other,
}
impl ObjectValue {
/// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value
/// being read, and gives the literal the method only when the value is a single function
/// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give
/// it nothing).
fn step(&mut self, t: &Sig) {
let Some((bit, value)) = self.value else { return };
if t.is(",") || t.is("}") {
if value == Value::Body {
self.bits |= bit;
} else {
self.bits &= !bit;
}
self.value = None;
return;
}
let next = match value {
Value::Function if t.kind == T::Ident => Value::Name,
Value::Function | Value::Name if t.is("(") => Value::Params,
Value::Params if t.is("{") => Value::Body,
_ => Value::Other,
};
self.value = Some((bit, next));
}
}
/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it
/// is a Folder object whatever the path names: [`Operand::file_step`]).
enum Held {
@@ -472,6 +531,8 @@ impl Chain {
/// member chain or a File object assigned in it to an outer name stays.
struct Scope {
depth: usize,
/// The offset of the body's `{` in the text, which [`Declared::looped`] names it by.
start: usize,
saved: HashMap<String, Saved>,
/// The bracket depth of the `var` statement the body is in, if any: it goes on when the body
/// closes.
@@ -507,6 +568,8 @@ struct Saved {
shadowed: Option<bool>,
/// It was a platform name the script had a meaning of its own for.
own: bool,
/// What it held in [`Analyzer::writers`], 0 for nothing.
writer: u8,
}
/// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are
@@ -556,6 +619,8 @@ struct Analyzer<'s, 'a, 'l> {
file: Option<&'a str>,
/// The four significant tokens before this one, the latest first.
h: [Option<Sig<'s>>; 4],
/// The significant token before the four of [`Self::h`].
h4: Option<Sig<'s>>,
brackets: Brackets,
/// Nesting too deep to follow was reported: it is reported once.
deep: bool,
@@ -578,6 +643,25 @@ struct Analyzer<'s, 'a, 'l> {
maybe_files: HashSet<String>,
/// `maybe_files` ran out of room: no variable counts as holding a Folder object.
maybe_files_full: bool,
/// The variables holding an object literal of the script's own that defines a method named as a
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
writers: HashMap<String, u8>,
/// The object literals being assigned to a variable, the innermost last, up to
/// [`crate::Limits::nesting`] of them.
objects: Vec<ObjectValue>,
/// An object literal whose `}` the last token was, with the methods it defines: the variable
/// holds them when the next token ends the `var` statement's value.
closed: Option<(String, u8)>,
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
/// that is not such a variable.
index_receiver: u8,
/// The variables that may get another value when code read elsewhere runs: assigned inside a
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
/// None of them joins [`Analyzer::writers`].
later: HashSet<String>,
/// `later` ran out of room: no variable joins [`Analyzer::writers`].
later_full: bool,
/// This file or what the scan started with gives names values the analysis doesn't read
/// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names.
unsure: bool,
@@ -641,6 +725,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
acc,
file,
h: [None; 4],
h4: None,
brackets: Brackets::default(),
deep: false,
active: None,
@@ -654,6 +739,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// property of the global object.
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
maybe_files_full: false,
writers: HashMap::new(),
objects: vec![],
closed: None,
index_receiver: 0,
later: HashSet::new(),
later_full: false,
unsure: known.unsure || declared.unsure,
own_names: HashSet::new(),
scopes: vec![],
@@ -738,6 +829,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
// closes a function body.
self.settle_groups(&t);
self.settle_literal(&t);
// A line break ends a `var` statement when it is outside the statement's brackets, and the
// tokens on either side of it don't go on with the expression.
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) {
@@ -760,9 +852,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.group_step(&t, started, before);
self.paren_step(&t, before);
self.assignment(&t, started);
self.object_key(&t, before);
self.features(&t);
self.newer(&t);
self.module_check(&t);
self.h4 = self.h[3];
self.h = [Some(t), self.h[0], self.h[1], self.h[2]];
}
@@ -859,6 +953,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn bind(&mut self, name: String, path: String) {
self.files.remove(&name);
self.folders.remove(&name);
self.writers.remove(&name);
if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) {
self.bound.insert(name, path);
}
@@ -868,6 +963,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
fn hold_file(&mut self, name: String, folder: bool) {
self.bound.remove(&name);
self.folders.remove(&name);
self.writers.remove(&name);
if !folder && !self.maybe_files.contains(&name) {
if self.acc.room(self.maybe_files.len()) {
self.maybe_files.insert(name.clone());
@@ -991,6 +1087,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
local: false,
shadowed,
own: self.own_names.contains(name),
writer: self.writers.get(name).copied().unwrap_or(0),
}
}
@@ -1025,6 +1122,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
} else {
self.own_names.remove(&name);
}
// An outer variable the body assigned keeps only the methods it still has: the body may have
// given it another value.
let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) };
if writer != 0 {
self.writers.insert(name.clone(), writer);
} else {
self.writers.remove(&name);
}
if let Some(hidden) = saved.shadowed
&& let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name)
&& let Some(s) = self.shadowed.get_mut(i)
@@ -1074,6 +1179,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.bound.remove(name);
self.files.remove(name);
self.folders.remove(name);
self.writers.remove(name);
self.hide_root(name);
}
@@ -1134,7 +1240,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if body {
let params = self.params.take().map(|(_, names)| names).unwrap_or_default();
if self.scopes.len() < self.acc.limits.nesting {
self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() });
self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() });
// The parameters are the body's own names, and so are the names it declares.
for name in params {
self.acc.steps = self.acc.steps.saturating_add(1);
@@ -1267,6 +1373,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
local: false,
shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true),
own: platform_name(name),
writer: 0,
};
let outside = std::mem::replace(&mut c.saved, empty);
if let Some(scope) = self.scopes.last_mut() {
@@ -1290,6 +1397,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.start_value(a.name, Operand::Done(Held::File { folder: false }));
} else if !a.after_new && t.is("(") {
self.start_group(a.name);
} else if !a.after_new && t.is("{") {
// An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]).
self.unbind(&a.name);
let [_, _, declaration, before] = self.h;
let depth = self.depth();
let body = self.scopes.last().map_or(0, |s| s.depth);
let starts = before.is_none()
|| [";", "{", "}"].iter().any(|p| is(before, p))
// A line break after a label's `:` does not end the statement the label may be
// the body of (`if (c) l:` before the line).
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do"));
let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body);
if self.objects.len() < self.acc.limits.nesting {
self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None });
}
} else {
self.unbind(&a.name);
}
@@ -1316,9 +1438,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other
// name before `=` is a variable, at the start of a statement or inside an expression.
if !member_mark(h1) && !is(h1, "@") {
if !self.scopes.is_empty() && !self.declared_in_body(name.text) {
self.reassigned_later(name.text);
}
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
}
}
if let Some((name, _)) = self.updated(t)
&& !self.scopes.is_empty()
&& !self.declared_in_body(name)
{
self.reassigned_later(name);
}
match self.updated(t) {
// The value on the right is read at this depth, and the name holds nothing the check
// follows once that value ends ([`Analyzer::settle_groups`]).
@@ -1328,6 +1459,85 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins
/// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t`
/// closes a function body, so a literal given to the body's own variable stays inside the body.
/// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods.
fn settle_literal(&mut self, t: &Sig<'s>) {
if let Some((name, bits)) = self.closed.take()
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
&& !self.later_full
&& !self.later.contains(&name)
&& !self.declared.looped_full
&& (self.writers.contains_key(&name) || self.acc.room(self.writers.len()))
{
self.writers.insert(name, bits);
}
}
/// `name` may get another value when code read elsewhere runs: a function body assigns it without
/// declaring it, and the function may be called before or after any line, or it is assigned as a
/// property of `this`. Its object literal's methods are no longer known, now or later.
fn reassigned_later(&mut self, name: &str) {
self.writers.remove(name);
if !self.later.contains(name) {
if self.acc.room(self.later.len()) {
self.later.insert(name.to_string());
} else {
self.later_full = true;
}
}
}
/// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`],
/// and when a function body's own variable hides it, the global's methods saved for the body's
/// end are no longer known either.
pub(super) fn reassigned_global(&mut self, name: &str) {
self.reassigned_later(name);
if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) {
saved.writer = 0;
}
}
/// Whether `name` is declared in the innermost function body (`var name`, `function
/// name`, a parameter).
fn declared_in_body(&self, name: &str) -> bool {
self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local))
}
/// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single
/// function expression directly inside its braces as the whole value of a key that names a
/// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`)
/// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`,
/// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing
/// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the
/// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on
/// (`{…} && d`), see the variable as it was.
fn object_key(&mut self, t: &Sig<'s>, before: usize) {
if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) {
o.step(t);
}
let depth = self.depth();
while let Some(o) = self.objects.pop_if(|o| o.depth > depth) {
if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) {
self.closed = Some((o.name, o.bits));
}
}
let [h0, h1, h2, _] = self.h;
if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) {
return;
}
let key = match h1 {
Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text),
Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)),
_ => return,
};
let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return };
// A value that starts with a bracket has opened it already: the key is at the depth before it.
let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return };
o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other }));
}
/// The variable that `t` changes to a number or a string, nothing the check follows, and whether
/// the change waits for the value on the right. `name += …` and the other compound assignments
/// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the
@@ -1542,6 +1752,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.var_depth = None;
self.conds.clear();
self.h = [None; 4];
self.h4 = None;
self.acc.steps = self.acc.steps.saturating_add(1);
let d = directives::parse(t.text);
let Some(name) = d.known else {
+319 -3
View File
@@ -1,6 +1,6 @@
//! The names declared, read before the analysis.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word};
@@ -14,10 +14,41 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E
/// The property a function reaches `Function` through.
const CONSTRUCTOR: &str = "constructor";
/// The statements whose parentheses the rest of the statement follows, so a line break after them
/// does not end a loop's body without braces.
const HEADS: &[&str] = &["if", "while", "for", "with", "switch"];
/// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in
/// brackets that spells a longer one sets [`Declared::unsure`].
const PROPERTY_CHARS: usize = 256;
#[cfg(not(test))]
type LoopSpans = Vec<(usize, usize)>;
#[cfg(test)]
#[derive(Default)]
pub(super) struct LoopSpans {
spans: Vec<(usize, usize)>,
reads: std::cell::Cell<usize>,
}
#[cfg(test)]
impl std::ops::Deref for LoopSpans {
type Target = Vec<(usize, usize)>;
fn deref(&self) -> &Self::Target {
self.reads.set(self.reads.get() + 1);
&self.spans
}
}
#[cfg(test)]
impl std::ops::DerefMut for LoopSpans {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.spans
}
}
/// The names a file's function bodies and its global code declare, read before the analysis. A
/// function's `var` statements and the function declarations directly in its body make the names
/// they declare the function's own before any statement in it runs, and the function declarations
@@ -36,6 +67,16 @@ pub(crate) struct Declared<'s> {
/// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be
/// the global object, so a variable of that name may get a value the analysis doesn't read.
pub(super) rebound: HashSet<String>,
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
/// offset of the `{` of the function body that declares it (`None`: the global code's), with the
/// outermost loops that assign it, entries of `loop_spans`.
pub(super) looped: HashMap<(Option<usize>, &'s str), Vec<usize>>,
/// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at
/// the end of the text).
pub(super) loop_spans: LoopSpans,
/// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any
/// variable may be assigned in a loop.
pub(super) looped_full: bool,
/// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or
/// a `constructor` property used, a property read, called or assigned whose name in brackets is
/// not one string or number literal, which may be a variable's name on the global object
@@ -46,14 +87,23 @@ pub(crate) struct Declared<'s> {
pub(super) unsure: bool,
}
#[cfg(test)]
impl Declared<'_> {
pub(crate) fn loop_span_reads(&self) -> usize {
self.loop_spans.reads.get()
}
}
/// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in
/// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement
/// the body is in, which goes on when the body closes.
/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it
/// so far, each with its loops ([`Declared::looped`]).
struct Body<'s> {
depth: usize,
index: usize,
names: HashSet<&'s str>,
var_depth: Option<usize>,
looped: HashMap<&'s str, Vec<usize>>,
}
/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in
@@ -87,9 +137,46 @@ struct Declarations<'s, 'a, 'l> {
untracked: Option<usize>,
/// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`].
keys: Vec<Key>,
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
loops: Vec<Loop>,
out: Declared<'s>,
}
/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read,
/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object
/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether
/// the last token was that `)`.
struct Loop {
depth: usize,
stage: Stage,
block: bool,
head: bool,
after_head: bool,
/// The loop starts with `do` and has a trailing condition.
do_loop: bool,
}
/// How far a [`Loop`] has been read.
#[derive(Clone, Copy, PartialEq)]
enum Stage {
/// The parentheses after `for` or `while`.
Head,
/// The parentheses after the `while` of a `do` loop.
DoHead,
/// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the
/// next token.
DoEnd,
/// The body's first token is next.
Start,
/// A body in braces.
Block,
/// A body that is one statement without braces.
Statement,
/// The statement of a body without braces has reached its end: the loop ends at the next token,
/// unless it is `else`, `catch` or `finally`, which go on with the statement.
Tail,
}
/// What `src` declares ([`Declared`]), read in one pass over its tokens.
pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
let mut lexer = Lexer::new(src, acc.limits.nesting);
@@ -103,6 +190,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
bodies: vec![],
untracked: None,
keys: vec![],
loops: vec![],
out: Declared::default(),
};
let mut breaks = LineBreaks::default();
@@ -113,7 +201,15 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
Read::Token(sig) => d.token(sig),
}
}
// A body the file does not close keeps its names assigned in a loop as well.
while let Some(body) = d.bodies.pop() {
d.settle_looped(body);
}
let mut out = d.out;
for ids in out.looped.values_mut() {
ids.sort_unstable();
ids.dedup();
}
out.unsure |= out.rebound.contains(catalog::FOLDER);
acc.steps = acc.steps.saturating_add(lexer.steps);
out
@@ -138,12 +234,22 @@ impl<'s> Declarations<'s, '_, '_> {
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) {
self.var_depth = None;
}
self.loop_start(&t);
if t.kind == T::Punct {
self.bracket(&t);
} else if t.kind == T::Ident {
self.declaration(&t);
}
let depth = self.depth();
self.loop_end(&t, depth);
if t.is("=")
&& !self.loops.is_empty()
&& !member_mark(h1)
&& !is(h1, "@")
&& let Some(name) = h0.filter(|s| s.kind == T::Ident)
{
self.looped(name.text);
}
if let Some(after_new) = self.assign.take() {
if t.word("new") && !after_new {
self.assign = Some(true);
@@ -167,6 +273,209 @@ impl<'s> Declarations<'s, '_, '_> {
self.h = [Some(t), h0, h1];
}
/// `t`, a token before the brackets are followed past it: the body of the innermost loop starts
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
/// variable may be assigned in one ([`Declared::looped_full`]).
fn loop_start(&mut self, t: &Sig<'s>) {
let [h0, h1, ..] = self.h;
let depth = self.depth();
while let Some(l) = self.loops.last_mut() {
let after_head = std::mem::take(&mut l.after_head);
match l.stage {
Stage::Start => {
l.stage = if t.is("{") { Stage::Block } else { Stage::Statement };
l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0);
break;
}
// A line break ends a body of one statement where the tokens on either side of it
// don't go on with it, as in [`Analyzer::token`], and it does not follow the
// parentheses of an `if` or another statement that the body goes on with.
Stage::Statement
if t.nl
&& depth == l.depth
&& !goes_on_after(h0)
&& !goes_on_with(t)
&& !after_head
&& !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) =>
{
l.stage = Stage::Tail;
}
Stage::Statement => {
if depth == l.depth {
if t.is("{") {
l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1));
} else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) {
l.head = true;
}
}
break;
}
Stage::Tail if l.do_loop && t.word("while") => {
l.stage = Stage::DoHead;
return;
}
Stage::Tail if t.word("else") => {
l.stage = Stage::Statement;
break;
}
// The `catch` and `finally` of a `try` statement that is the body go on with it.
Stage::Tail if t.word("catch") || t.word("finally") => {
l.stage = Stage::Statement;
l.head = t.word("catch");
break;
}
Stage::DoEnd if t.is(";") && depth == l.depth => break,
Stage::Tail | Stage::DoEnd => {
self.pop_loop(t.start);
// A body of one statement that is this loop ends with it.
if let Some(outer) = self.loops.last_mut()
&& outer.stage == Stage::Statement
&& outer.depth == depth
{
outer.stage = Stage::Tail;
}
}
_ => break,
}
}
let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) {
Stage::Head
} else if t.word("do") && !member_mark(h0) {
Stage::Start
} else {
return;
};
if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) {
self.out.looped_full = true;
} else {
if self.loops.is_empty() {
self.out.loop_spans.push((t.start, usize::MAX));
}
self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") });
}
}
/// Ends the innermost loop at offset `at`, which ends the outermost one in
/// [`Declared::loop_spans`].
fn pop_loop(&mut self, at: usize) {
self.loops.pop();
if self.loops.is_empty()
&& let Some((_, end)) = self.out.loop_spans.last_mut()
{
*end = at;
}
}
/// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the
/// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement
/// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a
/// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it.
fn loop_end(&mut self, t: &Sig<'s>, depth: usize) {
let mut inner = false;
while let Some(l) = self.loops.last_mut() {
let ended = depth < l.depth
|| match l.stage {
Stage::Head => {
if t.is(")") && depth == l.depth {
l.stage = Stage::Start;
}
false
}
Stage::DoHead => {
if t.is(")") && depth == l.depth {
l.stage = Stage::DoEnd;
}
false
}
Stage::DoEnd => t.is(";") && depth == l.depth,
Stage::Block => {
if t.is("}") && depth == l.depth && l.do_loop {
l.stage = Stage::Tail;
false
} else {
t.is("}") && depth == l.depth
}
}
Stage::Statement => {
if depth == l.depth {
if t.is(";") || (t.is("}") && l.block) || inner {
l.stage = Stage::Tail;
} else if t.is(")") && l.head {
l.head = false;
l.after_head = true;
}
}
false
}
Stage::Start | Stage::Tail => false,
};
if !ended {
break;
}
self.pop_loop(t.start);
inner = true;
}
}
/// `name` is assigned in the loops being read: kept with the outermost one for the innermost
/// function body that declares it when that body closes ([`Self::settle_looped`]), or for the
/// global code.
fn looped(&mut self, name: &'s str) {
let id = self.out.loop_spans.len().saturating_sub(1);
match self.bodies.last_mut() {
Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => {
let ids = body.looped.entry(name).or_default();
if !ids.contains(&id) {
ids.push(id);
}
}
Some(_) => self.out.looped_full = true,
None => self.keep_looped(None, name, vec![id]),
}
}
/// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it,
/// and the others go to the body around it, or to the global code.
fn settle_looped(&mut self, body: Body<'s>) {
let start = self.out.bodies.get(body.index).map(|(at, _)| *at);
for (name, ids) in body.looped {
if body.names.contains(name) {
self.keep_looped(start, name, ids);
} else if let Some(outer) = self.bodies.last_mut() {
if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) {
let kept = outer.looped.entry(name).or_default();
for id in ids {
if !kept.contains(&id) {
kept.push(id);
}
}
} else {
self.out.looped_full = true;
}
} else {
self.keep_looped(None, name, ids);
}
}
}
/// Keeps `name` of `body` as assigned in outermost loops `ids`.
fn keep_looped(&mut self, body: Option<usize>, name: &'s str, ids: Vec<usize>) {
let len = self.out.looped.len();
match self.out.looped.get_mut(&(body, name)) {
Some(kept) => {
for id in ids {
if !kept.contains(&id) {
kept.push(id);
}
}
}
None if self.acc.room(len) => {
self.out.looped.insert((body, name), ids);
}
None => self.out.looped_full = true,
}
}
/// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and
/// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read.
fn unread_binding(&mut self, t: &Sig<'s>) {
@@ -234,7 +543,13 @@ impl<'s> Declarations<'s, '_, '_> {
if self.bodies.len() < self.acc.limits.nesting {
let index = self.out.bodies.len();
self.out.bodies.push((t.start, vec![]));
self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() });
self.bodies.push(Body {
depth: self.depth(),
index,
names: HashSet::new(),
var_depth: self.var_depth.take(),
looped: HashMap::new(),
});
} else if self.untracked.is_none() {
self.untracked = Some(self.depth());
}
@@ -261,6 +576,7 @@ impl<'s> Declarations<'s, '_, '_> {
}
while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) {
self.var_depth = body.var_depth;
self.settle_looped(body);
}
if self.untracked.is_some_and(|d| depth < d) {
self.untracked = None;
+114 -5
View File
@@ -85,6 +85,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
}
self.writer_use(t);
match t.kind {
T::Ident => self.name(t, line),
T::Punct => self.punct(t, line),
@@ -130,6 +131,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to
/// its own file, and the value may reach `close` through a variable or an argument.
fn save_changes(&mut self, line: Option<usize>) {
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
}
/// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes.
fn file_setter(&mut self, line: Option<usize>) {
self.acc.feature(FeatureId::FileWrite, line);
@@ -200,6 +208,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
} else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) {
self.acc.feature(FeatureId::FilePlaces, line);
}
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
self.save_changes(line);
}
if n == catalog::ON_DRAW {
self.acc.feature(FeatureId::ScriptuiDrawing, line);
}
@@ -272,8 +283,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
"]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => {
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
self.setter(&name, h2, h3, line);
if name == catalog::SAVE_CHANGES
&& word(h2, catalog::SAVE_OPTIONS)
&& !member_mark(h3)
&& !self.own_names.contains(catalog::SAVE_OPTIONS)
{
self.save_changes(line);
}
}
"(" => self.call(line),
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
"(" => self.call(t, line),
// `Name.prototype["+"] = …` defines an operator.
"=" => {
let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str()));
@@ -288,13 +308,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
/// `(` after a name: a call.
fn call(&mut self, line: Option<usize>) {
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(name) = h1.filter(|s| s.kind == T::Str)
&& catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str())
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
&& !Self::defines(self.index_receiver, &method)
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
@@ -320,7 +341,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.acc.feature(FeatureId::FileDialog, line);
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
self.acc.feature(FeatureId::FileRead, line);
} else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) {
} else if (file && catalog::FILE_WRITES.contains(&n))
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
} else if n == catalog::EXECUTE {
@@ -343,6 +366,87 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
/// 0 for anything else. A receiver the check does not follow may be a document.
/// At call offset `at`, a variable assigned in a loop containing that offset may be a document.
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, at: Option<usize>) -> u8 {
match receiver {
Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => {
let Some(bits) = self.writers.get(r.text).copied() else { return 0 };
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
return 0;
}
let looped = at.is_some_and(|at| {
self.declared.looped_full
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
})
});
if looped { 0 } else { bits }
}
_ => 0,
}
}
/// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`,
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
/// `local[k] = w`, `delete local.saveAs`).
fn writer_use(&mut self, t: &Sig<'s>) {
let [h0, h1, h2, h3] = self.h;
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
// function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the
// global variable of that name may get another value.
if changes {
// `this`, not a property named `this` (`holder.this.d`).
let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) {
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) {
h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64))
} else {
None
};
if let Some(name) = global {
self.reassigned_global(&name);
}
}
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
let escaped = if word(h0, "delete") {
// `delete local…`
writer(Some(*t), h0)
} else if let Some(name) = writer(h0, h1) {
// `local` followed by anything but a member, its own assignment or an object key's `:`.
(!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name)
} else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) {
// `local.saveAs = …`
writer(h2, h3)
} else if is(h0, "[") {
// `local[k]` with a key that is not a string literal.
writer(h1, h2).filter(|_| t.kind != T::Str)
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
writer(h3, self.h4)
} else {
None
};
if let Some(name) = escaped {
self.writers.remove(name);
}
}
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
fn defines(bits: u8, method: &str) -> bool {
catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0)
}
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
/// (not a property of the same name), or a File or Folder object made in place or held in
/// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names
@@ -365,6 +469,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
if t.text.contains(catalog::ACTION_TEXT) {
self.acc.feature(FeatureId::Actions, line);
}
// The value written as the string `"SaveOptions.SAVECHANGES"`.
let value = unquote(t.text, 32);
if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) {
self.save_changes(line);
}
let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!=="));
if compares && word(h1, "typename") && is(h2, ".") {
let name = unquote(t.text, self.acc.limits.echo.saturating_add(1));
+6
View File
@@ -79,6 +79,12 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"];
// The save option of `Document.close` that saves the document to its own file:
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions).
pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES";
pub(crate) const SAVE_OPTIONS: &str = "SaveOptions";
// Application methods that page doesn't list, named in public forum posts:
// https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand,
// doScript, loadAction, unloadAction) and
+402 -15
View File
@@ -565,21 +565,6 @@ fn image_capture_writes_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[2, 3, 4][..])]);
}
/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file
/// too; reading the method without calling it does not.
#[test]
fn save_as_and_export_file_in_brackets_write_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"app.activeDocument['open'](f);\n",
"app.activeDocument[\"saveAs\"](f);\n",
"var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n",
"var n = d['saveAs'];\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one.
#[test]
fn export_variables_writes_a_file() {
@@ -603,6 +588,408 @@ fn export_variables_in_brackets_writes_a_file() {
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
#[test]
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
let r = report(&format!(
"var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\
eval('local = app.activeDocument');\n{call}\n"
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}");
let written = r.outside.iter().find(|o| o.id == "filesWritten");
assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}");
}
}
/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in
/// brackets, as a string or through a variable; closing without it, and the other save options,
/// write nothing.
#[test]
fn closing_with_save_changes_writes_a_file() {
let r = report(concat!(
"app.activeDocument.close();\n",
"app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n",
"app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n",
"app.activeDocument.close(SaveOptions.SAVECHANGES);\n",
"var how = SaveOptions['SAVECHANGES'];\n",
"documents[0].close(how);\n",
"documents[1].close('SaveOptions.SAVECHANGES');\n",
"var w = new Window('dialog'); w.close(1);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 7][..])]);
}
#[test]
fn unrelated_save_changes_properties_and_strings_do_not_report_writes() {
let r = report(concat!(
"var a = other.SAVECHANGES;\n",
"var b = other['SAVECHANGES'];\n",
"app.activeDocument.close('SAVECHANGES');\n",
"var c = holder.SaveOptions.SAVECHANGES;\n",
"var d = holder.SaveOptions['SAVECHANGES'];\n",
"var e = 'SAVECHANGES';\n",
"var key = SaveOptions['SAVECHANGES' + suffix];\n",
"var f = SaveOptions.SAVECHANGES;\n",
"var g = SaveOptions['SAVECHANGES'];\n",
"var h = 'SaveOptions.SAVECHANGES';\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[8, 9, 10][..])]);
}
/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file
/// too; reading the method without calling it does not.
#[test]
fn save_as_and_export_file_in_brackets_write_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"app.activeDocument['open'](f);\n",
"app.activeDocument[\"saveAs\"](f);\n",
"var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n",
"var n = d['saveAs'];\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
/// assigned something else since, and for a method the literal does not define, they write the file.
#[test]
fn the_scripts_own_save_as_writes_no_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var local = {saveAs: function () {}, 'n': 1};\n",
"local.saveAs(f);\n",
"local['saveAs'](f);\n",
"app.activeDocument.saveAs(f);\n",
"local.exportFile(f);\n",
"other.saveAs(f);\n",
"local = app.activeDocument;\n",
"local.saveAs(f);\n",
"var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n",
"t['exportFile'](f);\n",
"t.saveAs(f);\n",
"var activeDocument = {saveAs: function () {}};\n",
"app.activeDocument['saveAs'](f);\n",
"app.activeDocument.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]);
}
/// Once the script replaces or deletes such a method, indexes the object with a computed key, or
/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key
/// whose last value in the literal is not a function expression.
#[test]
fn a_changed_or_shared_own_save_as_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n",
"a.saveAs = app.activeDocument.saveAs;\n",
"b['saveAs'] = w;\n",
"delete d.saveAs;\n",
"var h = e;\n",
"use(g);\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"d.saveAs(f);\n",
"e.saveAs(f);\n",
"g['saveAs'](f);\n",
"var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n",
"m.saveAs(f);\n",
"n.saveAs(f);\n",
"var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n",
"q['saveAs'](f);\n",
"s.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..]));
// A computed key may name any variable, so every `saveAs` in the script may write, the ones
// before the computed key included.
let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n");
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
}
/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`,
/// before the assignment in the text: the call writes a file. One assigned only after a loop does
/// not.
#[test]
fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n",
"var d = {saveAs: function () {}};\n",
"for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n",
"while (n--) b.saveAs(f), b = app.activeDocument;\n",
"do { c.saveAs(f); } while ((c = next()));\n",
"for (;;) { d.saveAs(f); break; }\n",
"d = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 6][..])]);
// The `else` of a body without braces is in the loop; a statement after a line break that ends
// such a body is not, and neither is a variable of the same name that a function declares.
let r = report(concat!(
"var f = new File(p);\n",
"var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n",
"while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n",
"while (n--) g.saveAs(f), n\n",
"g = app.activeDocument\n",
"function k() { var h; for (;;) h = app.activeDocument; }\n",
"h.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
// An object literal's `}` does not end a body without braces, a call's `)` before a line break
// does, and a literal given after the last loop that assigns its variable is the script's own.
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n",
"b.saveAs(f);\n",
"while (n--) tick()\n",
"b = app.activeDocument\n",
"for (;;) { c = app.activeDocument; }\n",
"var c = {saveAs: function () {}};\n",
"c.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}};\n",
"while (n--) if (n)\n",
" a.saveAs(f), a = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
"a.saveAs(f); b['saveAs'](f);\n",
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
"while (n--) { b['saveAs'](f); b = app.activeDocument; }\n",
"var a = {saveAs: function () {}};\n",
"a.saveAs(f);\n",
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..]));
}
/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without
/// braces, are in the loop; a statement after the whole loop is not.
#[test]
fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"var h = {saveAs: function () {}};\n",
"while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n",
"while (i++ < 2)\n",
" if (i === 2) do e.saveAs(f); while (false);\n",
" else e = app.activeDocument;\n",
"while (n--) do g.saveAs(f); while (false);\n",
"g = app.activeDocument;\n",
"while (n--) h.saveAs(f), holder.finally\n",
"h = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..]));
}
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
/// variable hides the global one changes the global, and a property `d` of another object is not
/// the variable `d`.
#[test]
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = app.activeDocument;\n",
"if (no) l:\n",
"var a = {saveAs: function () {}};\n",
"a.saveAs(f);\n",
"var b = {saveAs: function () {}};\n",
"function change() { var b; this.b = app.activeDocument; }\n",
"change(); b.saveAs(f);\n",
"var c = {saveAs: function () {}};\n",
"function keep() { var c; c = 1; }\n",
"keep(); c.saveAs(f);\n",
"var d = {saveAs: function () {}};\n",
"holder.d['saveAs'] = 1;\n",
"d.saveAs(f);\n",
"var e = {saveAs: function () {}};\n",
"e['saveAs'] = app.activeDocument.saveAs;\n",
"e.saveAs(f);\n",
"var g = {saveAs: function () {}};\n",
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
"other(); g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..]));
}
/// Only a `var` statement directly in a function body or the global code that gives its first name
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
/// or to a later name of the statement, a call inside the literal, and a variable a function gave
/// another value keep reporting the write.
#[test]
fn only_a_whole_var_value_makes_save_as_the_scripts_own() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}};\n",
"function choose() { d = null; d = app.activeDocument; }\n",
"d.saveAs(f);\n",
"var e = app.activeDocument;\n",
"if (flag) var e = {saveAs: function () {}};\n",
"e.saveAs(f);\n",
"if (flag) { var e2 = {saveAs: function () {}}; }\n",
"e2.saveAs(f);\n",
"var g = {saveAs: function () {}} && app.activeDocument;\n",
"g.saveAs(f);\n",
"var h = app.activeDocument;\n",
"h = {saveAs: function () {}, value: h.saveAs(f)};\n",
"var k = {saveAs: function () {}, value: k.saveAs(f)};\n",
"k.saveAs(f);\n",
"var x = 1, y = {saveAs: function () {}};\n",
"y.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..]));
}
#[test]
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
for reinitialize in [false, true] {
let mut src = "var d = {saveAs: function () {}};\n".to_string();
for _ in 0..512 {
src.push_str("while (n--) { d = next(); }\n");
}
if reinitialize {
src.push_str("var d = {saveAs: function () {}};\n");
}
src.push_str("var local = {saveAs: function () {}};\n");
for _ in 0..2048 {
src.push_str("d.saveAs(f); local.saveAs(f);\n");
}
let limits = Limits::default();
let mut acc = report::Acc::new(&limits);
let declared = analyze::declarations(&src, &mut acc);
let before = declared.loop_span_reads();
analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
let reads = declared.loop_span_reads() - before;
if reinitialize {
assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d");
} else {
assert_eq!(reads, 0);
}
}
}
/// A function body read before the literal that assigns its variable without declaring it may run
/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the
/// name assigns its own variable.
#[test]
fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() {
let r = report(concat!(
"var f = new File(p);\n",
"function choose() { d = app.activeDocument; }\n",
"var d = {saveAs: function () {}};\n",
"choose(); d.saveAs(f);\n",
"function bump() { e++; }\n",
"var e = {saveAs: function () {}};\n",
"e.saveAs(f);\n",
"function own() { var g; g = app.activeDocument; }\n",
"var g = {saveAs: function () {}};\n",
"g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
}
#[test]
fn captured_writer_receivers_can_change_before_each_call() {
for method in ["saveAs", "exportFile"] {
for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] {
for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] {
let src = format!(
"{prefix}var d = {{{method}: function () {{}}}};\n\
function save(f) {{ {call}; }}\n\
d = app.activeDocument; save(f);\n{suffix}"
);
let r = report(&src);
let line = if prefix.is_empty() { 2 } else { 3 };
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}");
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[line][..])], "{src}");
}
}
}
}
#[test]
fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() {
let r = report(concat!(
"var f = new File(p);\n",
"function outer() {\n",
" function choose() { d = app.activeDocument; }\n",
" var d = {saveAs: function () {}};\n",
" choose(); d.saveAs(f);\n",
" function bump() { e++; }\n",
" var e = {saveAs: function () {}};\n",
" bump(); e.saveAs(f);\n",
" function own() { var g; g = app.activeDocument; }\n",
" var g = {saveAs: function () {}};\n",
" own(); g.saveAs(f);\n",
"}\n",
"outer();\n",
));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 8][..])]);
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
}
/// Assigning a property of `this`, the global object in the global code and in a function called
/// without a receiver, may give the global variable of that name another value, before or after
/// its literal.
#[test]
fn assigning_a_property_of_this_keeps_save_as_writing() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}};\n",
"this.d = app.activeDocument;\n",
"d.saveAs(f);\n",
"function swap() { this['e'] = app.activeDocument; }\n",
"var e = {saveAs: function () {}};\n",
"swap(); e.saveAs(f);\n",
"var g = {saveAs: function () {}};\n",
"this.other = 1;\n",
"g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
}
/// A `saveAs` key's value is a method of the script's own only when the whole value is one function
/// expression: a value that goes on after the function's body, and a literal inside another, leave
/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body
/// leaves the outer variable as it was.
#[test]
fn a_value_that_goes_on_after_the_function_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = {saveAs: function () {} && app.activeDocument.saveAs};\n",
"var b = {saveAs: function () {}(f), n: 1};\n",
"var c = {saveAs: function () {} ? x : y};\n",
"var e = {saveAs: function () {}.call};\n",
"var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n",
"var m = {o: {saveAs: function () {}}};\n",
"var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n",
"}\n",
"a.saveAs(f);\n",
"b.saveAs(f);\n",
"c.saveAs(f);\n",
"e.saveAs(f);\n",
"k.saveAs(f); k.exportFile(f);\n",
"m.saveAs(f);\n",
"q.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..]));
}
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
/// them and setting them on another object does not.
#[test]
+2
View File
@@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-text = { workspace = true }
vectorcraft-pathops = { workspace = true }
# Installed memory (cgroup limits included), which sizes the element limit.
vectorcraft-render = { workspace = true }
kurbo = { workspace = true }
# Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs).
usvg = { workspace = true }
+9 -4
View File
@@ -28,6 +28,11 @@ pub(crate) use fx::BLEND;
/// expansion bombs (#3564).
pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 };
/// Most elements an SVG may expand to on this machine, its memory considered (#10165).
pub fn max_elements() -> usize {
budget::max_elements() as usize
}
mod convert;
mod importer;
mod layers;
@@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool)
}
let xml = parse(svg)?;
// Before the style cascade of `depth::height`, as `import` measures it.
budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?;
budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?;
if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() {
return Err(too_deep());
}
@@ -142,7 +147,7 @@ pub(crate) fn import_finding(
let xml = parse(svg)?;
// Before the style cascade of `depth::height` and the prepass, which keeps the declarations of
// each element it reads; measured again below on the text usvg reads when that differs.
let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?;
let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?;
let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else {
return Err(too_deep());
};
@@ -165,8 +170,8 @@ pub(crate) fn import_finding(
// Before usvg copies what `<use>`s show and the style values of each copy: the text usvg reads.
let spent = match &src {
Cow::Borrowed(_) if !rewritten => spent,
Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?,
Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?,
Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?,
Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?,
};
let files = found.files;
files.spent_by_svg(spent);
+48 -6
View File
@@ -6,8 +6,9 @@
//! sheets and the `style` attribute give the element, so a long style on an element that `<use>`s
//! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more
//! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after
//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or
//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead.
//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than
//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`]
//! bytes of copied styles is refused here instead.
//!
//! The copies are counted, never made: each element's count is worked out once and added up, so a
//! `<use>` of an element costs one addition, however many elements its copy holds. References
@@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError};
/// which usvg stops (its count includes a root of its own).
pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 };
/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a
/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare.
const ELEMENT_BYTES: u64 = 8 << 10;
/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the
/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused
/// with an error instead of running out of memory.
pub(crate) fn max_elements() -> u64 {
static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory()))
}
/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known).
fn elements_for(memory: Option<u64>) -> u64 {
memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64))
}
/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it.
fn too_many_elements() -> SvgError {
let most = max_elements();
match vectorcraft_render::installed_memory() {
Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20),
_ => SvgError::TooLarge(MAX_SVG_ELEMENTS),
}
}
/// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it
/// shows, all together: VectorCraft's own limit.
pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20;
@@ -209,7 +236,9 @@ pub(crate) struct Cost {
impl Cost {
/// The most an SVG and the SVG images it shows may cost together.
pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS };
pub(crate) fn limits() -> Cost {
Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }
}
pub(crate) fn add(self, other: Cost) -> Cost {
Cost {
@@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu
pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result<Cost, SvgError>, u64) {
let (result, tests) = measure_spending(xml, left, depth);
let result = result.map_err(|past| match past {
Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS),
Past::Elements => too_many_elements(),
Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize),
Past::Tests => SvgError::StylesTooComplex,
Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH),
@@ -562,6 +591,19 @@ mod tests {
assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 });
}
#[test]
fn less_memory_reads_fewer_elements_up_to_the_element_limit() {
let most = MAX_SVG_ELEMENTS as u64;
assert_eq!(elements_for(None), most, "unknown memory");
assert_eq!(elements_for(Some(0)), most, "unknown memory");
assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory");
// A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165).
let small = elements_for(Some(1 << 30));
assert!(small < 400_000, "{small}");
assert!(elements_for(Some(512 << 20)) < small);
assert!(max_elements() <= most);
}
#[test]
fn style_sheet_rules_count_where_they_match() {
let groups = "<g class='a'/>".repeat(4);
@@ -614,7 +656,7 @@ mod tests {
let xml = roxmltree::Document::parse(&deep).unwrap();
assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth));
assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none());
assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_))));
assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_))));
for text in [chain(5, ""), svg("<g><g><use href='#r'/></g></g><rect id='r'/>")] {
let xml = roxmltree::Document::parse(&text).unwrap();
let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0);
@@ -674,7 +716,7 @@ mod tests {
fn a_selector_that_never_matches_stops_at_the_test_limit() {
let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20)));
let xml = roxmltree::Document::parse(&never).unwrap();
assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests));
assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests));
let before = super::super::css::selector_tests();
let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err();
assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}");
+4 -4
View File
@@ -478,7 +478,7 @@ impl Files {
// reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the
// linked SVG files measured before it left: past it, its links aren't read, and the
// selector tests it made still count.
let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left);
let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left);
match result {
Ok(cost) => reading.measured = reading.measured.add(cost),
Err(e) => {
@@ -593,13 +593,13 @@ impl Files {
}
/// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most
/// what is left of [`budget::Cost::LIMITS`].
/// what is left of [`budget::Cost::limits()`].
pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) {
self.set_spent(spent);
}
fn spent(&self) -> budget::Cost {
self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS)
self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits())
}
fn set_spent(&self, spent: budget::Cost) {
@@ -807,7 +807,7 @@ impl Files {
// with theirs while usvg reads it, and only when it decodes. Too deep, it is left out;
// past the other limits, the whole SVG is refused.
let spent = self.spent();
let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) {
let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) {
Ok(cost) => cost,
Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true),
Err(e) => {
+5 -1
View File
@@ -363,6 +363,10 @@ pub enum SvgError {
/// nested-image expansion bombs, #3564).
#[error("the SVG expands to more than {0} objects")]
TooLarge(usize),
/// The SVG expands to more objects (the first number) than this machine's memory, or the
/// process's memory limit (the second number, in MB), has room to read (#10165).
#[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")]
TooLargeForMemory(usize, u64),
/// The SVG expands to more nested SVG images than the reader takes (a guard against
/// nested-image expansion bombs, #3564).
#[error("the SVG expands to more than {0} nested SVG images")]
@@ -536,7 +540,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu
pub use glyph::glyph_art;
pub use import::{
MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT,
MAX_NODES,
MAX_NODES, max_elements,
};
/// Import an SVG document reading the files it links to as `opts` says, also returning warnings.
+18 -3
View File
@@ -892,11 +892,22 @@ fn styles_that_expand_past_the_limit_are_refused() {
assert_eq!(art(&d).len(), 5000);
}
/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose
/// memory has room for fewer (#10165).
fn past_the_element_limit(err: &SvgError) -> bool {
let most = vectorcraft_svg::MAX_NODES.min(999_999);
match *err {
SvgError::TooLarge(n) => n == most,
SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(),
_ => false,
}
}
/// A chain of `<use>`s that makes more elements than usvg reads is refused before usvg makes them.
#[test]
fn a_use_chain_past_the_elements_usvg_reads_is_refused() {
let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}");
assert!(past_the_element_limit(&err), "{err:?}");
}
/// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images
@@ -927,9 +938,13 @@ fn svg_images_share_the_element_limit() {
assert_ne!(chain, unshown);
let image = image_of("image/svg+xml", &unshown);
let rect = r#"<rect width="1" height="1"/>"#;
assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok());
// One image fits, unless this machine's memory has room for fewer elements than it makes.
match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) {
Ok(_) => {}
Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"),
}
let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}");
assert!(past_the_element_limit(&err), "{err:?}");
}
/// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit
+43 -42
View File
@@ -42,35 +42,37 @@ impl Kind {
}
/// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height,
/// with `preview` (Use Preview Bounds on) to the outside of its strokes.
/// to the outside of its strokes.
#[derive(Clone, Debug, PartialEq)]
enum Target {
Segment(SegmentRef),
Corner { first: SegmentRef, second: SegmentRef, at: Point },
Radial { source: DimensionSource, center: Point, radius: f64 },
Extent { node: NodeId, preview: bool },
Extent { node: NodeId },
}
/// A path, whether its points are moved out to its strokes, and the document its outermost points
/// ([`whole_ends`]) were read from ([`whole_box_source`]).
type WholeBoxKey = (NodeId, bool, (u64, u64, usize));
/// A path and the document its outermost points ([`whole_ends`]) were read from
/// ([`whole_box_source`]).
type WholeBoxKey = (NodeId, (u64, u64, usize));
/// The key of a path's outermost points ([`WholeBoxKey`]), with the points.
type WholeBox = (WholeBoxKey, Option<[(Point, Point); 2]>);
/// The document a path's box is read from, with what identifies it: while an interaction is in
/// progress, the document as it began; otherwise the document `cx` shows, at its revision.
fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId, preview: bool) -> (&'a vectorcraft_doc::Document, WholeBoxKey) {
fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, WholeBoxKey) {
match cx.interaction_doc {
Some(began) => (began, (node, preview, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))),
None => (cx.doc, (node, preview, (cx.revision.0, cx.revision.1, 0))),
Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))),
None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))),
}
}
/// The outermost points a dimension of the whole path `node` measures: [`dimension::extents`], or
/// with `preview` [`dimension::preview_extents`], moved out to the outside of the path's strokes.
fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> {
if preview { dimension::preview_extents(doc, node) } else { dimension::extents(doc, node) }
/// The outermost points a dimension the tool places on the whole path `node` measures
/// ([`dimension::preview_extents`]): moved out to the outside of the path's strokes, whether Use
/// Preview Bounds is on or off. The dimension records `"preview": true`, so it measures to there
/// after later edits too.
fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId) -> Option<[(Point, Point); 2]> {
dimension::preview_extents(doc, node)
}
#[derive(Default)]
@@ -175,7 +177,8 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation {
.map_or(Orientation::Aligned, |(_, orientation)| orientation)
}
/// The box through a path's outermost points ([`whole_ends`]): left, top, right and bottom.
/// The box through a path's outermost points moved out to its strokes ([`whole_ends`]): left, top,
/// right and bottom.
fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect {
Rect::new(left.x, top.y, right.x, bottom.y)
}
@@ -1045,23 +1048,23 @@ impl DimensionTool {
/// document changes. While an interaction is in progress they are read from the document as
/// the interaction began, which each preview starts again from (as the levels in
/// [`Self::preview`] are), so the previews themselves do not make the tool read the path again.
fn whole_box(&mut self, cx: &ToolContext, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> {
let (from, key) = whole_box_source(cx, node, preview);
fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> {
let (from, key) = whole_box_source(cx, node);
if let Some((kept, ends)) = self.whole_box
&& kept == key
{
return ends;
}
let ends = whole_ends(from, node, preview);
let ends = whole_ends(from, node);
self.whole_box = Some((key, ends));
ends
}
/// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point
/// is picked, is the whole path: with Use Preview Bounds on, to the outside of its strokes.
/// is picked, is the whole path, to the outside of its strokes.
fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option<Target> {
let edge = pick(cx, p)?;
match self.kind {
Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node, preview: cx.preview_bounds }),
Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }),
Kind::Linear => Some(Target::Segment(edge)),
Kind::Angular => {
let (anchor, at) = anchor_near(cx, &edge, p)?;
@@ -1113,8 +1116,8 @@ impl DimensionTool {
let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter };
self.recipe(mode, *center, p, Point::ZERO, Some(source.clone()))
}
Target::Extent { node, preview } => {
let source = DimensionSource::Extent { node: *node, preview: *preview };
Target::Extent { node } => {
let source = DimensionSource::Extent { node: *node, preview: true };
let mut d = self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(source));
d.orientation = Orientation::Horizontal;
d
@@ -1139,7 +1142,7 @@ impl DimensionTool {
}
self.level_guide = None;
let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) {
Some(DimensionSource::Extent { node, preview }) => Some(self.whole_box(cx, *node, *preview)),
Some(DimensionSource::Extent { node, .. }) => Some(self.whole_box(cx, *node)),
_ => None,
};
let Some(d) = &mut self.pending else { return vec![] };
@@ -1408,8 +1411,8 @@ impl Tool for DimensionTool {
}
self.hover = self.target(cx, ev.pos, ev.mods.alt);
let whole = match self.hover {
Some(Target::Extent { node, preview }) => {
self.whole_box(cx, node, preview);
Some(Target::Extent { node }) => {
self.whole_box(cx, node);
true
}
_ => false,
@@ -1562,15 +1565,14 @@ impl Tool for DimensionTool {
out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true });
}
}
Some(Target::Extent { node, preview }) => {
// The box through the path's outermost points (with Use Preview Bounds on, out
// to its strokes): a Smart Guide, or with Smart Guides off a line in the
// tool's own color. Read again when the path changed since the pointer last
// moved.
let (from, at) = whole_box_source(cx, *node, *preview);
Some(Target::Extent { node }) => {
// The box through the path's outermost points, out to its strokes: a Smart
// Guide, or with Smart Guides off a line in the tool's own color. Read again
// when the path changed since the pointer last moved.
let (from, at) = whole_box_source(cx, *node);
let b = match self.whole_box {
Some((key, ends)) if key == at => ends,
_ => whole_ends(from, *node, *preview),
_ => whole_ends(from, *node),
}
.map(extent_box);
if let Some(b) = b {
@@ -2874,7 +2876,7 @@ mod tests {
}
}
/// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide,
/// With Alt held, hovering a path shows the box its strokes paint as a Smart Guide,
/// and a click starts placing a dimension of the whole path: above or below it, its width;
/// beside it, its height. A drag places it on release. Without Alt the same click picks a point.
#[test]
@@ -2890,7 +2892,7 @@ mod tests {
};
let mut t = DimensionTool::default();
t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0));
assert_eq!(t.hover, Some(Target::Extent { node: id, preview: false }));
assert_eq!(t.hover, Some(Target::Extent { node: id }));
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color)));
// With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by
// the pointer.
@@ -2907,7 +2909,7 @@ mod tests {
t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0));
assert!(t.pending.is_some() && t.points.is_empty());
let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0)));
assert_eq!(above["source"], json!({"kind":"extent","node":id}));
assert_eq!(above["source"], json!({"kind":"extent","node":id,"preview":true}));
assert_eq!(above["orientation"], json!("horizontal"));
// Past a corner, the side the pointer is farther out on decides.
let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0)));
@@ -2954,29 +2956,28 @@ mod tests {
assert!(o.iter().any(near), "{o:?}");
}
/// With Use Preview Bounds on, the box Alt shows over a stroked path reaches the outside of its
/// stroke, and the dimension of the whole path it places measures to there, as W and H do; it
/// keeps doing so after the art changes (`"preview": true`). With the preference off, the box
/// and the dimension go through the outermost points.
/// With Use Preview Bounds on or off, the box Alt shows over a stroked path reaches the outside
/// of its stroke, and the dimension of the whole path it places measures to there; it keeps
/// doing so after the art changes (`"preview": true`).
#[test]
fn with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke() {
fn an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(Mods { alt: true, ..Mods::default() });
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
for (preview, (left, right)) in [(true, (99.5, 200.5)), (false, (100.0, 200.0))] {
let (left, right) = (99.5, 200.5);
for preview in [true, false] {
let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) };
let mut t = DimensionTool::default();
t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0));
assert_eq!(t.hover, Some(Target::Extent { node: id, preview }));
assert_eq!(t.hover, Some(Target::Extent { node: id }));
let xs: Vec<f64> = t.overlays(&c).iter().filter_map(|o| if let Overlay::Line { a, .. } = o { Some(a.x) } else { None }).collect();
assert!(xs.iter().any(|x| near(*x, left)) && xs.iter().any(|x| near(*x, right)), "preview {preview}: {xs:?}");
t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0));
t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0));
let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0));
let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") };
let source = if preview { json!({"kind":"extent","node":id,"preview":true}) } else { json!({"kind":"extent","node":id}) };
assert_eq!(params["source"], source);
assert_eq!(params["source"], json!({"kind":"extent","node":id,"preview":true}), "preview {preview}");
let (a, b) = (params["a"][0].as_f64().unwrap_or(f64::NAN), params["b"][0].as_f64().unwrap_or(f64::NAN));
assert!(near(a, left) && near(b, right), "preview {preview}: {a} to {b}");
}
+22 -8
View File
@@ -191,16 +191,30 @@ mod tests {
#[test]
fn same_bytes_for_every_pair_of_grey_levels() {
// Every pixel next to every possible neighbour, one table for all of them (the picture
// tests above run the three rounds).
// tests above run the three rounds). Each pair is one row of a 2-pixel-wide image for the
// pass along rows, and one column of a 2-pixel-high image for the pass along columns, so
// one pass checks all 65,536 pairs.
let weights = weight_table();
for p in 0..=255u8 {
for q in 0..=255u8 {
// Grey, and a mixed pair, along a row (2x1) and along a column (1x2).
for src in [[p, p, p, 255, q, q, q, 255], [p, q, p ^ q, 255, q, p, q ^ 0x5a, 255]] {
assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}");
assert_eq!(pass(&src, 1, 2, false, &weights), reference(&src, 1, 2, false), "{p} {q}");
}
let pairs: Vec<(u8, u8)> = (0..=255u8).flat_map(|p| (0..=255u8).map(move |q| (p, q))).collect();
let n = pairs.len();
// The pair of pixel `i` in the output of the pass along rows (`true`) or columns.
let pair_of = |along_rows: bool, i: usize| pairs.get(if along_rows { i / 2 } else { i % n }).copied();
let first_difference = |along_rows: bool, fast: &[u8], slow: &[u8]| {
if fast.len() != slow.len() {
return Some(format!("lengths {} and {}", fast.len(), slow.len()));
}
fast.chunks(4).zip(slow.chunks(4)).position(|(a, b)| a != b).map(|i| format!("pair {:?}", pair_of(along_rows, i)))
};
// Gray, and a mixed pair: the two pixels made from levels `p` and `q`.
type Kind = fn(u8, u8) -> [[u8; 4]; 2];
let kinds: [Kind; 2] = [|p, q| [[p, p, p, 255], [q, q, q, 255]], |p, q| [[p, q, p ^ q, 255], [q, p, q ^ 0x5a, 255]]];
for (k, kind) in kinds.into_iter().enumerate() {
let rows: Vec<u8> = pairs.iter().flat_map(|&(p, q)| kind(p, q).into_iter().flatten()).collect();
let columns: Vec<u8> = (0..2).flat_map(|side| pairs.iter().flat_map(move |&(p, q)| kind(p, q)[side])).collect();
let fast = pass(&rows, 2, n, true, &weights);
assert_eq!(first_difference(true, &fast, &reference(&rows, 2, n, true)), None, "kind {k}, along rows");
let fast = pass(&columns, n, 2, false, &weights);
assert_eq!(first_difference(false, &fast, &reference(&columns, n, 2, false)), None, "kind {k}, along columns");
}
}
+4
View File
@@ -110,3 +110,7 @@ wat = { workspace = true }
[build-dependencies]
serde_json = { workspace = true }
toml = "1"
# The files of other crates that this crate's tests read, for CI's test selection.
[package.metadata.craft]
reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"]
+35 -2
View File
@@ -34,6 +34,7 @@ pub(crate) struct Spec {
pub(crate) struct AddonDialogs {
open: Option<Open>,
preview: LivePreview,
preview_error: Option<(u64, String)>,
/// The open Tangent Circle Tool radius dialog.
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
}
@@ -65,6 +66,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> {
/// Closes the open add-on dialog without an answer and rolls its preview back.
fn close_open(app: &mut VectorcraftApp) {
let Some(open) = app.addon_dialogs.open.take() else { return };
app.addon_dialogs.preview_error = None;
let id = open.id;
if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
host.with(|h| {
@@ -108,6 +110,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
color::legend::COMMAND => color::legend::open,
color::nearest::COMMAND => color::nearest::open,
select::COMMAND => select::open,
select::points_only::COMMAND => select::points_only::open,
_ => return super::arrange::open(app, id),
};
Some(open(app))
@@ -132,6 +135,7 @@ fn pump_commit(app: &mut VectorcraftApp) {
if !on_document {
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
app.addon_dialogs.preview = LivePreview::default();
app.addon_dialogs.preview_error = None;
}
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
if on_document && let Some((previewing, params)) = &live {
@@ -139,6 +143,13 @@ fn pump_commit(app: &mut VectorcraftApp) {
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
let answer = preview.run(app, *previewing, label, spec.command, params);
app.addon_dialogs.preview = preview;
if spec.command == super::select::points_only::COMMAND {
match &answer {
Some(Err(_)) => app.addon_dialogs.preview_error = Some((app.ui.status_sets, app.ui.status.clone())),
Some(Ok(_)) => clear_preview_error(app),
None => {}
}
}
if let (Some(found), Some(answer)) = (spec.found, answer) {
host.with(|h| {
if let Some(d) = h.get_mut_by_id::<HostedParamDialog>(id) {
@@ -156,18 +167,40 @@ fn pump_commit(app: &mut VectorcraftApp) {
app.status("The document was reverted. Reopen this dialog to continue.");
} else if !on_document {
app.status("The add-on settings apply only to the drawing where the dialog opened.");
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
app.status(error);
} else {
let params = (spec.params)(&result.fields);
let answer = if spec.command == super::select::points_only::COMMAND {
preview.commit_selection(app, spec.command, params)
} else {
preview.commit(app, spec.command, params)
};
if let Err(error) = answer {
app.status(error);
} else if spec.command == super::select::points_only::COMMAND {
clear_preview_error(app);
}
}
app.addon_dialogs.preview_error = None;
}
Some(None) => {
app.addon_dialogs.open = None;
app.addon_dialogs.preview_error = None;
mem::take(&mut app.addon_dialogs.preview).cancel(app);
}
None if live.is_none() => {
app.addon_dialogs.open = None;
app.addon_dialogs.preview_error = None;
mem::take(&mut app.addon_dialogs.preview).cancel(app);
}
None => {}
}
}
fn clear_preview_error(app: &mut VectorcraftApp) {
if let Some((sets, error)) = app.addon_dialogs.preview_error.take()
&& app.ui.status_sets == sets
&& app.ui.status == error
{
app.ui.status.clear();
}
}
@@ -228,4 +228,27 @@ mod tests {
let top: Vec<u64> = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect();
assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle");
}
#[test]
fn the_status_line_says_why_an_ellipse_is_refused() {
use crate::tests::panel_harness::Panel;
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let a = circle(&mut app, 100.0, 10.0);
let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [a, oval]})).unwrap();
let original = geometry(&app);
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
let before = panel.app().session.doc().unwrap().history.undo.len();
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
let why = "an ellipse whose width and height differ is not a circle";
assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status);
panel.click("OK");
panel.frame();
assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status);
assert_eq!(geometry(&panel.app()), original);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step");
}
}
+5 -2
View File
@@ -1,8 +1,8 @@
//! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the
//! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size,
//! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK
//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status
//! ([`link_status`], #5526).
//! runs `addon.select.byArtboards` with the relation chosen; Select by Link Status
//! ([`link_status`], #5526); and Edit Points Only ([`points_only`]).
use craft::behavior::{Selection, keyed};
use craft::i18n::Folder;
@@ -27,6 +27,7 @@ use crate::VectorcraftApp;
use crate::menus::{Sep, cp};
pub mod link_status;
pub mod points_only;
/// Select by Artboards, and its dialog's kind.
pub const COMMAND: &str = "addon.select.byArtboards";
@@ -40,6 +41,8 @@ const LIST_ROWS: u16 = 9;
pub fn menu() -> Vec<Node> {
let mut v = vec![cp("Select by Artboards…", COMMAND, Value::Null), Sep];
v.extend(link_status::menu());
v.push(Sep);
v.extend(points_only::menu());
v
}
@@ -0,0 +1,51 @@
//! Edit Points Only in the interface: its item in Object › Plug-ins › Selection Tools and its
//! dialog, which previews the narrowed selection on the canvas and runs
//! `addon.select.editPointsOnly` on OK; Cancel puts the selection back.
use std::borrow::Cow;
use craft::menu::Node;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
use serde_json::{Map, Value, json};
use crate::VectorcraftApp;
use crate::addons::dialogs::Spec;
use crate::dialogs::form;
use crate::menus::c;
/// Edit Points Only: the dialog's key and the command its OK runs.
pub const COMMAND: &str = "addon.select.editPointsOnly";
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
/// The menu item.
pub fn menu() -> Vec<Node> {
vec![c("Edit Points Only…", COMMAND)]
}
/// The dialog's rows.
fn rows() -> Vec<Param> {
vec![Param::new("segmentEnds", tl!("Keep Ends of Selected Segments"), ParamKind::bool(false))]
}
/// The command's params for the dialog's `fields`.
fn params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&rows(), fields))
}
/// Opens the dialog on the active document, with the ends of selected segments left out.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if app.session.active().is_none() {
return Err("no document".into());
}
let mut opening = Map::new();
opening.insert("segmentEnds".into(), json!(false));
let fields = form::fields_of(&rows(), &opening);
crate::addons::dialogs::open(app, &SPEC, fields, |fields| {
ParamDialog::new(COMMAND, tl!("Edit Points Only"), Cow::Owned(rows())).previews(true).values(Bind::bound(fields))
})
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,175 @@
use std::collections::BTreeSet;
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
use crate::addons::dialogs::tests as host;
use crate::tests::panel_harness::Panel as Harness;
/// An app with a window and two rectangles: anchors 0 and 1 of the first selected, and segment 1
/// of the second (whose ends are its anchors 1 and 2) beside its anchor 3.
fn app() -> (VectorcraftApp, NodeId, NodeId) {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
let (a, b) = (rect(10), rect(100));
let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]);
app.run("select.anchorsMany", json!({"items": items})).unwrap();
app.run("select.segments", json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
(app, a, b)
}
fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
v.iter().copied().collect()
}
/// The selected anchors of `id`, and whether any segment is selected.
fn points(app: &VectorcraftApp, id: NodeId) -> (Option<BTreeSet<(usize, usize)>>, bool) {
let sel = &app.session.doc().unwrap().selection;
(sel.anchors.get(&id).cloned(), !sel.segments.is_empty())
}
#[test]
fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard() {
let (app, a, b) = app();
let undo = app.session.doc().unwrap().history.undo.len();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…");
panel.frame();
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(false));
assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false), "the preview drops the segment and its ends");
assert_eq!(points(&panel.app(), a).0, Some(refs(&[(0, 0), (0, 1)])));
panel.focus("Keep Ends of Selected Segments");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(true));
assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false), "the ends are kept as anchor points");
panel.click("OK");
panel.frame();
let app = panel.app();
assert!(!app.any_dialog_open());
assert_eq!(points(&app, b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false));
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step");
}
#[test]
fn ok_drops_puppet_pins_without_an_undo_step() {
for previewing in [true, false] {
let (mut app, a, b) = app();
app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap();
app.run("object.group", json!({})).unwrap();
app.run("object.puppetWarp", json!({"pins": [[35, 35]], "moved": [[35, 35]], "rest": true})).unwrap();
assert!(app.session.doc().unwrap().doc.puppet.is_some());
let undo = app.session.doc().unwrap().history.undo.len();
host::open_item(&mut app, "Selection Tools", "Edit Points Only…");
let id = host::dialog_id(&app);
if previewing {
host::frame(&mut app);
assert!(app.session.doc().unwrap().doc.puppet.is_none());
}
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert!(!app.any_dialog_open());
let st = app.session.doc().unwrap();
assert!(st.doc.puppet.is_none());
assert_eq!(st.selection.objects, vec![a, b]);
assert!(!app.session.in_interaction());
assert_eq!(st.history.undo.len(), undo, "pin cleanup does not add an undo step");
}
}
#[test]
fn cancel_puts_the_selection_back() {
let (app, _, b) = app();
let before = app.session.doc().unwrap().selection.clone();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…");
panel.frame();
assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false));
panel.click("Cancel");
panel.frame();
let app = panel.app();
assert!(!app.any_dialog_open());
assert_eq!(app.session.doc().unwrap().selection, before);
}
#[test]
fn successful_preview_and_confirmation_preserve_another_status() {
for previewing in [true, false] {
let (mut app, _, _) = app();
host::open_item(&mut app, "Selection Tools", "Edit Points Only…");
let id = host::dialog_id(&app);
app.status("The active text edit reported a warning.");
if previewing {
host::frame(&mut app);
assert_eq!(app.ui.status, "The active text edit reported a warning.");
}
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert_eq!(app.ui.status, "The active text edit reported a warning.");
assert!(!app.any_dialog_open());
}
}
#[test]
fn recovering_from_a_preview_error_preserves_a_later_status() {
for previewing in [true, false] {
for same_text in [true, false] {
let (mut app, a, _) = app();
app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap();
host::open_item(&mut app, "Selection Tools", "Edit Points Only…");
let id = host::dialog_id(&app);
host::frame(&mut app);
assert!(app.ui.status.contains("no anchor points are selected"));
let status = if same_text { app.ui.status.clone() } else { "Another command reported a warning.".to_owned() };
app.status(status.clone());
host::set(&app, id, "segmentEnds", json!(true));
if previewing {
host::frame(&mut app);
assert_eq!(app.ui.status, status);
}
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert_eq!(app.ui.status, status);
}
}
}
#[test]
fn keeping_segment_ends_clears_the_preview_error() {
for previewing in [true, false] {
let (mut app, a, _) = app();
app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap();
host::open_item(&mut app, "Selection Tools", "Edit Points Only…");
let id = host::dialog_id(&app);
host::frame(&mut app);
assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status);
host::set(&app, id, "segmentEnds", json!(true));
if previewing {
host::frame(&mut app);
assert!(app.ui.status.is_empty(), "{}", app.ui.status);
assert_eq!(points(&app, a), (Some(refs(&[(0, 0), (0, 1)])), false));
}
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert!(app.ui.status.is_empty(), "{}", app.ui.status);
assert!(!app.any_dialog_open());
}
}
#[test]
fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() {
let (mut app, a, _) = app();
app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap();
let before = app.session.doc().unwrap().selection.clone();
host::open_item(&mut app, "Selection Tools", "Edit Points Only…");
let id = host::dialog_id(&app);
assert!(host::confirm(&app, id));
host::frame(&mut app);
assert!(!app.any_dialog_open());
assert_eq!(app.session.doc().unwrap().selection, before);
assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status);
}
+12 -1
View File
@@ -18,7 +18,8 @@
//! - `ui.find`: the controls of the window's access tree that match a name or role
//! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}`
//! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by
//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`)
//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by
//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders
//! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the
//! PNG comes back in the reply)
//! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly
@@ -152,6 +153,10 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
}
let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host)));
crate::dialogs::javascript_files::show_selected(app, &mut dialogs);
// The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it.
if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) {
open.insert(0, strip);
}
json!({
"scriptRunning": app.session.script_running(),
"scriptReport": app.session.shown_script_report(),
@@ -1437,6 +1442,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
if crate::prefs_dialog::is_open(app) && (p["dialog"] == "preferences" || (top && dialogs.with(|host| host.stack().is_empty()))) {
return wrap(preferences_method(app, method, p));
}
// The Simplify and Smooth sliders are the app's own strip over the canvas, not hosted dialogs: they take a
// request that names them, or the top dialog while no hosted dialog is open.
let hosted_open = dialogs.with(|host| !host.stack().is_empty());
if let Some(r) = crate::dialogs::simplify_slider::dialog_method(app, method, p, hosted_open) {
return wrap(r);
}
// The dialog asked for is `dialog`, the top one when it is missing.
let mut params = if p.is_object() { p.clone() } else { json!({}) };
if params.get("dialog").is_none_or(Value::is_null) {
+6
View File
@@ -125,6 +125,12 @@ impl LivePreview {
Ok(Value::Null)
}
/// OK for a selection command: rolls its preview back and runs the command without an interaction.
pub(crate) fn commit_selection(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result<Value, String> {
self.cancel(app);
Self::default().commit(app, cmd, params)
}
/// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is.
pub(crate) fn cancel(self, app: &mut VectorcraftApp) {
if self.previewed.is_some() && self.owns(app) {
@@ -13,11 +13,14 @@
// PLAN: the framework paths below (`craft_ui_widgets`, `craft_ui_contract`, `craft_behavior`) and
// `LivePreview`'s module are assumed; no app file imports them yet.
use craft::automation::dialogs::MAX_DIALOG_FIELDS;
use craft::automation::protocol::Params;
use craft::behavior::overlay::{Align, Side};
use craft::behavior::{CanvasView, IconId};
use craft::ui::buttons::IconButton;
use craft::ui::contract::overlay::{Anchor, Dismiss, Outside, Place};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::dialog_id;
use craft::ui::layout_components::Row;
use craft::ui::popover::Popover;
use craft::ui::primitives::IconSpec;
@@ -78,6 +81,20 @@ impl StripKind {
StripKind::Smooth => SMOOTH_AUTO_LEVEL,
}
}
/// The dialog key `ui.inspect` lists the strip under, which `ui.dialog.set`, `ui.dialog.confirm` and
/// `ui.dialog.cancel` take as `dialog`.
pub(crate) fn key(self) -> &'static str {
match self {
StripKind::Simplify => "simplifySlider",
StripKind::Smooth => "smoothSlider",
}
}
/// The id `ui.inspect` lists the strip under: the one a hosted dialog with the same key has, as a decimal string.
fn id(self) -> String {
dialog_id(self.key()).value().to_string()
}
}
/// An open slider strip: the level the canvas previews, the selection's bounds from before any
@@ -210,6 +227,132 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result<Value, String> {
Ok(json!({ "tolerance": tolerance }))
}
/// The open strip as `ui.inspect` lists a dialog, `{id, parent, key, fields: {level}}`; `None` when no strip shows.
pub(crate) fn inspected(app: &VectorcraftApp) -> Option<Value> {
let strip = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?;
let kind = strip.kind;
Some(json!({ "id": kind.id(), "parent": null, "key": kind.key(), "fields": { "level": strip.level() } }))
}
/// The level a `ui.dialog.set` on a strip of `kind` asks for: field `level`, a number from 0 to 100, as `field` and
/// `value` or as the last item of `fields`. `None` when it sets nothing.
fn requested_level(kind: StripKind, params: &Value) -> Result<Option<f64>, String> {
let level = |field: &Value, value: &Value| {
let field = field.as_str().ok_or("`field` is not a string")?;
if field != "level" {
return Err(format!("the {} slider has no field `{field}`", kind.label()));
}
match value.as_f64() {
Some(level) if (0.0..=100.0).contains(&level) => Ok(level),
_ => Err("`level` must be a number from 0 to 100".to_string()),
}
};
let Some(list) = params.get("fields") else {
return match params.get("field") {
Some(field) => level(field, params.get("value").unwrap_or(&Value::Null)).map(Some),
None if params.get("value").is_some() => Err("missing `field`".into()),
None => Ok(None),
};
};
if params.get("field").is_some() || params.get("value").is_some() {
return Err("`fields` takes the place of `field` and `value`".into());
}
let items = list.as_array().ok_or("`fields` is not a list")?;
if items.len() > MAX_DIALOG_FIELDS {
return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len()));
}
let mut last = None;
for item in items {
last = Some(level(item.get("field").unwrap_or(&Value::Null), item.get("value").unwrap_or(&Value::Null))?);
}
Ok(last)
}
/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`) when `params.dialog` names the open strip:
/// its key or the id [`inspected`] lists, or `"top"` (or no `dialog`) while `hosted_open` is false. `None` for any
/// other dialog.
///
/// `ui.dialog.set {field: "level", value}` moves the slider and previews the level, then answers with `action`
/// (`confirm` or `cancel`) when one is given; a set it refuses leaves the slider as it was. `ui.dialog.confirm` keeps
/// the preview as one undo step, as Enter does, and `ui.dialog.cancel` puts the paths back, as Escape does.
pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value, hosted_open: bool) -> Option<Result<Value, String>> {
let kind = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?.kind;
let ours = match params.get("dialog") {
None | Some(Value::Null) => !hosted_open,
Some(Value::String(named)) if named == "top" => !hosted_open,
Some(Value::String(named)) => named == kind.key() || *named == kind.id(),
Some(named) => named.as_u64().is_some_and(|id| id.to_string() == kind.id()),
};
if !ours {
return None;
}
let keys: &[&str] = match method {
"ui.dialog.set" => &["dialog", "field", "value", "fields", "action"],
"ui.dialog.confirm" | "ui.dialog.cancel" => &["dialog"],
_ => return None,
};
if let Err(e) = Params(params).only(None, keys) {
return Some(Err(e));
}
let answer = match (method, params.get("action")) {
("ui.dialog.confirm", _) => Some(true),
("ui.dialog.cancel", _) => Some(false),
(_, None | Some(Value::Null)) => None,
(_, Some(action)) if action == "confirm" => Some(true),
(_, Some(action)) if action == "cancel" => Some(false),
(_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())),
};
let level = if method == "ui.dialog.set" {
match requested_level(kind, params) {
Ok(None) if answer.is_none() => return Some(Err("missing `field`".into())),
Ok(level) => level,
Err(e) => return Some(Err(e)),
}
} else {
None
};
let mut strip = app.object_dialogs.strip.take()?;
if let Some(level) = level {
let before = strip.level;
strip.level = level;
let params = strip.params();
let ran = strip.preview.run(app, true, kind.label(), kind.cmd(), &params);
// Nothing ran: the canvas already previews this level, or another edit holds the interaction.
let shown = || {
app.session
.active()
.and_then(|doc| doc.interaction.as_ref()?.preview.as_ref())
.is_some_and(|(cmd, showing)| cmd == kind.cmd() && showing == &params)
};
let error = match ran {
Some(Err(e)) => Some(e),
None if !shown() => Some(tl!("Finish the active edit first.").to_owned()),
_ => None,
};
if let Some(e) = error {
strip.level = before;
app.object_dialogs.strip = Some(strip);
return Some(Err(e));
}
}
app.object_dialogs.strip = Some(strip);
let set = inspected(app).unwrap_or(Value::Null);
let Some(answer) = answer else { return Some(Ok(set)) };
let strip = app.object_dialogs.strip.take()?;
let result = if answer {
let params = strip.params();
strip.preview.commit(app, kind.cmd(), params).map(|_| Value::Null)
} else {
strip.cancel(app);
Ok(Value::Null)
};
// A set with an `action` replies `{dialog, result}`: the slider as the set left it, and the answer's result.
Some(match (method, result) {
("ui.dialog.set", Ok(result)) => Ok(json!({ "dialog": set, "result": result })),
(_, result) => result,
})
}
/// Where the strip hangs: a point under the lowest corner on screen of the selection's bounds from
/// before the preview, centred on them, kept on the canvas.
fn anchor_rect(view: &CanvasView, bounds: Option<Rect>) -> ScreenRect {
+146
View File
@@ -326,3 +326,149 @@ fn path_sliders_close_when_file_revert_restores_the_artwork() {
assert!(app.session.in_interaction());
}
}
/// The two sliders: the dialog key `ui.inspect` lists, the menu command that opens it and its undo step's name.
const PATH_SLIDERS: [(&str, &str, &str); 2] =
[("simplifySlider", "object.path.simplify", "Simplify"), ("smoothSlider", "object.path.smooth", "Smooth")];
/// One control channel request, answered at once.
fn control(app: &mut VectorcraftApp, method: &str, params: serde_json::Value) -> serde_json::Value {
let ctx = app.ui_ctx.clone().unwrap();
let (req, _) = craft::automation::ControlRequest::new(method, params);
let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method} answered later") };
r
}
/// The open dialog `key` in `ui.inspect`'s `dialogs`.
fn inspected_dialog(app: &mut VectorcraftApp, key: &str) -> Option<serde_json::Value> {
let r = control(app, "ui.inspect", json!({}));
r["result"]["dialogs"].as_array()?.iter().find(|d| d["key"] == key).cloned()
}
/// Both sliders show in `ui.inspect` as the dialog their params text names, with field `level`. `ui.dialog.set`
/// moves the slider and previews the level, and `ui.dialog.confirm` keeps the result as one undo step.
#[test]
fn path_sliders_show_in_ui_inspect_and_ui_dialog_confirm_keeps_the_level() {
for (key, command, label) in PATH_SLIDERS {
let mut app = app_with_dense_path();
let undo_len = app.session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut app, command, json!({}));
settle(&mut app);
let open = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"));
assert!(open["fields"]["level"].is_number(), "{open}");
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(r["result"]["fields"]["level"], 20.0, "{r}");
let preview = app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).map(|p| p.1);
assert_eq!(preview, Some(json!({"level": 20.0})), "{key}");
settle(&mut app);
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(json!(20.0)), "{key}");
let r = control(&mut app, "ui.dialog.confirm", json!({"dialog": key}));
assert_eq!(r["ok"], true, "{r}");
assert!(inspected_dialog(&mut app, key).is_none(), "{key}");
assert!(!app.session.in_interaction(), "{key}");
let history = &app.session.doc().unwrap().history;
assert_eq!(history.undo.len(), undo_len + 1, "{key}");
assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}");
}
}
/// A repeated level succeeds, but another active edit blocks a set and leaves the slider's level unchanged.
#[test]
fn path_sliders_refuse_a_set_when_another_edit_owns_the_interaction() {
for (key, command, _) in PATH_SLIDERS {
let mut app = app_with_dense_path();
crate::menus::invoke(&mut app, command, json!({}));
settle(&mut app);
for _ in 0..2 {
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 30}));
assert_eq!(r["ok"], true, "{key}: {r}");
}
let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone();
app.session.cancel_interaction().unwrap();
app.begin_interaction("Other").unwrap();
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20}));
assert_eq!(r["ok"], false, "{key}: {r}");
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key}");
settle(&mut app);
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level), "{key}");
}
}
/// `ui.dialog.set` with `action` sets the level and answers in one request, replying `{dialog, result}` with the
/// slider as the set left it: `confirm` keeps the level as one undo step, and `cancel` puts the paths back.
#[test]
fn path_sliders_answer_a_set_with_an_action_in_one_request() {
for (key, command, label) in PATH_SLIDERS {
for action in ["confirm", "cancel"] {
let mut app = app_with_dense_path();
let before = app.session.active().unwrap().doc.clone();
let undo_len = app.session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut app, command, json!({}));
settle(&mut app);
let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "fields": [{"field": "level", "value": 30}], "action": action}));
assert_eq!(r["ok"], true, "{key} {action}: {r}");
assert_eq!(r["result"]["dialog"]["key"], key, "{r}");
assert_eq!(r["result"]["dialog"]["fields"]["level"], 30.0, "{r}");
assert!(r["result"].get("result").is_some(), "{r}");
assert!(inspected_dialog(&mut app, key).is_none(), "{key} {action}");
assert!(!app.session.in_interaction(), "{key} {action}");
let history = &app.session.doc().unwrap().history;
if action == "confirm" {
assert_eq!(history.undo.len(), undo_len + 1, "{key}");
assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}");
} else {
assert_eq!(history.undo.len(), undo_len, "{key}");
assert_eq!(app.session.active().unwrap().doc, before, "{key}");
}
}
}
}
/// With a hosted dialog open over a slider, `ui.inspect` lists the slider first, and `"top"` names the hosted dialog.
#[test]
fn path_sliders_list_below_a_hosted_dialog_that_top_names() {
let mut app = app_with_dense_path();
crate::menus::invoke(&mut app, "object.path.simplify", json!({}));
settle(&mut app);
app.run("ui.javascriptFilesDialog", json!({})).unwrap();
let r = control(&mut app, "ui.inspect", json!({}));
let open = r["result"]["dialogs"].as_array().cloned().unwrap_or_default();
assert!(open.len() >= 2 && open[0]["key"] == "simplifySlider", "{open:?}");
let r = control(&mut app, "ui.dialog.cancel", json!({"dialog": "top"}));
assert_eq!(r["ok"], true, "{r}");
assert!(inspected_dialog(&mut app, "simplifySlider").is_some(), "the hosted dialog closed, the slider stays");
let r = control(&mut app, "ui.inspect", json!({}));
assert_eq!(r["result"]["dialogs"].as_array().map(Vec::len), Some(open.len() - 1), "{r}");
}
/// `ui.dialog.cancel` on the top dialog puts the paths back, as Escape does. A level outside 0..100, a value that
/// isn't a number and another field are refused, and the slider keeps its level.
#[test]
fn path_sliders_answer_ui_dialog_cancel_and_refuse_bad_fields() {
for (key, command, _) in PATH_SLIDERS {
let mut app = app_with_dense_path();
let before = app.session.active().unwrap().doc.clone();
let undo_len = app.session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut app, command, json!({}));
settle(&mut app);
let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone();
for bad in [json!({"field": "level", "value": 101}), json!({"field": "level", "value": "20"}), json!({"field": "tolerance", "value": 2})] {
let mut params = bad.clone();
params["dialog"] = json!(key);
let r = control(&mut app, "ui.dialog.set", params);
assert_eq!(r["ok"], false, "{key} {bad}: {r}");
assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key} {bad}");
}
let r = control(&mut app, "ui.dialog.cancel", json!({}));
assert_eq!(r["ok"], true, "{r}");
assert!(inspected_dialog(&mut app, key).is_none(), "{key}");
assert!(!app.session.in_interaction(), "{key}");
assert_eq!(app.session.active().unwrap().doc, before, "{key}");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len, "{key}");
}
}
+36 -3
View File
@@ -10,6 +10,10 @@
//! - The web host then starts again with new graphics and a new egui context, handing it the same
//! app. The app notices the new context and makes everything it uploaded to the old one again:
//! its fonts and theme, the canvas, and every texture cache ([`TexCache`]).
//! - The desktop host can't give the window a new device. When the window closes after a loss
//! ([`GraphicsLoss::happened`]), the process ends once the app has saved what it keeps on
//! quitting, before the window's graphics are torn down: releasing a swapchain that still holds
//! a frame the lost device couldn't present panics in the graphics driver layer (#6374).
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -20,7 +24,16 @@ use crate::VectorcraftApp;
/// Raised by the host when the window's graphics device is lost (from any thread), read on the UI
/// thread. Cheap to clone; the clones share the report.
#[derive(Clone, Default)]
pub struct GraphicsLoss(Arc<Mutex<Option<String>>>);
pub struct GraphicsLoss(Arc<Mutex<Loss>>);
/// What a [`GraphicsLoss`] holds.
#[derive(Default)]
struct Loss {
/// The loss not handled yet, for [`GraphicsLoss::take`].
why: Option<String>,
/// A loss was reported at some point, handled or not.
happened: bool,
}
impl GraphicsLoss {
/// The graphics device was lost (`why`, for the log): the next frame of `ctx` handles it. A
@@ -28,13 +41,23 @@ impl GraphicsLoss {
pub fn report(&self, ctx: &egui::Context, why: impl Into<String>) {
let why = why.into();
log::error!("vectorcraft: the graphics device was lost: {why}");
self.0.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(why);
{
let mut loss = self.0.lock().unwrap_or_else(|e| e.into_inner());
loss.why.get_or_insert(why);
loss.happened = true;
}
ctx.request_repaint();
}
/// The loss reported since the last call, if any.
pub fn take(&self) -> Option<String> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).take()
self.0.lock().unwrap_or_else(|e| e.into_inner()).why.take()
}
/// Whether the device was lost at any point, a loss [`Self::take`] already handled included.
/// A window can't be given a new device, so once true this stays true.
pub fn happened(&self) -> bool {
self.0.lock().unwrap_or_else(|e| e.into_inner()).happened
}
}
@@ -190,6 +213,16 @@ mod tests {
assert_eq!(loss.take(), None, "handled once");
}
#[test]
fn a_handled_loss_is_still_known_when_the_window_closes() {
let (loss, ctx) = (GraphicsLoss::default(), crate::testing::ui_context());
assert!(!loss.happened(), "nothing lost yet");
let (l, c) = (loss.clone(), ctx.clone());
std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap();
assert!(loss.take().is_some(), "the next frame handles it");
assert!(loss.happened(), "the device stays lost after the frame handled the report");
}
#[test]
fn a_tex_cache_empties_when_the_ui_moves_to_a_new_context() {
thread_local! {
+148 -14
View File
@@ -40,9 +40,15 @@ pub(crate) struct Menus {
/// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the
/// first: the `input` of [`state_key`].
pressed: Option<u64>,
/// The address of the window's keymap that the panel rows took their shortcuts from ([`keymap_addr`]), `None`
/// before the window has one.
keymap: Option<usize>,
/// How many times [`refresh`] built the model.
#[cfg(test)]
pub(crate) rebuilds: u64,
/// How many times [`refresh`] set the keymap's shortcuts again without building the model ([`refresh_shortcuts`]).
#[cfg(test)]
pub(crate) shortcut_refreshes: u64,
/// The menus as built, before a layout.
pub(crate) bar: MenuBar,
/// `bar` laid out for the shell's target: what the in-window bar shows.
@@ -92,14 +98,22 @@ pub(crate) fn translate_label(english: &'static str) -> String {
/// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one,
/// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An
/// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check
/// for an open interaction change state then and the menus stay open while it previews.
/// for an open interaction change state then and the menus stay open while it previews. The window's keymap, which the
/// shown shortcuts are read from, is in the hash too.
pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
(rows_key(app, input), keymap_addr(app)).hash(&mut h);
h.finish()
}
/// [`state_key`] without the window's keymap: what the model's rows are built from. A new keymap alone changes only
/// the shortcuts of the rows that read it, which [`refresh`] sets again without a rebuild ([`refresh_shortcuts`]).
fn rows_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
input.hash(&mut h);
app.run_count.hash(&mut h);
// The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it
// after the first frame's menus, and builds a new one when the bindings or the catalog change.
app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h);
// The user's shortcuts, which the catalog's rows are made from.
std::sync::Arc::as_ptr(&app.shortcut_overrides).addr().hash(&mut h);
let s = &app.session;
(s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h);
if let Some(d) = s.active() {
@@ -129,12 +143,19 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
}
/// Brings the menus up to date once per frame, before the frame's input: the model is built again
/// when the rows' state ([`state_key`]) or the shell's target changed.
/// when the rows' state ([`rows_key`]) or the shell's target changed. When only the window's keymap
/// changed (the framework builds the first one after the first frame's menus), the rows that read
/// their shortcuts from it get them again ([`refresh_shortcuts`]).
pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) {
let target = Target::of_shell(&WindowHost::of(ctx).shell());
let press = last_press(app, ctx);
let key = state_key(app, press);
let key = rows_key(app, press);
let keymap = keymap_addr(app);
if app.menus.key == Some(key) && app.menus.target == Some(target) {
if app.menus.keymap != keymap {
refresh_shortcuts(app, target);
app.menus.keymap = keymap;
}
return;
}
rebuild(app, target);
@@ -144,6 +165,54 @@ pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
app.menus.key = Some(key);
app.menus.target = Some(target);
app.menus.keymap = keymap;
}
/// The address of the window's keymap, which the panel rows read their shortcuts from ([`reads_keymap`]): the framework
/// builds it after the first frame's menus, and builds a new one when the bindings or the catalog change.
fn keymap_addr(app: &VectorcraftApp) -> Option<usize> {
app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr())
}
/// Whether the row running `id` with `params` shows a shortcut read from the window's keymap ([`Build::decorate`]).
fn reads_keymap(id: &str, params: &Value) -> bool {
matches!(id, "window.panel" | "edit.preferences") && !params.is_null()
}
/// Sets the shortcuts of the rows that read the window's keymap ([`reads_keymap`]) again and lays the bar out again.
/// The rows' states and the catalog stay as the last rebuild made them.
fn refresh_shortcuts(app: &mut VectorcraftApp, target: Target) {
fn walk(app: &VectorcraftApp, nodes: &mut [Node]) {
for node in nodes {
match node {
Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => {
let shortcut = super::labels::item_shortcut(app, &item.command.id, &item.command.params);
item.shortcut = shortcut;
}
Node::Submenu { children, .. } => walk(app, children),
_ => {}
}
}
}
let mut bar = std::mem::take(&mut app.menus.bar);
for menu in &mut bar.menus {
walk(app, &mut menu.children);
}
app.menus.bar = bar;
lay_out(app, target);
#[cfg(test)]
{
app.menus.shortcut_refreshes += 1;
}
}
/// Lays `app.menus.bar` out for `target` into `app.menus.laid`, which is edited only when the laid-out bar differs.
fn lay_out(app: &mut VectorcraftApp, target: Target) {
let options = LayoutOptions::new(APP_NAME).label(&translate_label);
let laid = layout(&app.menus.bar, target, &options).bar;
if *app.menus.laid != laid {
app.menus.laid.edit(|l| *l = laid);
}
}
/// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read
@@ -297,14 +366,9 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
row_states(app, &rows, &mut states, &mut checks);
crate::panels::panel_menu_states(app, &mut states);
let bar = MenuBar::new(menus);
let options = LayoutOptions::new(APP_NAME).label(&translate_label);
let laid = layout(&bar, target, &options).bar;
app.menus.rows = Some(rows);
app.menus.bar = bar;
if *app.menus.laid != laid {
app.menus.laid.edit(|l| *l = laid);
}
app.menus.bar = MenuBar::new(menus);
lay_out(app, target);
app.menus.states.edit(|s| *s = states);
}
@@ -620,7 +684,7 @@ impl Build<'_> {
// A panel row shows the chord of the panel's shortcut (`panel:<id>`), which binds `window.panel {panel}`;
// a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command.
// Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page.
"window.panel" | "edit.preferences" if !params.is_null() => {
_ if reads_keymap(id, params) => {
let mut item = item;
item.shortcut = super::labels::item_shortcut(self.app, id, params);
item
@@ -681,6 +745,76 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
}
/// A new window keymap with nothing else changed (the framework builds the first one after the first frame's
/// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus
/// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held
/// steady against tests running alongside, and the steps run again on a new app, at most 20 times, until the
/// other catalogs held still through them.
#[test]
fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() {
fn clear(nodes: &mut [Node]) {
for node in nodes {
match node {
Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => item.shortcut = None,
Node::Submenu { children, .. } => clear(children),
_ => {}
}
}
}
fn panel_chords(bar: &MenuBar) -> usize {
bar.items()
.into_iter()
.filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some())
.count()
}
let fonts = vectorcraft_text::FontDb::global();
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
let catalogs = || {
(
crate::menus::plugin_revision(),
fonts.generation(),
fonts.installed_fonts_ready(),
crate::scripts_menu::revision(),
crate::dialogs::proof_setup::saved_revision(),
)
};
let run = || {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
let ctx = crate::testing::ui_context();
for _ in 0..2 {
crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default());
}
let shown = panel_chords(&app.menus.bar);
// The menus as a refresh before the window's keymap leaves them.
app.menus.keymap = None;
for menu in &mut app.menus.bar.menus {
clear(&mut menu.children);
}
app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children)));
let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes);
refresh(&mut app, &ctx);
let first = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes);
let chords = (panel_chords(&app.menus.bar), panel_chords(&app.menus.laid));
refresh(&mut app, &ctx);
let second = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes);
(shown, first, chords, second)
};
let (shown, first, chords, second) = (0..20)
.find_map(|_| {
let before = catalogs();
let out = run();
(catalogs() == before).then_some(out)
})
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
assert!(shown > 0, "the panel rows show their shortcuts' chords");
assert_eq!(first.0, 0, "a new keymap alone does not build the menus again");
assert_eq!(first.1, 1, "the new keymap sets the shortcuts");
assert_eq!(chords.0, shown, "the panel rows show their chords again");
assert_eq!(chords.1, shown, "the laid-out bar shows them too");
assert_eq!(second, (0, 1), "the same keymap sets nothing again");
}
/// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the
/// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown.
#[test]
+4 -2
View File
@@ -334,9 +334,11 @@ fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Catego
}
/// A pinned background as saved (`{model, …}`) or as `ui.colorWheel` takes it (any color the
/// paint commands take); anything else reads as no pin.
/// paint commands take); anything else, a color with a component too large to store included,
/// reads as no pin.
fn background_value(v: &Value) -> Option<Color> {
serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v))
let saved = serde_json::from_value(v.clone()).ok().filter(vectorcraft_engine::cmd::color_is_finite);
saved.or_else(|| vectorcraft_engine::cmd::color_value(v))
}
fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Color>, D::Error> {
@@ -24,35 +24,27 @@ use crate::panels::transform;
/// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard
/// increment and Scale Strokes & Effects, and Quick Actions.
///
/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a
/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox`
/// and runs after its section.
/// Every section but Appearance shows in a `MemoView` keyed on what it reads, header and body together,
/// so a frame that changes none of it replays the whole section. What a section picks comes back
/// through an `Outbox` and runs after it.
pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
let lang = crate::i18n::current();
let units = app.session.general_unit();
let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX);
let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len());
let mut picked_units = Vec::new();
super::section(tl!("Document")).show(ui, |ui, _| {
let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) };
let _ = MemoView::new("properties-document", document, document_body).show(ui);
});
let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) };
memoized("properties-document", document, document_section, ui);
if let Some(u) = picked_units.pop() {
app.run("document.setUnits", json!({ "units": u.label() })).ok();
}
super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui));
super::section(tl!("Rulers & Grids")).show(ui, |ui, _| {
let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui);
});
super::section(tl!("Guides")).show(ui, |ui, _| {
let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui);
});
memoized("properties-rulers", Language { lang }, rulers_section, ui);
memoized("properties-guides", Language { lang }, guides_section, ui);
let mut snaps = Vec::new();
let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid);
super::section(tl!("Snap Options")).show(ui, |ui, _| {
let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) };
let _ = MemoView::new("properties-snap", snap, snap_body).show(ui);
});
let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) };
memoized("properties-snap", snap, snap_section, ui);
for command in snaps {
app.run(command, json!({})).ok();
}
@@ -62,11 +54,9 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX);
let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes);
let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app));
super::section(tl!("Preferences")).show(ui, |ui, _| {
let picked = Outbox::new(&mut prefs);
let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked };
let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui);
});
let picked = Outbox::new(&mut prefs);
let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked };
memoized("properties-preferences", preferences, preferences_section, ui);
for pick in prefs {
match pick {
PreferencePick::Increment(event) => {
@@ -79,9 +69,50 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on),
}
}
super::section(tl!("Quick Actions")).show(ui, |ui, _| {
let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui);
});
memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui);
}
/// Shows `section` in a `MemoView` with `id`, keyed on `props`. A section scrolled out of view still runs or replays, so
/// its controls keep their focus stops and accessibility nodes. Tests can show it directly instead, to compare where
/// the memoized sections land with where direct ones do.
fn memoized<P: MemoProps>(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) {
#[cfg(test)]
if tests::shown_directly() {
let mut props = props;
section(&mut props, ui);
return;
}
let _ = MemoView::new(id, props, section).shown_out_of_view().show(ui);
}
/// The Document section: its header and [`document_body`].
fn document_section(p: &mut DocumentProps<'_>, ui: &mut Ui) {
super::section(tl!("Document")).show(ui, |ui, _| document_body(p, ui));
}
/// The Rulers & Grids section: its header and [`rulers_body`].
fn rulers_section(p: &mut Language, ui: &mut Ui) {
super::section(tl!("Rulers & Grids")).show(ui, |ui, _| rulers_body(p, ui));
}
/// The Guides section: its header and [`guides_body`].
fn guides_section(p: &mut Language, ui: &mut Ui) {
super::section(tl!("Guides")).show(ui, |ui, _| guides_body(p, ui));
}
/// The Snap Options section: its header and [`snap_body`].
fn snap_section(p: &mut SnapProps<'_>, ui: &mut Ui) {
super::section(tl!("Snap Options")).show(ui, |ui, _| snap_body(p, ui));
}
/// The Preferences section: its header and [`preferences_body`].
fn preferences_section(p: &mut PreferencesProps<'_>, ui: &mut Ui) {
super::section(tl!("Preferences")).show(ui, |ui, _| preferences_body(p, ui));
}
/// The Quick Actions section: its header and [`quick_actions_body`].
fn quick_actions_section(p: &mut Language, ui: &mut Ui) {
super::section(tl!("Quick Actions")).show(ui, |ui, _| quick_actions_body(p, ui));
}
/// What a section that reads only command states reads besides them: the interface language of its labels.
@@ -248,6 +279,63 @@ mod tests {
SECTION_RUNS.with(std::cell::Cell::get)
}
thread_local! {
/// This thread shows the memoized sections directly, outside their `MemoView`s.
static DIRECT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(super) fn shown_directly() -> bool {
DIRECT.with(std::cell::Cell::get)
}
/// The runs of text the whole Properties panel paints with nothing selected, after idle frames that replay the
/// memoized sections, with the sections shown in their `MemoView`s or, with `direct`, directly.
fn panel_texts(direct: bool) -> Vec<(String, egui::Rect)> {
DIRECT.with(|d| d.set(direct));
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let mut panel = Panel::new(app, super::super::show);
panel.frame();
let before = runs();
panel.frame();
panel.frame();
if !direct {
assert_eq!(runs(), before, "the last frames replay the memoized sections");
}
let texts = panel.texts();
DIRECT.with(|d| d.set(false));
texts
}
/// Whole sections shown in `MemoView`s, header and body, land where the same sections shown directly do under the
/// app's `SectionRhythm::Spaced` and `QuietHeader::Heads`: the Document section under the panel's heading draws no
/// rule above it, and each later section keeps the stack's gap.
#[test]
fn memoized_sections_land_where_direct_ones_do() {
let direct = panel_texts(true);
for heading in ["Document", "Rulers & Grids", "Guides", "Snap Options", "Preferences", "Quick Actions", "Snap to Point"] {
assert!(direct.iter().any(|(text, _)| text == heading), "the panel shows {heading:?}: {direct:?}");
}
let memoized = panel_texts(false);
assert_eq!(memoized, direct, "memoized sections land where direct ones do");
}
/// In a panel too short for every section, the sections below the fold still register their controls, so Tab
/// and a screen reader reach them before the panel scrolls.
#[test]
fn sections_below_the_fold_keep_their_controls() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let mut panel = Panel::new(app, super::super::show);
panel.room(egui::vec2(300.0, 200.0));
panel.frame();
panel.frame();
for name in ["Keyboard Increment", "Scale Strokes & Effects", "Snap to Grid"] {
assert!(panel.shows(name), "the panel registers {name:?} below the fold");
assert!(panel.rect(name).top() > 200.0, "{name:?} is below the fold of a 200 pt panel");
}
}
#[test]
fn canceling_the_units_popup_leaves_the_document_unchanged() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
@@ -347,6 +347,8 @@ fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() {
(json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"),
(json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"),
(json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"),
(json!({"contrastBackground": {"model": "rgb", "r": 1e300, "g": 0, "b": 0}}), "`contrastBackground` must be a color or null"),
(json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1e300}}), "`contrastBackground` must be a color or null"),
] {
assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}");
}
+7 -1
View File
@@ -74,6 +74,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU (
- **Automatic on Linux and the BSDs** is the GPU that drives the panel or a monitor, then the system's order: Mesa's Vulkan device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid laptops; `DRI_PRIME` and `MESA_VK_DEVICE_SELECT` steer it). A Wayland compositor may not accept frames from another GPU: on a desktop whose compositor ran on an NVIDIA GPU, rendering on the Ryzen's integrated GPU made KWin end the window's connection ("importing the supplied dmabufs failed") and 0.5.0 crashed at startup (#502).
- 0.5.0 saved `powerSaving`, its default, for everyone; it reads as `automatic`.
- **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`, #651). The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking.
- **If no graphics adapter can show the window at all** on Linux or a BSD, the app starts once more on Mesa's software renderer (llvmpipe, through `LIBGL_ALWAYS_SOFTWARE=1`), which draws on the CPU and is slower, and says so in the status bar. That covers every adapter left out by the restarts above, and a GPU whose driver offers none of the backends wgpu draws with: Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (PCI id `8086:0046`, in a ThinkPad T510) has OpenGL 2.1 alone, so wgpu started no backend and the window failed with `Failed to create surface for any enabled backend: {}` (#2654). The software start carries `VECTORCRAFT_GPU_SOFTWARE`, so it happens once; when it fails too, or when `WGPU_BACKEND`, `WGPU_ADAPTER_NAME` or `LIBGL_ALWAYS_SOFTWARE` is set, the app exits with an error that names the backends the driver needs. On a laptop with a second GPU, choosing that GPU in the firmware settings may give a driver with one of these backends.
- **If the window's first frame never reaches the screen** within 20 seconds of the app being created (the files named at the start opened), the adapter counts as hanging and the app starts again without it in the same way (#964: High Performance on a hybrid laptop left the app running in the background with no window and nothing in the log). A window minimized at the start isn't counted. When the processor that hung was chosen in Preferences, the status bar points to Automatic.
- **If the app crashes while the window starts**, as when Intel's Direct3D 12 driver (`igd12umd64.dll`) ended 0.9.0 before its window appeared on an Intel UHD Graphics 605 (#2243), no code in the process runs to start it again, so the next start leaves the adapter out. Each start writes `graphics-start.json` in the log folder before the graphics start and adds the adapter once one is picked; when the first frame reaches the screen or the app ends without crashing, the start is cleared from the file. A start that finds an earlier start still recorded there logs the adapter, leaves it out and shows a note in the status bar. When the crash came while the adapters were being listed (wgpu's Direct3D 12 backend creates a device on each GPU to list it), the next start lists OpenGL's adapters alone; on macOS, where wgpu has no OpenGL adapters, it lists them all. Later starts keep leaving them out until the app version or Preferences › Performance › Graphics Processor changes, a start shows its first frame on the adapter that crashed, or no adapter is left that can show the window. `WGPU_BACKEND` and `WGPU_ADAPTER_NAME` choose regardless of the file: a start with `WGPU_BACKEND=dx12` tries Direct3D 12 again, and when its first frame appears, the crash is cleared. A process ended from outside during the start (Task Manager, `kill`) counts as a crash. Runs without preferences (`VECTORCRAFT_NO_PREFS`) record nothing, and a start made while another copy of the app is starting neither reads nor writes the file.
- **To recover from a Graphics Processor choice that doesn't work** without editing files: start once with `WGPU_POWER_PREF=low` (or `WGPU_ADAPTER_NAME=…`), which overrides the preference for that start while settings still save, and set Graphics Processor back to Automatic. `VECTORCRAFT_NO_PREFS=1` also starts without it, but saves nothing.
@@ -109,6 +110,7 @@ When the interface thread stays in one part of a frame for 3 s (VectorCraft's ow
| `WGPU_ADAPTER_NAME` | Graphics adapter by (part of) its name, any case (see [Desktop graphics processor](#desktop-graphics-processor)) |
| `WGPU_BACKEND` | Graphics backends: `vulkan`, `dx12`, `metal`, `gl` |
| `VECTORCRAFT_GPU_SKIP` | Set by the app when it starts again without a graphics adapter that failed (see [Desktop graphics processor](#desktop-graphics-processor)) |
| `VECTORCRAFT_GPU_SOFTWARE` | Set by the app, with `LIBGL_ALWAYS_SOFTWARE=1`, when it starts again on Mesa's software renderer because no graphics adapter could show the window (Linux and the BSDs; see [Desktop graphics processor](#desktop-graphics-processor)) |
| `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) |
## macOS: the menu bar
@@ -134,7 +136,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On
- **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server.
- **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text).
- **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own.
- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way.
- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (<the pen's name>): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --nosocket=fallback-x11 --socket=x11 ai.storyteller.vectorcraft` gives it one and keeps its Wayland socket. `--socket=x11` alone is not enough: while `fallback-x11` is set, Flatpak gives the app no X display whenever Wayland is available. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way.
- **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure.
- **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11.
@@ -349,6 +351,10 @@ The app decides which cursors exist; whoever draws them works from the list. For
`cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there.
## Test lint
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
## Tests
- `cargo xtask test` runs the workspace's unit and integration tests with
+11 -9
View File
@@ -93,8 +93,8 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers
The
[linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html)
describes plotting an object's horizontal and vertical dimensions by holding Alt
(Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's
outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when
(Option on macOS) over its path. With Alt held, hovering a path shows the box the path's strokes
paint (described below), as a Smart Guide when Smart Guides are on and in the tool's own color when
they are off, with its width and height beside the pointer when Measurement Labels are on.
Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out
from the path places it on release. The rest is VectorCraft's own rule. With
@@ -105,12 +105,14 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers
that starts no segment is left out. They are read again whenever the path changes, so a turned
path shows its new overall width or height rather than that of its bounding box before the
turn. The line keeps its distance from the whole path when the path changes or the dimension
changes orientation. With Use Preview Bounds on, the box and the dimension reach the outside of
the path's strokes, the width or height that W and H show: each outermost point moves out to the
edge of the box the strokes paint (a member of a compound path takes the compound path's
strokes, with an arrowhead only where the compound path draws one on that member), and a dimension placed that way measures to there again when the path or its strokes
change. Geometry effects are not included. Alt has this effect only before the first point is
clicked.
changes orientation. With Use Preview Bounds on or off, the box and the dimension reach the
outside of the path's strokes, the width or height that W and H show with Use Preview Bounds
on: each outermost point moves out to the edge of the box the strokes paint (a member of a
compound path takes the compound path's strokes, with an arrowhead only where the compound path
draws one on that member), and a dimension placed that way measures to there again when the
path or its strokes change. Geometry effects are not included. A dimension of a whole path saved
without `"preview":true` keeps measuring between the outermost points. Alt has this effect only
before the first point is clicked.
- **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two
straight lines that meet (or would, extended), then click to place.
- **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its
@@ -205,7 +207,7 @@ another document.
`vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":<id>}`
measures a whole path, linear only: between its leftmost and rightmost points when horizontal
or aligned, and its topmost and bottommost points when vertical. With `"preview":true` (what
the tool records with Use Preview Bounds on; `false` when omitted, and any value other than
the tool records for an Alt-placed dimension; `false` when omitted, and any value other than
`true` or `false` is an error) those points move out to the outside of the path's strokes. A
version without the extent source does not open a file that holds one, and a version without
`preview` measures such a dimension between the points themselves. `offset` is the distance of
+7 -5
View File
@@ -31,7 +31,7 @@ OpenType panel feature-row context menus (part of G12): a secondary click on a f
Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged.
Appearance panel row context menus (part of G12): right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Evidence: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, and `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance` in `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged.
@@ -187,7 +187,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain.
- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged.
- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged.
- **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged.
@@ -199,7 +199,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Polygon/Star count persistence:** Exact-size placement saves the chosen count for later drags and reopening the existing canvas dialog. Regression coverage includes both tools, repeated drags, switching tools and Cancel. The remaining G1 scope and estimates are unchanged.
- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged.
- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged.
- **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. Broader scope and estimates unchanged.
@@ -400,8 +400,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
## G11 Correctness bugs in core tools
- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged.
- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged.
- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/it/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged.
- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged.
- **Implemented (#6470):** Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping, following the existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions are in `crates/tools/src/draw2/anchor/tests.rs`; broader G11 scope and estimates unchanged.
@@ -853,6 +853,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
character and paragraph attributes, their links to each other and the stories they form, its character and
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
runs a script in a named engine whose globals last between runs,
File › Scripts lists the scripts of the Scripts folder, and
+1 -1
View File
@@ -25,7 +25,7 @@ It reads the pen's tilt and barrel rotation on Windows with Windows Ink (#372),
| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none (an Art brush's Width, a Pattern brush's Scale and Bristle brushes follow them, #8490); 3–6 h (#372) |
| Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial |
| Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch-screen rotation missing (the Touch workspace ships, #3139), 3–5 h |
| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done |
| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | smooth scroll; pinch and rotate on native Wayland where the compositor offers pointer gestures (#5981), not under X11 or XWayland | yes | done |
| HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated |
| Multiple monitors: panels and document windows on another screen | yes | yes: floating panels (#4135) and floating document windows (#5278) are OS windows, and a floating panel reopens on the monitor where it was left (#6038) | yes | under X11; on Wayland they are windows inside the main window | — | partial: Wayland remains, 6–10 h (with multiple windows, gap G7) |
| Display colour profile (proof and display through the monitor's ICC) | yes | yes: the window is tagged sRGB and macOS converts it | yes: the display's default ICC profile, Windows' own conversion with Advanced Color on | X11: colord or `_ICC_PROFILE`; Wayland: sRGB | — | done on macOS, Windows and X11; Wayland and floating document windows remain |
+137 -52
View File
@@ -642,7 +642,8 @@ Paint values (`fill`, `stroke`) accept `"#rrggbb"`, `"none"`, `[r,g,b]` (0..1),
or a full `paint.setFill` params object (`{"gradient": …}`, `{"swatch": "name"}`).
A color read this way (a fill or stroke color, a swatch's, an artboard's or new type's color, and the other colors
commands read in these forms) that is given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without
the `#`) is an error and changes nothing, as VectorCraft's own rule. The `color` of Drop Shadow, Inner Glow, Outer Glow
the `#`) is an error and changes nothing, as VectorCraft's own rule. So is a color with a component too large to store
as a 32-bit float, such as `{"c": 1e300, "m": 0, "y": 0, "k": 0}`. The `color` of Drop Shadow, Inner Glow, Outer Glow
and Shift to Color is read differently and takes `#rrggbbaa`, as described below.
For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new-art appearance](#new-art). Both
also style the new object in the same call: `dash` (lengths, or null for solid), `cap`
@@ -985,6 +986,8 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a
`item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later
calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of
its kind (`paint.proxies`) and the Gradient tool's annotator then show that row.
An `appearance.setActiveItem` call made outside a drag's preview keeps its selected row, including an explicit
`index: null`, when the preview is replaced or canceled.
`inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity`
(0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with
or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint
@@ -2231,9 +2234,10 @@ in a replayed journal or action too, and nothing changes.
The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color must be one the effect can read: a hex color
(`#rrggbb`, `#rgb` or `#rrggbbaa`, with or without the `#`), `black`, `white`, `red`, `green` or `blue`, `[r, g, b]`
(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`).
`effect.apply` and `effect.setParams` refuse any other value themselves (where the parameter check runs first, a number
or a boolean is refused as not a string), so the app's effect dialogs and Appearance panel, a step of
(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`), with no
number too large to store as a 32-bit float (`[1e300, 0, 0]` is refused). `effect.apply` and `effect.setParams`
refuse any other value themselves (where the parameter check runs first, a number or a boolean is refused as not a
string), so the app's effect dialogs and Appearance panel, a step of
`command.batch` and a replayed journal get the same error, and the document and its undo history stay as they were:
```json
@@ -2745,9 +2749,11 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256
characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
object; a document's `saveAs`, `exportFile`, `imageCapture` or `exportVariables` counts too; the same objects left out are not counted for the File-only
functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`,
which a Folder object does not have), `filesOpened` (files opened in other apps), `network`,
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
have; a document's `saveAs`, `exportFile`, `imageCapture` or `exportVariables` counts too, and so does `SaveOptions.SAVECHANGES`
wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened
in other apps), `network`,
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
@@ -3103,6 +3109,93 @@ through `$`:
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
themselves that this page does not describe are not defined yet and read as `undefined`.
- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file.
When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's
file and saved state unchanged.
`Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is.
`app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`
(https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/).
`file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the
format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/,
https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/);
without options the name supplied by the script picks the format before symbolic links are resolved, and a name
without a recognized extension uses the document's current format. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
`exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`;
`cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`,
`saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
`ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF.
As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an
empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is
true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the
document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/).
`exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()`
and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/,
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
`pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files.
`app.open` rejects a file over 128 MiB before reading it.
Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`;
explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`,
`EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as
`"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`,
`CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`,
`MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`,
`PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and
`SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A
path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written
or opened.
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open
document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is
read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs`
and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the
files a command reads or writes besides the one named, such as an SVG's linked files, are
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
when the script's folders refuse one of those files, none of them is written; a write that fails once the
first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
`parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in
preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and
`[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes
a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range
(every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its
artboards to `<name>-<artboard name>.ai`, and an EPS range goes to `useArtboards`, which writes
`<name>_<artboard name>.eps` for each of two or more artboards beside the file at the path, and for one artboard
writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS
`artboardRange` is not checked against the document's artboards, but one that is not written as a range of
artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's
file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of
`""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw
`Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved
without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an
undo step. Assigning its current value runs no command and adds no journal entry.
With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`;
`SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document
was last saved in and after the same write-access check of the path as `saveAs`, and throws an error
and leaves the document open when the document has no file (a converted or recovered document included) or when
the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several
artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with
`useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other
than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve
Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not
refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with
`useArtboards: false`, and the SVG save still refuses a range that selects several artboards.
`SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
(`saveAs: …`).
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
@@ -3369,48 +3462,6 @@ through `$`:
on `add()`; `add()` gives a tag with an empty name and value; `getByName` gives the first tag with the name;
`name` and `value` take strings of at most 65,536 bytes, and an object has at most 64 tags. A tag that was deleted
throws `Stale tag`, and one whose page item was deleted throws `Stale page item`.
- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file.
`Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is.
`app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`
(https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/).
`file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the
format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/,
https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/);
without options the name supplied by the script picks the format before symbolic links are resolved.
A name without a recognized extension uses the document's current format. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
`exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`,
`postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
`ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF.
`exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()`
and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/,
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
`pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`,
`EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`.
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open
document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is
read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs`
and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the
files `app.open` reads besides the one named, such as an SVG's linked files, are read only where the script's
folders allow, including links inherited from documents that were already open. Rendering existing documents
can still read their inherited linked files. Ancillary writes require the script's write grants.
`saveAs` and `exportFile` send command warnings to the Script Console with the method name.
`userInteractionLevel` does not change what a command
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help
pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
keeps the preset's value. A bad value throws an error before anything is written.
- `Document.rasterize(sourceArt, clipBounds?, options?)` runs `object.rasterize` with the source art's `ids` and gives
the new `RasterItem`; the source art is replaced in one undo step and its objects throw `Stale page item` after.
`Document.imageCapture(imageFile, clipBounds?, options?)` runs `document.export` of a PNG of the art inside
@@ -10625,7 +10676,9 @@ document. With no document open they fail with "no document open". `document.act
the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip
does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the
current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and
remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current
remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as
having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs
it. `file.close {index}` on a document other than the current one leaves the current
document current, and its tool keeps its state; closing the current document makes the document in the next tab
current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first,
to ask whether to save it.
@@ -16957,12 +17010,19 @@ Commands:
circle of the smaller circle's size about the arc's center. For equal circles that gap apart, that center is where a
third circle the gap from both would sit, as in a triangular grid, so the channels around an empty place in such a
grid are one width; in a square grid they are not. Giving both `radius` and `gap` is an error. Overlapping and
touching circles are joined at every radius. One circle inside the other is an error, and so are circles too far apart
touching circles are joined at every radius. An object that is not a circle is an error that says why: an ellipse whose
width and height differ, a compound path, an object that is hidden or locked, or another object. More than 2,000
objects (with each group other than a clipping group counted as the objects inside it, and a clipping group as one
object, which is not a circle) are refused as more than 2,000 circles before any of them is
checked, so that error does not say which object is not a circle. One circle inside the
other is an error, and so are circles too far apart
for the radius or gap: the arcs would not reach both circles, or would cross before they do. The error suggests a
larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two
circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the
upper circle, painted as it, and the circles stay. The outline is selected. Two circles are bridged however far apart
their outlines are; `reach` does not apply to them.
their outlines are; `reach` does not apply to them. When outlines replace circles (with any number of circles), a group
or compound path that the circles leave with nothing in it is removed, and so is each group above it left empty in
turn; layers stay.
With three or more circles, every two whose outlines are at most `reach` apart (0 to 10,000 pt, 10 by default;
overlapping ones included) are bridged the same way, and the bridges that connect are united into one shape each,
which can have holes where bridges enclose space; holes smaller than 1% of the smallest circle's area are filled. A
@@ -17562,6 +17622,31 @@ locked". Select by Link Status… lists every image and placed document with its
name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select
selects the rows chosen, zooming to them when Zoom to Selection is on (the default).
`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to paths and their selected
anchor points. A path with selected anchor points keeps them.
A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of
the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor
points. A path selected whole stays selected whole and still receives object transforms, including stroke and effect
scaling when enabled. A group or compound path selected whole is replaced by the paths
inside it, each selected whole unless it has an explicit anchor pick. Explicit anchor picks take precedence regardless
of selection order. The command leaves out hidden and locked paths, a Shaper Group's original shapes and, while
guides are locked, paths made into guides. Type,
images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. The command
does not add an undo step. It returns `{changed, count, points}`: `changed` is `false` when the
selection already held only anchor points, `count` is the number of paths left selected and `points` the number of
anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a
`segmentEnds` that is not `true` or `false` (including `null`) is an error, and the selection is left as it was.
```json
{"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}}
```
In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected
Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection
back.
After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current
status message. Messages from other commands stay displayed.
### Vector Halftone (live)
`addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its
+3
View File
@@ -77,6 +77,9 @@ WebAssembly Clippy run also encounters existing target-specific lints in unchang
(`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and
the native Clippy run above pass without source changes for those findings.
The engine preflight tests now live in the `it` test binary. Run them with
`cargo test -p vectorcraft-engine --test it preflight::`.
### Review follow-up on `main` at `ee60c51fd`
The exact-threshold and locked-artboard regressions were first run against the original
+2 -2
View File
@@ -36,7 +36,7 @@ Color conversion (#8804) builds one first-name index for the document's global s
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged.
Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending.
@@ -208,7 +208,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
+15 -14
View File
@@ -79,7 +79,7 @@ Variables panel row context menus (2026-11-20, G12): Right-click highlights the
Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged.
`window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged.
@@ -348,8 +348,8 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de
| Area | Weight | Done | Main gaps | One agent (h) | Kind |
|---|---:|---:|---|---:|---|
| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) |
| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged |
| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/it/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) |
| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/it/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged |
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) |
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) |
| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) |
@@ -694,12 +694,12 @@ since 2026-10-01.
- **`.ai` clipping paths grouped in a compound path (#8128):** `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs` covers clipping paths grouped in a compound path (`*u u <path> W n … U *U`, also nested in other groups): they are the compound path's subpaths, and the compound clipping path, their union, clips its clipping group however many there are and wherever in the group it is written. Synthetic files written in the test; no fixtures added. Scores and hours unchanged.
**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged.
**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/it/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged.
- `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`).
- Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`).
- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged.
- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/it/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged.
- **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged.
- **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`.
@@ -718,7 +718,7 @@ since 2026-10-01.
- **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged.
**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged.
**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged.
- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged.
@@ -729,7 +729,7 @@ since 2026-10-01.
- **PDF Indic type (#5235, #6906):** `crates/pdf/src/tests/reshaped.rs` covers a vowel sign the file draws before its consonant (the line keeps the file's glyphs as outlines, with a note), text in reading order (stays type), a mark with no advance (stays on its line, not vertical type of its own), outlined glyphs stroked with different dashes and translucent outlined glyphs (each keeps its own path). Synthetic font only; one real Gujarati file checked by eye on page 1. Indic type in an uninstalled font keeps the file's glyphs as outlines; reordering signs so more lines stay editable is not done. Scores and hours stay at 75% / 10-20 h.
- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged.
- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/it/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged.
- **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged.
- **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged.
@@ -759,7 +759,7 @@ since 2026-10-01.
**Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it.
**Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed.
**Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it.
**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on, the box and the dimension reach the outside of the path's strokes, which is the size W and H show when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it.
**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows the box its strokes paint, which reaches 0.5 pt past its outermost points for a centered 1 pt stroke (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it.
**Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it.
**Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it.
**Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it.
@@ -836,7 +836,7 @@ since 2026-10-01.
- **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged.
- **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged.
- **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`.
- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`.
- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`.
- **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`.
- **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`.
- **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`.
@@ -1123,7 +1123,6 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
@@ -1132,6 +1131,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
@@ -1537,6 +1537,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged.
Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`.
Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`.
Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it, leaving out a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`.
The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`.
The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`.
A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345).
@@ -1600,10 +1601,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`).
In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`.
The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`).
The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`).
- **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes).
The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged.
With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`.
The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/it/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged.
With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`.
A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path.
The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`).
While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again.
@@ -2903,7 +2904,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. Colored Revolve's faces lie over an underlay of themselves the same way, run by run in a group and with mapped graphics kept after their faces; `colored_revolve_faces_leave_no_alpha_holes_at_one_to_one` checks that no pixel inside the art lets the background through at 1:1 where 3x averaged down is opaque, live, read back from SVG and PDF, and expanded.
Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::turned_colored_inflate_facets_and_seams_cover_their_edges_once` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke.
Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke.
## Eyedropper character dimensions (2026-11-11)
+1 -1
View File
@@ -57,7 +57,7 @@ against Illustrator's public documentation; **estimated** unless noted.
| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` |
| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). |
| Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` |
| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character |
| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame |
| Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner |
| Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. |
| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu and the context menu, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) |

Some files were not shown because too many files have changed in this diff Show More