Merge main into fix/craft-libs-869c970

This commit is contained in:
dotCooCoo committed 2026-11-28 22:31:06 -08:00
commit 3b119db0d4
65 files changed
+2920 -157

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
//! The hand-off from the browser's input hook to the visible UI pass.
use std::cell::Cell;
use egui::{DroppedFileHandle, Pos2, RawInput};
/// CSS pixels from the canvas origin, and whether Shift was held.
pub(crate) type DragPosition = (f32, f32, bool);
pub(crate) struct DropBatch {
pub(crate) files: Vec<DroppedFileHandle>,
pub(crate) pos: Option<Pos2>,
pub(crate) shift: bool,
}
#[derive(Default)]
pub(crate) struct FileDrops(Vec<DroppedFileHandle>);
impl FileDrops {
pub(crate) fn capture(&mut self, raw: &mut RawInput) {
// The shared router reads dropped files at the start of the pass, before the web UI runs.
self.0.append(&mut raw.dropped_files);
}
pub(crate) fn take(&mut self, ctx: &egui::Context, position: &Cell<Option<DragPosition>>) -> Option<DropBatch> {
let files = std::mem::take(&mut self.0);
if files.is_empty() {
return None;
}
let at = position.take();
let z = ctx.zoom_factor();
let pos = at.map(|(x, y, _)| egui::pos2(x / z, y / z));
let shift = at.is_some_and(|(_, _, shift)| shift);
Some(DropBatch { files, pos, shift })
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
#[derive(Debug)]
struct Svg;
impl egui::DroppedFile for Svg {
fn path(&self) -> &Path {
Path::new("drawing.svg")
}
fn bytes(&self) -> Result<Vec<u8>, String> {
Err("test file has no contents".into())
}
}
fn check_handoff(at: Option<DragPosition>, expected_pos: Option<Pos2>, expected_shift: bool) {
let ctx = egui::Context::default();
let shared_files = Arc::new(AtomicUsize::new(0));
ctx.on_begin_pass("observe dropped files before the app UI", {
let shared_files = shared_files.clone();
Arc::new(move |ui| {
shared_files.fetch_add(ui.ctx().input(|input| input.raw.dropped_files.len()), Ordering::Relaxed);
})
});
let mut drops = FileDrops::default();
let position = Cell::new(at);
let svg = Arc::new(Svg) as DroppedFileHandle;
let mut raw = RawInput { dropped_files: vec![svg.clone()], ..Default::default() };
drops.capture(&mut raw);
let mut delivered = Vec::new();
ctx.run_ui(raw, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
let mut next = RawInput::default();
drops.capture(&mut next);
ctx.run_ui(next, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
assert_eq!(shared_files.load(Ordering::Relaxed), 0, "the shared router must not see browser-owned drops");
assert_eq!(delivered.len(), 1, "the browser UI must receive exactly one batch");
let batch = &delivered[0];
assert_eq!(batch.files.len(), 1, "the browser UI must receive exactly one file");
assert!(Arc::ptr_eq(&batch.files[0], &svg));
assert_eq!((batch.pos, batch.shift), (expected_pos, expected_shift));
assert!(position.get().is_none());
}
#[test]
fn a_positioned_browser_drop_reaches_the_web_ui_once() {
check_handoff(Some((53.0, 27.0, true)), Some(egui::pos2(53.0, 27.0)), true);
}
#[test]
fn a_browser_drop_without_a_position_reaches_the_web_ui_once() {
check_handoff(None, None, false);
}
}
+2
View File
@@ -22,6 +22,8 @@
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(any(target_arch = "wasm32", test))]
mod file_drops;
#[cfg(target_arch = "wasm32")]
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
+9 -12
View File
@@ -22,6 +22,7 @@ use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use wasm_bindgen::JsCast as _;
use crate::file_drops::{DragPosition, DropBatch, FileDrops};
use crate::locks::WebLocks;
use crate::pencil::SharedPointers;
@@ -39,7 +40,7 @@ struct OpenInboxes {
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
/// whether Shift was held: where dropped files land.
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
type DragPos = Rc<Cell<Option<DragPosition>>>;
/// A picture or file pasted into the page, read and waiting for the next frame with the modifiers
/// held at the paste, and the context to wake for it (the current runner's).
@@ -176,7 +177,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
};
app.adopt_context(ctx);
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss }))
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss, dropped: FileDrops::default() }))
}),
)
.await;
@@ -376,6 +377,7 @@ struct WebShell {
host: Host,
canvas: web_sys::HtmlCanvasElement,
loss: GraphicsLoss,
dropped: FileDrops,
}
impl WebShell {
@@ -410,9 +412,9 @@ impl eframe::App for WebShell {
embed::logic(ctx, || app.close_decision());
}
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
/// shared input hook before egui runs.
/// Gather browser drops and forward host pointer events before egui runs.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.dropped.capture(raw);
raw.events.extend(self.host.pointers.borrow_mut().take());
if let Some(app) = &mut self.app {
app.raw_input(ctx, raw);
@@ -425,18 +427,13 @@ impl eframe::App for WebShell {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
if let Some(app) = &mut self.app {
// DOM paste and drop are host input: read them in the UI phase, once per pass, not in
// `logic` where a hidden tab replays the last shown frame's input.
// Deliver host input in a visible UI pass. Hidden tabs only run `logic`.
let pasted = self.host.pasted.borrow_mut().flavour.take();
if let Some((f, held)) = pasted {
app.paste_from_host(&ctx, f, held);
}
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
if !dropped.is_empty() {
let at = self.host.drag.take();
let z = ctx.zoom_factor();
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
for f in dropped {
if let Some(DropBatch { files, pos, shift }) = self.dropped.take(&ctx, &self.host.drag) {
for f in files {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
let target = app.drop_target(&name, app.drop_spot(pos), shift);
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
+159 -1
View File
@@ -6,7 +6,7 @@
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
//! color may leave out its `#`.
//! color may leave out its `#`. [`format`] writes a color in these forms.
//!
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
@@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
/// The forms [`format`] writes a color in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Notation {
/// `#rrggbb`.
Hex,
/// `#rrggbbaa`, `ff` for a color without an alpha.
HexAlpha,
/// `rgb(51 102 153)`.
Rgb,
/// `hsl(210 50% 40%)`.
Hsl,
/// `oklch(49.93% 0.0987 250.43)`.
Oklch,
}
/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation`
/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of
/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form
/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and
/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and
/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a
/// gray is 0. [`Notation::Hex`] leaves the alpha out.
pub fn format(rgb: [f32; 3], alpha: Option<f32>, notation: Notation) -> String {
// A NaN alpha reads as none.
let alpha = alpha.filter(|a| !a.is_nan());
let bytes = rgb.map(byte);
let units = bytes.map(|v| f64::from(v) / 255.0);
let [r, g, b] = bytes;
match notation {
Notation::Hex => hex_of(rgb),
Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))),
Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)),
Notation::Hsl => {
let [h, s, l] = rgb_to_hsl(units);
format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha))
}
Notation::Oklch => {
let lch = oklab::to_oklch(units.map(|v| v as f32));
// The fewest places that read back to the same bytes, from two (four for chroma).
let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes);
let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch)));
let places = |base: i32| usize::try_from(base + p).unwrap_or(2);
let c = number(c, places(4));
// A chroma that rounds to 0 is a gray, whose hue is 0.
let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) };
format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha))
}
}
}
/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the
/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under
/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of
/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at
/// the rounded lightness and hue; the chroma is lowered a step at a time instead.
fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> {
let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra));
let step = 10f64.powi(-(4 + extra));
let mut c = rounded(c, 4 + extra);
for _ in 0..OKLCH_CHROMA_STEPS {
if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) {
return Some([l, c.max(0.0), h]);
}
c = rounded(c - step, 4 + extra);
}
None
}
/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB.
const OKLCH_CHROMA_STEPS: usize = 50;
/// `v` rounded to `places` decimal places.
fn rounded(v: f64, places: i32) -> f64 {
let f = 10f64.powi(places);
(v * f).round() / f
}
/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing.
fn alpha_part(alpha: Option<f32>) -> String {
let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2);
if percent == "100" { String::new() } else { format!(" / {percent}%") }
}
/// A hue in degrees to two places, 360 written as 0.
fn hue_text(h: f64) -> String {
hue_text_to(h, 2)
}
/// A hue in degrees to `places` places, 360 written as 0.
fn hue_text_to(h: f64, places: usize) -> String {
let text = number(h, places);
if text == "360" { "0".to_string() } else { text }
}
/// `v` to `places` decimal places, without trailing zeros or a sign on zero.
fn number(v: f64, places: usize) -> String {
let text = format!("{v:.places$}");
let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() };
if text == "-0" { "0".to_string() } else { text.to_string() }
}
/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's
/// rgbToHsl (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>); the hue of a gray is 0.
fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] {
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
let (d, l) = (max - min, (max + min) / 2.0);
if d == 0.0 {
return [0.0, 0.0, l];
}
let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) };
let h = if max == r {
(g - b) / d + if g < b { 6.0 } else { 0.0 }
} else if max == g {
(b - r) / d + 2.0
} else {
(r - g) / d + 4.0
};
[h * 60.0, s, l]
}
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
fn hex(text: &str) -> Option<CssColor> {
let digits = text.strip_prefix('#').unwrap_or(text);
@@ -412,6 +532,26 @@ mod tests {
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
}
#[test]
fn format_writes_each_notation_with_the_alpha_where_it_belongs() {
let rgb = [0.2, 0.4, 0.6];
let half = Some(0.5);
assert_eq!(format(rgb, half, Notation::Hex), "#336699");
assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980");
assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff");
assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff");
assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)");
assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)");
assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out");
assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)");
assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)");
assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)");
assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)");
assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)");
assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)");
assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)");
}
proptest! {
#[test]
fn random_text_never_panics(text in "\\PC{0,60}") {
@@ -439,5 +579,23 @@ mod tests {
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
}
#[test]
fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) {
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
let alpha = f32::from(a) / 255.0;
for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] {
let text = format(rgb, Some(alpha), notation);
let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse"));
prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text);
let read = c.alpha.unwrap_or(1.0);
match notation {
Notation::Hex => prop_assert_eq!(c.alpha, None),
Notation::HexAlpha => prop_assert_eq!(byte(read), a),
// A percentage to two places, left out when it rounds to 100.
_ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read),
}
}
}
}
}
+34
View File
@@ -146,6 +146,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
parse_color
),
cmd!(
query "color.format",
"Format Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB",
always,
format_color
),
cmd!(
query "color.contrast",
"Contrast",
@@ -158,6 +167,31 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn format_color(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.format";
let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let opacity = super::paint::opacity_param(p, C)?;
let notation = match text_param(p, "notation", C)? {
Some("hex") => Some(css::Notation::Hex),
Some("hexAlpha") => Some(css::Notation::HexAlpha),
Some("rgb") => Some(css::Notation::Rgb),
Some("hsl") => Some(css::Notation::Hsl),
Some("oklch") => Some(css::Notation::Oklch),
Some("cmyk") => None,
_ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")),
};
let cms = vectorcraft_color::cms::active();
let intent = cms.settings().intent;
let text = match notation {
None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)),
Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")),
// The working RGB numbers, as the Color panel's hex field and color.parse read them; for
// oklch() the working RGB space is sRGB.
Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n),
};
Ok(json!({ "text": text }))
}
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.parse";
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
+173 -21
View File
@@ -91,6 +91,8 @@
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
//! one out is not an undo step.
use std::sync::Arc;
use serde::Serialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
@@ -214,8 +216,18 @@ struct Form {
frame: Affine,
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`Form::of`] reduced an object to its form on this thread.
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
impl Form {
fn of(n: &Node) -> Option<Self> {
#[cfg(test)]
FORMS_MADE.with(|c| c.set(c.get() + 1));
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
f.add(n, 0)?;
let first = *f.points.first()?;
@@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
),
};
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
let in_scope = |n: &Node| {
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
let in_scope = |b: Option<Rect>| {
let Some(b) = b else { return false };
if !d.artboards.iter().any(|a| on(a.rect, b)) {
return o.include_canvas;
}
@@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
};
// A copy that lies the same way has the size of the selected object when their boxes are as
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
let same_size = |n: &Node, xf: Affine, turned: bool| {
let same_size = |b: Option<Rect>, xf: Affine, turned: bool| {
if turned {
close(xf.determinant().abs().sqrt(), 1.0)
} else {
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height()))
}
};
let mut out = vec![(*id, Affine::IDENTITY)];
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.forms.pass();
super::select::walk_selectable(d, st.isolation, |n| {
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
@@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
_ => false,
};
// The object count first: it turns most objects down before their form is made.
if n.children().map(Vec::len) == count
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
&& (!o.size || same_size(n, xf, turned))
&& (!o.appearance || same_look(key, n))
&& in_scope(n)
{
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
if n.children().map(Vec::len) != count {
return look_in;
}
let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None });
if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) {
let b = seen.bounds(n, &symbols);
if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) {
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
}
}
look_in
});
cache.forms.end(pass, d);
Ok(out)
}
/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to
/// the next so that after an edit only the objects the edit replaced are measured again. A clone
/// starts empty.
#[derive(Default)]
pub struct FormCache(std::cell::RefCell<FormCacheInner>);
#[derive(Default)]
struct FormCacheInner {
forms: ByNode<Seen>,
/// The outline of each highlighted object, or `None` when it has none and its box is shown.
outlines: ByNode<Option<BezPath>>,
}
/// An object as [`matches`] found it.
struct Seen {
/// Its form, or `None` when Global Edit doesn't support it.
form: Option<Form>,
/// Its geometric bounds, once measured; not kept for an object with symbol instances, whose
/// bounds follow the symbols' art.
bounds: Option<Option<Rect>>,
}
impl Seen {
fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option<Rect> {
if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) {
return n.geometric_bounds_with(symbols);
}
*self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols))
}
}
/// Values found for nodes of a document, by node address. The layers they were found in are held,
/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so
/// no other node can have that address while its entry is here.
struct ByNode<T> {
layers: Vec<Arc<Node>>,
values: ByAddress<T>,
}
impl<T> Default for ByNode<T> {
fn default() -> Self {
Self { layers: vec![], values: ByAddress::default() }
}
}
/// Values by node address.
type ByAddress<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHasher>>;
/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low
/// half (addresses are aligned, so their low bits are always the same).
#[derive(Default)]
struct AddressHasher(u64);
impl std::hash::Hasher for AddressHasher {
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
}
fn write_usize(&mut self, n: usize) {
let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
self.0 = x ^ (x >> 32);
}
fn finish(&self) -> u64 {
self.0
}
}
/// One walk of a document: the values it asks for, taken from the ones kept or found anew.
struct Pass<T> {
old: ByAddress<T>,
new: ByAddress<T>,
}
impl<T> Pass<T> {
fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T {
let at = std::ptr::from_ref(n) as usize;
let old = &mut self.old;
self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find))
}
}
impl<T> ByNode<T> {
fn pass(&mut self) -> Pass<T> {
let old = std::mem::take(&mut self.values);
Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old }
}
/// Keep the values `pass` asked for, found in `d`.
fn end(&mut self, pass: Pass<T>, d: &Document) {
self.values = pass.new;
self.layers.clone_from(&d.layers);
}
}
impl Clone for FormCache {
fn clone(&self) -> Self {
Self::default()
}
}
impl std::fmt::Debug for FormCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let c = self.0.borrow();
f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish()
}
}
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.global_edit.is_some() {
@@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines {
/// selected object, in their layer's color.
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
let symbols = st.doc.symbol_boxes();
members
let mut cache = st.global_edit_forms.0.borrow_mut();
let mut pass = cache.outlines.pass();
let out = members
.iter()
.filter_map(|(id, _)| {
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
return None;
// One look-up of the object's place, then down through its layers and groups: none of
// them may be selected, and the innermost layer gives the color.
let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None);
for i in st.doc.index_path(*id)? {
let c: &Node = nodes.get(i)?;
if st.selection.objects.contains(&c.id) {
return None;
}
if c.is_layer() {
layer = Some(c);
}
if let Some(ch) = c.children() {
nodes = ch;
}
found = Some(c);
}
let path = match n.stroke_path() {
Some(p) => p,
let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?;
let color = match layer.map(|l| &l.kind) {
Some(NodeKind::Layer { color, .. }) => color.rgb(),
_ => vectorcraft_doc::LAYER_COLORS[0].1,
};
let path = match pass.get(n, || {
#[cfg(test)]
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
n.stroke_path()
}) {
Some(p) => p.clone(),
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
};
Some((path, st.doc.layer_color(*id)))
Some((path, color))
})
.collect()
.collect();
cache.outlines.end(pass, &st.doc);
out
}
#[cfg(test)]
+3 -3
View File
@@ -913,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
apply_paint_opacity(s, p, paint, opacity, fill)
}
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
/// when it is left out or null.
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as
/// 0..1; `None` when it is left out or null.
pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
match p.get("opacity") {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
+158 -6
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, PathfinderOp};
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clean Up…",
["Object", "Path"],
None,
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}",
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}",
has_doc,
clean_up
),
@@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool {
})
}
/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value.
pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4;
/// The widths Hairline Slivers takes, in points.
pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive<f64> = 0.001..=3.0;
/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string
/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`].
pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result<f64> {
let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH);
if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) {
let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end());
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt")));
}
Ok(w)
}
/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths
/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke),
/// whose fill no circle `width` across fits inside? A compound path is measured as one fill.
/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]).
/// A hidden member of a compound path is measured too, since the compound path paints it.
fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option<bool> {
// A shape with no fill that paints is left to Unpainted Objects.
if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) {
return Some(false);
}
let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind {
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule),
NodeKind::Compound { children, rule } => {
let mut all = vec![];
for c in children {
let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) };
all.extend(path.subpaths.iter());
}
(all, *rule)
}
_ => return Some(false),
};
// Paths of one anchor are stray points, and open paths are lines.
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) {
return Some(false);
}
po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget)
}
/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an
/// effect on the object or on one of its fills and strokes?
fn draws_beyond_its_fill(a: &Appearance) -> bool {
a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty())
}
/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a
/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping
/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers
/// leaves its members alone.
fn holds_generated_art(n: &Node) -> bool {
let e = n.extras();
vectorcraft_tools::builder::is_live_paint(n)
|| e.type_outlines
|| e.clip_pieces
|| e.graph.is_some()
|| e.shaper.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.trace.is_some()
|| e.objects_on_path.is_some()
|| e.live_paint_gaps.is_some()
|| e.compound_shape
}
/// The objects Hairline Slivers finds in `d` for `width`.
pub(crate) struct Slivers {
pub ids: Vec<NodeId>,
/// Closed paths and compound paths whose fill couldn't be measured, which are left as they are.
pub unmeasured: Vec<NodeId>,
}
/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any.
pub(crate) fn unmeasured_warning(count: usize) -> Option<String> {
(count > 0).then(|| {
format!(
"Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are"
)
})
}
/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not
/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and
/// groups of the whole document. A compound path counts as one object. The clipping paths of groups
/// and layers (and all of a clipping group used as one), the members of live and generated art,
/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and
/// layers whose own stroke or effect paints them are left out.
pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers {
struct Walk<'a> {
width: f64,
locks: LockedArtboards<'a>,
within: &'a dyn Fn(NodeId) -> bool,
// One budget for the whole document, so that thousands of shapes that need a search take
// a bounded time; the shapes after it runs out count as unmeasured.
budget: po::ThicknessBudget,
out: Vec<(NodeId, Option<bool>)>,
}
fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) {
// An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing.
if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) {
return;
}
let clips = n.clips();
for (i, c) in children.iter().enumerate() {
visit(c, clips && i == 0, w);
}
}
// Art on a locked artboard, or outside `within`, is left out before it is measured.
NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => {
match is_hairline_sliver(n, w.width, &mut w.budget) {
Some(false) => {}
found => w.out.push((n.id, found)),
}
}
_ => {}
}
}
let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] };
for l in &d.layers {
visit(l, false, &mut w);
}
let mut found = w.out;
let editable = d.editable();
found.retain(|(id, _)| editable(*id));
let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some());
Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() }
}
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.path.cleanUp";
let stray = switch_or(p, "strayPoints", true, C)?;
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
let found = {
let slivers = switch_or(p, "hairlineSlivers", false, C)?;
let width = sliver_width(p, "sliverWidth", C)?;
let (found, warning) = {
let d = &s.doc()?.doc;
let mut v = vec![];
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
@@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
let editable = d.editable();
v.retain(|id| editable(*id));
v
let mut warning = None;
if slivers {
let found = hairline_slivers(d, width, &|_| true);
let listed: BTreeSet<NodeId> = v.iter().copied().collect();
// A shape another option removes isn't left as it is.
warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count());
v.extend(found.ids.into_iter().filter(|id| !listed.contains(id)));
}
(v, warning)
};
let reply = |removed: usize| match &warning {
Some(w) => json!({ "removed": removed, "warning": w }),
None => json!({ "removed": removed }),
};
if found.is_empty() {
return Ok(json!({ "removed": 0 }));
return Ok(reply(0));
}
s.edit("Clean Up", |d, _| {
let mut gone = Beside::replacing(d, &found);
@@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
gone.finish(d)
})?;
Ok(json!({ "removed": found.len() }))
Ok(reply(found.len()))
}
// ---------- Divide Objects Below ----------
@@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[
"charStyle.setAttrs",
"charStyle.unused",
"color.convert",
"color.format",
"color.gamutCheck",
"color.harmony",
"color.parse",
@@ -541,6 +542,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.object.brushStrokes",
"select.object.clippingMasks",
"select.object.directionHandles",
"select.object.hairlineSlivers",
"select.object.notAlignedToPixelGrid",
"select.object.pointText",
"select.object.slices",
+1 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler Line truncated
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler Line truncated
always,
run
),
+28
View File
@@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning};
use super::wand::{fill_of, stroke_of};
use super::{
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
@@ -205,6 +206,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| p.anchor_count() == 1))),
cmd!(
"select.object.hairlineSlivers",
"Hairline Slivers…",
["Select", "Object"],
None,
"{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}",
has_doc,
select_hairline_slivers
),
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| !p.is_closed()))),
@@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes
/// ([`hairline_slivers`]), inside the isolated group while one is isolated.
fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "select.object.hairlineSlivers";
let width = sliver_width(p, "width", C)?;
let st = s.doc()?;
let (d, iso) = (&st.doc, st.isolation);
let locks = d.locked_artboards();
let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id));
let warning = unmeasured_warning(found.unmeasured.len());
s.select(|_, sel| sel.set(found.ids))?;
let count = s.doc()?.selection.objects.len();
Ok(match warning {
Some(w) => json!({ "count": count, "warning": w }),
None => json!({ "count": count }),
})
}
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
/// does not look at the paths inside it.
+4
View File
@@ -86,6 +86,9 @@ pub struct DocState {
/// Whether Start Global Edit supports the one selected object
/// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable.
pub(crate) global_edit_support: cmd::globaledit::SupportCache,
/// The forms Start Global Edit compared the selected object with
/// ([`cmd::globaledit::FormCache`]). Not saved, not undoable.
pub(crate) global_edit_forms: cmd::globaledit::FormCache,
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
pub(crate) symbol_edit_return: cmd::symboledit::Return,
pub interaction: Option<Interaction>,
@@ -481,6 +484,7 @@ impl DocState {
global_edit: None,
similar_outlines: Default::default(),
global_edit_support: Default::default(),
global_edit_forms: Default::default(),
symbol_edit_return: Default::default(),
interaction: None,
undo_group: None,
+1 -1
View File
@@ -33,7 +33,7 @@ pub use cmd::flare::flare_settings;
pub use cmd::gradient::{GradientEditPaints, StopOwner};
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::{auto_simplify_level, can_outline_stroke};
pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke};
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
+28
View File
@@ -44,6 +44,9 @@
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
//! - `app.activeDocument` with no document open throws `No active document`.
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
//! made; with no such step they change nothing, and with no document open they throw
//! `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
@@ -827,6 +830,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
/// only the steps the run made. With no step to undo or redo they change nothing.
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
let has_step = {
let s = h.session.borrow();
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
};
if has_step {
command(h, id, &json!({}))?;
}
Ok(Data::Undefined)
}
fn app_undo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.undo", false)
}
fn app_redo(h: &Host, _: &[Data]) -> Answer {
app_history(h, "edit.redo", true)
}
fn app_selection(h: &Host, _: &[Data]) -> Answer {
let uid = h.session.borrow().active().map(|st| st.uid);
match uid {
@@ -1746,6 +1771,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
d => vec![d],
};
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
// The ids listed so far; `ids` keeps them in the order they were first listed.
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
// The document is read once for every object: nothing changes it while the list is checked.
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
@@ -2677,6 +2703,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
("redraw", method(l, app_redraw), returns("undefined", &[])),
("undo", method(l, app_undo), returns("undefined", &[])),
("redo", method(l, app_redo), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
("toString", class_text("Application"), returns("string", &[])),
]);
+67
View File
@@ -399,6 +399,73 @@ fn parse_err(s: &mut Session, p: Value) -> String {
s.execute("color.parse", &p).unwrap_err().to_string()
}
/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse`
/// reads every notation but CMYK back to the same color and opacity.
#[test]
fn format_writes_each_notation_and_parse_reads_it_back() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let s = &mut s;
let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| {
let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap();
r["text"].as_str().unwrap().to_string()
};
let blue = json!("#336699");
for (notation, at_half, at_full) in [
("hex", "#336699", "#336699"),
("hexAlpha", "#33669980", "#336699ff"),
("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"),
("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"),
] {
assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}");
assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}");
}
let oklch = fmt(s, blue.clone(), json!(25), "oklch");
assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}");
// The working CMYK numbers through the color settings, as color.convert gives them.
let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap();
let pct: Vec<f64> = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect();
let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]);
assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them");
assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected);
assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values");
assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40");
for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] {
for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] {
let text = fmt(s, color.clone(), opacity.clone(), notation);
let shown = fmt(s, color.clone(), Value::Null, "hex");
let r = s.execute("color.parse", &json!({ "text": text })).unwrap();
assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}");
match notation {
"hex" => assert_eq!(r["opacity"], Value::Null, "{text}"),
"hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"),
_ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"),
}
}
}
}
/// `color.format` refuses a missing or wrong color, opacity or notation.
#[test]
fn format_refuses_bad_params() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string();
let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk";
assert!(err(json!({"color": "#336699"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation));
assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string"));
assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`"));
assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`"));
for opacity in [json!(-1), json!(101), json!("50"), json!(true)] {
assert!(
err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"),
"{opacity}"
);
}
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+37
View File
@@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts
assert!(highlights(&s).is_empty(), "two objects selected");
}
#[test]
fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights};
let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get));
let since = |b: (usize, usize)| {
let n = made();
(n.0 - b.0, n.1 - b.1)
};
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect();
sel(&mut s, &[key]);
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (40, 39), "the first preview measures each object");
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = made();
assert_eq!(highlights(&s).len(), 39);
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
sel(&mut s, &[copies[0]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
sel(&mut s, &[copies[1]]);
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
sel(&mut s, &[copies[2]]);
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
sel(&mut s, &[key]);
let before = made();
let shown = highlights(&s);
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
let moved = node(&s, copies[1]).stroke_path().unwrap();
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
}
#[test]
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
let mut s = session();
+333
View File
@@ -1066,6 +1066,339 @@ fn clean_up_removes_junk() {
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
}
/// A path drawn by `d`, filled black with no stroke.
fn filled(s: &mut Session, d: &str) -> NodeId {
let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap());
fill_only(s, id);
id
}
fn fill_only(s: &mut Session, id: NodeId) {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
Ok(())
})
.unwrap();
}
/// Hairline Slivers' test art: (the slivers, the shapes with a width).
fn sliver_art(s: &mut Session) -> (Vec<NodeId>, Vec<NodeId>) {
// A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide
// and tall. A long one across the page. A compound path of two slivers.
let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z");
let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z");
let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z");
let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, two);
// Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it
// draws a line), an open path, and a compound path of a sliver and a square.
let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z");
let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap());
fill_only(s, dot);
let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into();
Ok(())
})
.unwrap();
let open = filled(s, "M500 10 L540 40 L500.001 10.0015");
let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z");
let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z");
s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap();
let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, mixed);
s.execute("select.none", &json!({})).unwrap();
(vec![triangle, long, two], vec![strip, dot, stroked, open, mixed])
}
#[test]
fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() {
let mut s = session();
let (slivers, kept) = sliver_art(&mut s);
// Off by default.
assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0);
// A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is
// at 0 % opacity paints nothing either.
let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z");
let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z");
s.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() {
f.opacity = 0.0;
}
d.node_mut(clear).unwrap().appearance = a.into();
Ok(())
})
.unwrap();
let kept = [kept, vec![unpainted, clear]].concat();
let undo = s.doc().unwrap().history.undo.len();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left");
for (k, id) in kept.iter().enumerate() {
assert!(d.node(*id).is_some(), "shape {k} with a width went");
}
assert_eq!(r["removed"], slivers.len());
// One undo step brings every sliver back.
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some()));
// A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot.
let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"});
assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1);
assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some());
}
/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or
/// locked slivers.
#[test]
fn select_hairline_slivers_selects_what_clean_up_removes() {
let mut s = session();
let (slivers, _) = sliver_art(&mut s);
let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z");
let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z");
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
d.node_mut(locked).unwrap().locked = true;
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], slivers.len());
let mut selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
selected.sort_unstable();
let mut want = slivers.clone();
want.sort_unstable();
assert_eq!(selected, want);
// Inside an isolated group, only the slivers in it are selected.
let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z");
let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z");
s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
// A sliver in a group is selected as Clean Up finds it.
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1);
assert!(s.doc().unwrap().selection.objects.contains(&inner));
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A template layer that was unlocked afterward.
let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z");
s.edit("t", |d, _| {
let n = d.node_mut(template).unwrap();
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = true;
}
n.locked = false;
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(template).unwrap().is_template());
s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert!(!s.doc().unwrap().selection.objects.contains(&traced));
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some());
}
/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint
/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's
/// clipping path; Clean Up's other options keep the layer's clipping path too.
#[test]
fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() {
let mut s = session();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [rough.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap();
let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z");
let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z");
s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap();
s.execute("livePaint.make", &json!({})).unwrap();
// A group's own 5 pt stroke draws along its member.
let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into();
Ok(())
})
.unwrap();
// A thin part of type's glyph outlines.
let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap();
let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(outlines).unwrap().extras_mut().type_outlines = true;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
// A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects
// removes the clipping path.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z");
let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z");
let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went");
// A clip group whose clipping path is a sliver.
let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z");
let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
// A guide drawn as a sliver, and a sliver with an effect on its stroke.
let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z");
let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind {
*guide = true;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(mask).is_some(), "the clip group's clipping path went");
assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went");
// A layer clipped by a group (as an opened file can have it): its sliver member clips too.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z");
let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [bare.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind {
*clip = true;
let i = children.iter().position(|c| c.id == g).unwrap();
let c = children.remove(i);
children.insert(0, c);
}
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went");
}
/// A sliver on a locked artboard is left alone.
#[test]
fn hairline_slivers_leave_art_on_a_locked_artboard_alone() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.edit("t", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
assert!(s.doc().unwrap().doc.node(sliver).is_some());
}
/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone.
#[test]
fn hairline_slivers_leave_art_at_zero_opacity_alone() {
let mut s = session();
let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(clear).unwrap().opacity = 0.0;
d.node_mut(group).unwrap().opacity = 0.0;
d.node_mut(seen).unwrap().opacity = 0.5;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1);
let d = &s.doc().unwrap().doc;
assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went");
assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed");
}
/// A shape too complex to measure is kept, and both commands say how many there were.
#[test]
fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
// A closed zigzag of more anchors than one shape is measured with.
let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1;
let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect();
let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind {
*path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true));
}
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
assert_eq!(r["removed"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(sliver).is_none() && d.node(huge).is_some());
}
/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the
/// document, the selection and the undo history stay as they were.
#[test]
fn hairline_slivers_refuse_a_width_out_of_range() {
let mut s = session();
sliver_art(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] {
for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] {
let mut p = serde_json::Map::new();
p.insert(key.into(), w.clone());
if cmd == "object.path.cleanUp" {
p.insert("hairlineSlivers".into(), json!(true));
}
let r = s.execute(cmd, &Value::Object(p));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}");
assert!(state(&s) == before, "{cmd} {w} changed the document");
}
}
// Both ends of the range are taken.
for w in [json!(0.001), json!(3), json!("3 pt")] {
assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}");
let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w});
assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}");
}
}
/// A page-sized square under a ring (a compound path with a square hole), nothing selected.
fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) {
let art = rect(s, 0.0, 0.0, 100.0, 100.0);
+31
View File
@@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() {
}
}
/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one
/// undo step. They change nothing past the run's first edit or its last undone one.
#[test]
fn app_undo_and_redo_step_through_the_runs_edits() {
let (mut s, a, b) = doc();
let steps = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\
app.undo(); app.redo();\
i.name = 'first'; i.opacity = 40;\
app.undo(); vc.log([i.name, i.opacity]);\
app.redo(); vc.log(i.opacity);\
app.redo(); vc.log(i.opacity);\
app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\
vc.log(typeof app.undo());\
d.pageItems[1].name = 'kept';",
);
assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]);
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
let st = s.active().unwrap();
let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect();
assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}");
s.execute("edit.undo", &json!({})).unwrap();
let st = s.active().unwrap();
assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run");
let mut s = Session::new();
assert!(failure(&mut s, "app.undo();").contains("No active document"));
assert!(failure(&mut s, "app.redo();").contains("No active document"));
}
/// An opacity a graph mark already has still replaces the opacity another mark of its series left on
/// the graph, as `object.setProps` does.
#[test]
+39
View File
@@ -1248,6 +1248,45 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() {
assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again");
}
/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS
/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each
/// back to the hex color `color.format` gives.
#[test]
fn color_format_writes_every_css_form_through_the_intent() {
let _g = settings();
let old = cms::active_settings();
let mut s = session();
let format = |s: &mut Session, color: &serde_json::Value, notation: &str| {
s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string())
};
s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap();
let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string());
// The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent.
let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name;
s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap();
let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0});
let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8);
let intents_differ =
absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8);
// Collected as results, so that a failure still restores the process-wide settings first.
let mut read_back = vec![];
for notation in ["hex", "rgb", "hsl", "oklch"] {
let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string());
let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string()));
read_back.push((notation, text, hex));
}
cms::set_active(&old).unwrap();
cms::unregister_icc(&icc);
assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}");
assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB");
let hex = read_back[0].1.clone().unwrap();
let [r, g, b] = absolute;
assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB");
for (notation, text, back) in read_back {
assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}");
}
}
/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in
/// `Color Settings.json`.
#[test]
@@ -90,8 +90,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
unloadAction unloadAction=",
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
undo unloadAction unloadAction=",
),
("DocumentPreset.", "prototype"),
(
+5 -1
View File
@@ -314,6 +314,8 @@ impl Interp {
out
}
/// The [`crate::host_ref`] of the object of a host class `id`, its key, class name and handle
/// charged to `r` as the plain data they are before they are copied.
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
self.charge_entries(r, len.saturating_add(2))?;
@@ -526,7 +528,9 @@ impl Interp {
r
}
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
/// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the
/// first is the object `this` stands for, or `undefined` when it is not an object of a host
/// class, charged to the same limits as the arguments.
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
let mut reading = Reading {
limits: match how {
+2
View File
@@ -270,6 +270,8 @@ impl Interp {
Ok(Some(host_ref(&name, &h.handle)))
}
/// The length of the class name and of the handle of the object of a host class `id`, or `None`
/// when it is not one.
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
+34
View File
@@ -874,6 +874,40 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
}
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
/// with the handle `[0]`.
fn with_long_things(r: &mut Realm, len: usize) {
let make: HostFunction = Rc::new(move |a| {
let mut handle = vec![if let Some(Data::Number(n)) = a.get(1) { *n } else { 0.0 }];
handle.resize(len, 0.0);
Ok(host_ref("Thing", &handle))
});
let take: HostFunction = Rc::new(|_| Ok(Data::Undefined));
let members = vec![("make".to_string(), HostMember::Method(make)), ("take".to_string(), HostMember::Method(take))];
let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap();
}
#[test]
fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() {
let mut r = realm(100_000_000);
with_long_things(&mut r, 1024);
// 100 references to an object with a handle of 1,024 numbers are more than 100,000 entries.
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 100_000 });
let probe = "var t = thing.make(1), list = []; for (var i = 0; i < 100; i++) list.push(t); var m = 'none'; \
try { thing.take(list); } catch (e) { m = e.name + '|' + e.message; } m";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
// The object a member is called on counts too.
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 });
let probe = "var m = 'none'; try { thing.make(2).take(); } catch (e) { m = e.name + '|' + e.message; } m";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
// Short handles stay within the limits.
assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true));
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_wait() {
let mut r = realm(1_000_000);
+1 -1
View File
@@ -21,7 +21,7 @@ thread_local! {
/// The contour passes made over an arrangement on this thread, each of which walks all of it.
pub(crate) static CONTOUR_PASSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The sweeps [`normalize_bez`] made on this thread.
static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The input curves [`exact_merge`] tested on this thread.
static EXACT_MERGE_CURVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
+2
View File
@@ -15,6 +15,7 @@ mod offset;
mod pathfinder;
mod planar;
mod sweep_axis;
mod thickness;
mod trap;
pub use boolean::{
@@ -35,6 +36,7 @@ pub use planar::{
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
};
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
/// Errors from fallible operations.
+573
View File
@@ -0,0 +1,573 @@
//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its
//! fill (Clean Up's and Select › Object's Hairline Slivers).
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _};
use vectorcraft_geom::{FillRule, PathData};
use crate::boolean::{eps_for, fill_bezpath, normalize_bez};
/// Most line pieces the outline of one shape is measured with.
pub const MAX_THICKNESS_PIECES: usize = 100_000;
/// Most cells one search for a wide enough spot looks at.
const MAX_CELLS: usize = 500_000;
/// Most distances from a point to a piece of outline one search measures.
const MAX_WORK: usize = 50_000_000;
/// Most distances from a point to a piece of outline the shapes of one document are measured
/// with, all together ([`ThicknessBudget::document`]).
pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000;
/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves.
const FINE_PARTS: f64 = 32.0;
/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`.
const ROUGH_PARTS: f64 = 8.0;
/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than
/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is.
/// A shape within a small fraction of `width` of the limit is taken as thick enough.
///
/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't
/// finite, the fill can't be resolved into outlines (or only so coarsely, for a shape that large,
/// that edges closer than `width` would merge), or measuring it would take more than
/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long.
pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option<bool> {
thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK))
}
/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a
/// point to a piece of outline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ThicknessBudget(usize);
impl ThicknessBudget {
pub fn new(work: usize) -> Self {
Self(work)
}
/// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`].
pub fn document() -> Self {
Self(MAX_DOCUMENT_THICKNESS_WORK)
}
/// The work left.
pub fn left(&self) -> usize {
self.0
}
}
/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs
/// more than is left. The quick checks take nothing from it, so they still settle shapes once it
/// runs out.
pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option<bool> {
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
if !(width.is_finite() && width > 0.0)
|| !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out))
{
return None;
}
// Every segment is at least one piece of outline, so a path of more anchors is too long to
// measure before its outline is built.
if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::<usize>() > MAX_THICKNESS_PIECES {
return None;
}
let mut bp = fill_bezpath(path);
if bp.elements().is_empty() {
return Some(true);
}
// Measured from the corner of its bounds, so that a shape far from the origin measures as it
// does near it.
let corner = bp.bounding_box().origin();
bp.apply_affine(Affine::translate(-corner.to_vec2()));
let b = bp.bounding_box();
let (r, fine) = (width / 2.0, width / FINE_PARTS);
// A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the
// width go on to that measure, which keeps them.
if b.width().min(b.height()) < width - 2.0 * fine {
return Some(true);
}
// Every point of a fill lies within the widest circle's radius r of its outline, and the points
// within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds
// a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around
// any point is measured so: the areas of several subpaths add up to more than their fill where
// they overlap, a path that runs around a spot twice counts its area there twice, and an
// even-odd fill of a path that runs around twice is empty.
if path.subpaths.len() == 1
&& rule == FillRule::NonZero
&& winds_at_most_once(&bp)
&& bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r
{
return Some(false);
}
// The circle lies between any two parallel lines that hold the path's points and handles too,
// which settles a long sliver lying on a slant.
if hull_width(&bp) < width - 2.0 * fine {
return Some(true);
}
// A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's
// outline, so a spot this far from every edge (and from the rough pieces' error) is far enough.
let rough = width / ROUGH_PARTS;
let mut edges = vec![];
if !flatten_into(&bp, rough, &mut edges) {
return None;
}
match search(&edges, b, rule, r + rough, rough, budget) {
Search::Found => return Some(false),
// Resolving the outlines takes time of its own, so it isn't started when what is left of
// the budget cut the rough look short. The rough look can run out where the resolved
// outline is much shorter, so one that ran out of its own share goes on.
Search::TooLong if budget.0 < MAX_WORK => return None,
_ => {}
}
// The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the
// fill are no outline of it. A spot within the fine pieces' error of the radius counts as one.
// The sweep snaps points within its tolerance together, which grows with the shape's size: one
// as coarse as the fine pieces could close up a fill that holds the circle, so it isn't measured.
if eps_for([&bp]).ok()? >= fine {
return None;
}
let contours = normalize_bez(&bp, rule).ok()?;
edges.clear();
for c in contours.contours() {
if !flatten_into(&c.path, fine, &mut edges) {
return None;
}
}
if edges.is_empty() {
return Some(true);
}
match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) {
Search::Found | Search::Unsure => Some(false),
Search::Absent => Some(true),
Search::TooLong => None,
}
}
/// The points and handles of `bp`, in order.
fn control_points(bp: &BezPath) -> Vec<Point> {
bp.elements()
.iter()
.flat_map(|el| match *el {
PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p],
PathEl::QuadTo(a, p) => vec![a, p],
PathEl::CurveTo(a, b, p) => vec![a, b, p],
PathEl::ClosePath => vec![],
})
.collect()
}
/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point
/// that a curve winds around twice crosses it at least four times, so such a curve turns through
/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon
/// that turns through less than 4π winds at most once.
fn winds_at_most_once(bp: &BezPath) -> bool {
let mut pts = control_points(bp);
pts.dedup();
while pts.len() > 1 && pts.first() == pts.last() {
pts.pop();
}
if pts.len() < 3 {
return true;
}
let turned: f64 = pts
.iter()
.zip(pts.iter().cycle().skip(1))
.zip(pts.iter().cycle().skip(2))
.map(|((&a, &b), &c)| {
let (u, v) = (b - a, c - b);
u.cross(v).atan2(u.dot(v)).abs()
})
.sum();
turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9)
}
/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded.
const MAX_HULL: usize = 512;
/// The least distance between two parallel lines that hold every point and handle of `bp` (the
/// width of their convex hull, which holds the curves too).
fn hull_width(bp: &BezPath) -> f64 {
let mut pts = control_points(bp);
pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
pts.dedup();
if pts.len() < 3 {
return 0.0;
}
// Andrew's monotone chain: the lower hull, then the upper.
let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o);
let mut hull: Vec<Point> = Vec::with_capacity(pts.len() + 1);
for pass in [false, true] {
let floor = hull.len();
let ordered: Box<dyn Iterator<Item = &Point>> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) };
for &p in ordered {
while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) {
hull.pop();
}
hull.push(p);
}
hull.pop();
}
if hull.len() < 3 {
return 0.0;
}
if hull.len() > MAX_HULL {
return f64::INFINITY;
}
// For each side, the farthest corner from its line; the least of those is the width.
let mut least = f64::INFINITY;
for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) {
let side = b - a;
let len = side.hypot();
if len > 0.0 {
let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max);
least = least.min(far);
}
}
least
}
/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes
/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`]
/// to keep within `tolerance`.
fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool {
let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| {
if from != to {
edges.push((from, to));
}
};
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
for el in bp.iter() {
if edges.len() > MAX_THICKNESS_PIECES {
return false;
}
match el {
// An outline that doesn't end where it starts is closed with a line, as a fill paints it.
PathEl::MoveTo(p) => {
push(last, start, edges);
(start, last) = (p, p);
}
PathEl::ClosePath => {
push(last, start, edges);
last = start;
}
PathEl::LineTo(p) => {
push(last, p, edges);
last = p;
}
PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => {
let length = match el {
PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p),
_ => last.distance(a) + a.distance(p),
};
if length / most > tolerance {
return false;
}
let mut from = last;
vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| {
if let PathEl::LineTo(to) = piece {
push(from, to, edges);
from = to;
}
});
last = p;
}
}
}
push(last, start, edges);
edges.len() <= MAX_THICKNESS_PIECES
}
/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under
/// `rule`.
fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 {
let mut winding = 0i32;
let mut nearest = f64::INFINITY;
for &(a, b) in edges {
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
winding += if b.y > a.y { 1 } else { -1 };
}
let ab = b - a;
let len2 = ab.hypot2();
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
nearest = nearest.min((p - (a + ab * t)).hypot2());
}
let inside = match rule {
FillRule::NonZero => winding != 0,
FillRule::EvenOdd => winding % 2 != 0,
};
let d = nearest.sqrt();
if inside { d } else { -d }
}
/// A square cell of the search: its center, half its side, the signed distance from its center to
/// the outline, and the most that distance can be anywhere in it.
struct Cell {
c: Point,
h: f64,
d: f64,
most: f64,
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.most.total_cmp(&other.most) == Ordering::Equal
}
}
impl Eq for Cell {}
impl PartialOrd for Cell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Cell {
fn cmp(&self, other: &Self) -> Ordering {
self.most.total_cmp(&other.most)
}
}
/// What [`search`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Search {
/// A point at least the distance asked for from the outline.
Found,
/// No such point.
Absent,
/// None found, but cells smaller than the finest size could still hold one.
Unsure,
/// The search needed more cells or distances than it may take.
TooLong,
}
/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal`
/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest
/// point is split first, until a cell's center is `goal` away or no cell could be. The distance
/// changes no faster than the point moves, so a cell holds no point farther than its center's
/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The
/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`.
fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search {
let mut work = 0usize;
let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work);
budget.0 = budget.0.saturating_sub(work);
found
}
/// [`search`], measuring no more than `limit` distances and counting them in `work`.
fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search {
let side = bounds.width().min(bounds.height());
if side.is_nan() || side <= 0.0 {
return Search::Absent;
}
let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil());
if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 {
return Search::TooLong;
}
let cell = |c: Point, h: f64, work: &mut usize| {
*work += edges.len();
let d = signed_distance(edges, rule, c);
Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 }
};
let mut heap = BinaryHeap::new();
let h = side / 2.0;
for i in 0..cols as usize {
for j in 0..rows as usize {
heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work));
}
}
let (mut made, mut unsure) = (heap.len(), false);
while let Some(next) = heap.pop() {
if next.d >= goal {
return Search::Found;
}
if next.most < goal {
break;
}
if next.h < finest / 2.0 {
unsure = true;
continue;
}
if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit {
return Search::TooLong;
}
let h = next.h / 2.0;
for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] {
let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work);
// A cell that can't hold a point `goal` away is left out.
if part.most >= goal {
heap.push(part);
}
}
made += 4;
}
if unsure { Search::Unsure } else { Search::Absent }
}
#[cfg(test)]
mod tests {
use vectorcraft_geom::{Anchor, SubPath};
use super::*;
fn polygon(points: &[(f64, f64)]) -> SubPath {
SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)
}
fn one(points: &[(f64, f64)]) -> PathData {
PathData::single(polygon(points))
}
fn thin(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(true)
}
fn thick(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(false)
}
#[test]
fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
assert!(thin(&sliver, FillRule::NonZero, 0.085));
// Long and on a slant at the narrowest width, and far from the origin.
assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001));
let (x, y) = (1_000_000.0, 1_000_000.0);
assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001));
}
#[test]
fn a_bent_sliver_is_found_by_measuring_inside_it() {
// Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are
// wide, and only the measure inside finds it thin.
let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
assert!(thin(&v, FillRule::NonZero, 0.085));
}
#[test]
fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() {
// A diagonal strip 100 pt long.
let strip = |w: f64| {
let (dx, dy) = (0.6 * w, -0.8 * w);
one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)])
};
assert!(thick(&strip(0.2), FillRule::NonZero, 0.085));
assert!(thick(&strip(0.2), FillRule::NonZero, 0.18));
assert!(thin(&strip(0.05), FillRule::NonZero, 0.085));
assert!(thin(&strip(0.2), FillRule::NonZero, 0.24));
}
#[test]
fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() {
// Its inscribed circle is 2 across, centered at (1, 1).
let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]);
assert!(thick(&t, FillRule::NonZero, 1.95));
assert!(thin(&t, FillRule::NonZero, 2.3));
}
#[test]
fn a_tiny_round_dot_is_kept() {
let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3));
assert!(thick(&dot, FillRule::NonZero, 0.085));
assert!(thick(&dot, FillRule::NonZero, 0.29));
assert!(thin(&dot, FillRule::NonZero, 0.4));
}
#[test]
fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() {
let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]);
let mut hole = square(1.01, 98.99);
hole.reverse();
assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085));
// Even-odd: an inner square running the same way still cuts a hole.
assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085));
// Nonzero: it doesn't, and the edges inside the fill are no outline of it.
assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085));
}
#[test]
fn overlapping_strips_are_measured_by_their_union() {
// Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of
// each that run inside the other are no more than 0.1 pt apart.
let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]);
let strips = PathData::new(vec![strip(0.0), strip(0.1)]);
assert!(thick(&strips, FillRule::NonZero, 0.15));
assert!(thin(&strips, FillRule::NonZero, 0.35));
}
#[test]
fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() {
assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085));
assert!(thin(&PathData::default(), FillRule::NonZero, 0.085));
}
/// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled
/// without resolving their outlines, so a document of thousands of them is measured quickly.
#[test]
fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() {
let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get());
for k in 0..2000 {
let x = f64::from(k) * 12.0;
assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085));
assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085));
// Long slivers on a slant are settled by the width of their hull.
assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085));
}
assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before);
}
/// The area measure is used only for an outline that runs around once: one that runs around
/// twice counts its area twice.
#[test]
fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() {
let square = |n: usize| {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for _ in 0..n {
for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] {
bp.line_to(p);
}
}
bp.close_path();
bp
};
assert!(winds_at_most_once(&square(1)));
assert!(!winds_at_most_once(&square(2)));
// Measured inside instead, a square run around twice is still as thick as one.
let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
assert!(thick(&twice, FillRule::NonZero, 0.085));
}
/// Shapes that need the search share one budget: once it is spent they can't be measured, and
/// the quick checks still settle the rest.
#[test]
fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() {
let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let mut budget = ThicknessBudget::document();
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true));
assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK);
let mut spent = ThicknessBudget::new(0);
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None);
assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false));
}
/// A shape so long that resolving its outline snaps edges closer than the width together is not
/// measured, while the same height at an ordinary length is.
#[test]
fn a_shape_too_long_to_resolve_at_the_width_cannot_be_measured() {
let rect = |w: f64| one(&[(0.0, 0.0), (w, 0.0), (w, 0.0011), (0.0, 0.0011)]);
assert_eq!(thinner_than(&rect(1e12), FillRule::NonZero, 0.001), None);
assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.001), Some(false));
assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.0012), Some(true));
}
#[test]
fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
for w in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}");
}
let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]);
assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None);
}
}
+5
View File
@@ -65,6 +65,11 @@ impl Known {
self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure)
}
/// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set.
pub fn no_names(&self) -> bool {
self.bound.is_empty() && self.files.is_empty()
}
/// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already
/// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder
/// object only when both sides say so; otherwise it may hold a File object.
+4 -2
View File
@@ -231,7 +231,9 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits:
/// that includes nothing, so a variable a function uses before the global code assigns it holds
/// what it is assigned. `first` holds the scan made with nothing known, which found `known`, and
/// `pre` what came before it. A scan made with what the scans before it found, and that finds
/// nothing more, is the report scan; no other scan is repeated.
/// nothing more, is the report scan; no other scan is repeated. When `known` holds no name, `first`
/// is the report: [`analyze::Known::unsure`] alone comes from `declared`, which the first scan
/// already read.
fn settle<'l>(
first: report::Acc<'l>,
pre: report::Acc<'l>,
@@ -240,7 +242,7 @@ fn settle<'l>(
braced: &[analyze::Braced],
mut known: analyze::Known,
) -> report::Acc<'l> {
if known.len() == 0 {
if known.no_names() {
return first;
}
let entries = pre.limits.entries;
+31 -2
View File
@@ -1935,12 +1935,41 @@ fn the_costliest_inputs_stay_within_five_steps_a_byte() {
format!("\\u0061;function f({}) {{ var {}; }}", names.join(","), names.join(",")),
format!("\\u0061;function f({}) {{}}", vec!["a"; 900].join(",")),
format!("\\u0061;{}", "x=(".repeat(600)),
format!("\\u0061;o[k];{}", "{".repeat(2_000)),
] {
let r = report(&src);
assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len());
}
}
/// The most steps a check of `bytes` without a loader may take. The text is read once for the
/// escapes and once for the names declared, and a scan takes at most three steps a byte. A script
/// whose variables hold nothing the check follows is scanned once: five steps a byte. Any other
/// script is scanned up to five times (the first scan, three more while what its variables hold
/// grows, and the report's): seventeen steps a byte.
fn step_bound(bytes: &[u8]) -> usize {
let limits = Limits::default();
let mut acc = report::Acc::new(&limits);
let (text, _) = decode(bytes);
let (text, braced) = analyze::unescaped(text, &mut acc);
let declared = analyze::declarations(&text, &mut acc);
let known = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc).known;
let scans = if known.no_names() { 1 } else { 5 };
(2 + 3 * scans) * bytes.len() + 16
}
/// A name in brackets that is not one literal (`0[ \| … ]`) gives no variable a value, so the
/// script is scanned once. The bytes are the ones a run of the property below found.
#[test]
fn a_script_that_binds_no_name_is_scanned_once() {
let bytes: &[u8] = b"\x01\x01 \x010 !0!\x01!\x01#\x01#{#{ 0( #0\x01( \x01( {#{ # \x01#0:((0[\t \\| \x1b!!0:|!| 0) ) )] ! \x1b \x1b \x1b \\u\t\x01";
assert_eq!(bytes.len(), 104);
let r = check("a.jsx", bytes, None, &Limits::default());
assert_eq!(r.kind, Kind::Script);
assert_eq!(step_bound(bytes), 5 * bytes.len() + 16);
assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len());
}
#[test]
fn lists_stop_at_their_limits_and_echoes_are_cut() {
let mut s = String::new();
@@ -2339,13 +2368,13 @@ proptest! {
#[test]
fn any_bytes_are_checked_in_linear_work(bytes in prop::collection::vec(any::<u8>(), 0..2_000), jsxbin in any::<bool>()) {
let r = check(if jsxbin { "a.jsxbin" } else { "a.jsx" }, &bytes, None, &Limits::default());
prop_assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len());
prop_assert!(r.steps <= step_bound(&bytes), "{} steps for {} bytes", r.steps, bytes.len());
}
#[test]
fn script_like_text_is_checked_in_linear_work(text in script_text()) {
let r = report(&text);
prop_assert!(r.steps <= 5 * text.len() + 16, "{} steps for {} bytes", r.steps, text.len());
prop_assert!(r.steps <= step_bound(text.as_bytes()), "{} steps for {} bytes", r.steps, text.len());
let limits = Limits::default();
for list in [r.targets.len(), r.directives.len(), r.includes.len(), r.members.len(), r.types.len(), r.menu_strings.len(), r.problems.len()] {
prop_assert!(list <= limits.entries);
+13 -1
View File
@@ -97,6 +97,16 @@ pub(super) fn walk_but<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &m
}
}
/// [`walk_but`] in reverse paint order: the topmost node first.
fn walk_but_topmost_first<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &mut impl FnMut(&'a Node)) {
for n in nodes.iter().rev().filter(|n| n.visible && !skip.contains(&n.id)) {
if let Some(ch) = n.children() {
walk_but_topmost_first(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), skip, f);
}
f(n);
}
}
/// The lines of `lines` (sorted by where they run) within `tol` of `v`.
pub(super) fn lines_near(lines: &[(f64, Point, Kind)], v: f64, tol: f64) -> &[(f64, Point, Kind)] {
within(lines, |l| l.0, v, tol)
@@ -629,7 +639,9 @@ impl Targets {
}
}
let (mut budget, mut segment_budget) = (BUDGET, BUDGET);
walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| {
// Topmost first, so when the budgets run out the objects in front, the newest, keep
// their anchors, edges and centre (#8531).
walk_but_topmost_first(&doc.layers, &exclude.iter().copied().collect(), &mut |n| {
if budget == 0 || n.is_container() || !n.visible {
return;
}
+34
View File
@@ -11,6 +11,40 @@ fn artboard_bleed_is_a_target() {
assert_eq!(t.snap_point(Point::new(512.0, 300.0), 4.0).0.x, 510.0);
}
/// #8531: when a document has more anchors than the targets gather, the object drawn last, in
/// front, still gives its anchors, edges and centre, for a ruler guide, a moved selection and a
/// drawn point, while the anchors stay capped.
#[test]
fn the_topmost_object_keeps_its_targets_past_the_anchor_budget() {
let (d, rect) = doc_with_rect_over_many_anchors();
let t = Targets::collect(&d, &[], None);
let anchors: Vec<Point> = t.points.iter().filter(|(_, k)| *k == Kind::Anchor).map(|(p, _)| *p).collect();
let in_doc: usize = d.layers[0]
.children()
.into_iter()
.flatten()
.map(|n| match &n.kind {
NodeKind::Path { path, .. } => path.anchors().count(),
_ => 0,
})
.sum();
assert!(anchors.len() < in_doc, "the anchors stay capped");
assert!(anchors.contains(&Point::new(400.0, 300.0)), "the rectangle's corner");
assert_eq!(t.snap_guide(false, 301.0, 4.0).0, 300.0, "the bottom edge");
assert_eq!(t.snap_guide(true, 398.0, 4.0).0, 400.0, "the right edge");
let (p, ov) = t.snap_point(Point::new(302.0, 201.0), 4.0);
assert_eq!(p, Point::new(300.0, 200.0));
assert!(matches!(&ov[0], Overlay::Label { text, .. } if text == "center"), "{ov:?}");
// A box moved next to it lines up with its top edge.
let other = Targets::collect(&d, &[rect], None);
let (s, pt) = (Selection::default(), paint());
let moving = Targets::for_move(&cx(&d, &s, &pt), &[]);
assert_eq!(moving.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, -2.0);
assert_eq!(other.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, 0.0, "without the rectangle, nothing near");
let drawn = Targets::for_drawing(&d, &[], None, None);
assert_eq!(drawn.snap_point(Point::new(450.0, 298.0), 4.0).0.y, 300.0);
}
#[test]
fn snaps_to_anchor_and_alignment() {
let (d, _) = doc_with_rect();
+15
View File
@@ -442,6 +442,21 @@ pub(crate) mod testutil {
(d, id)
}
/// #8531: 21 polygons of 1000 sides at (40, 30)–(80, 70), 21,000 anchors (more than the
/// snap targets gather), drawn first, and over them a rectangle (200, 100)–(400, 300): the
/// document and the rectangle.
pub fn doc_with_rect_over_many_anchors() -> (Document, NodeId) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
for i in 0..21 {
let id = d.alloc_id();
d.insert(Some(l), i, Node::path(id, shapes::polygon(Point::new(60.0, 50.0), 20.0, 1000, 0.0), Appearance::default_art())).unwrap();
}
let id = d.alloc_id();
d.insert(Some(l), 21, Node::path(id, shapes::rectangle(Rect::new(200.0, 100.0, 400.0, 300.0)), Appearance::default_art())).unwrap();
(d, id)
}
/// A live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point
/// (Attributes › Show Center) is at (150, 150), and a press in the middle of it hits no art.
pub fn doc_with_live_rect() -> (Document, NodeId) {
+15
View File
@@ -108,6 +108,21 @@ fn a_new_guide_snaps_to_the_art_and_the_artboard() {
assert_eq!(drag(true, 320.0), (320.0, None), "nothing within reach");
}
/// #8531: in a document with more anchors than the snap targets gather, a guide dragged out of
/// the top ruler still lands on the edge of the rectangle drawn last, over all of them.
#[test]
fn a_new_guide_snaps_to_the_newest_object_over_many_anchors() {
let (d, _) = doc_with_rect_over_many_anchors();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let m = Mods::default();
let mut g = NewGuide::new(&c, false, None);
assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 300.0, -5.0, m), false), vec![], "still over the ruler");
let a = g.pointer(&c, &ev(PointerKind::Drag, 300.0, 301.0, m), true);
assert_eq!(a.last(), Some(&Action::Preview("guide.add".into(), json!({"vertical": false, "pos": 300.0}))), "onto the bottom edge: {a:?}");
assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 300.0, 301.0, m), true), vec![Action::Commit]);
}
/// Preferences › Smart Guides (#394) reach a guide dragged out of a ruler: Snapping
/// Tolerance sets how far a target pulls it, Anchor/Path Labels and Measurement Labels what
/// shows by it.
+22 -9
View File
@@ -120,9 +120,11 @@ pub(crate) struct CanvasDrops<'a> {
kind: BodyKind,
/// The uid of the document the canvas shows.
document: u64,
/// The revert count of the document the canvas shows: an appearance dragged from contents File › Revert replaced is
/// refused.
/// The revert count of the document the canvas shows: an appearance, graphic style or brush dragged from contents
/// File › Revert replaced is refused.
reverts: u64,
/// `(uid, reverts)` of every open document: a symbol dragged from contents File › Revert replaced is refused.
contents: Vec<(u64, u64)>,
/// `(uid, revision)` of every open document: carried art whose source is not listed unchanged is refused.
sources: Vec<(u64, u64)>,
/// Whether the art being carried is taken though its source's revision moved: its move was given up and the source
@@ -176,12 +178,17 @@ impl Component for CanvasDrops<'_> {
let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p {
PanelDrag::Art { .. } => None,
PanelDrag::Appearance { .. } if p.appearance_for(self.document, self.reverts).is_none() => None,
_ if p.stale_rows(Some((self.document, self.reverts))) => None,
_ => Some(Payload::Panel(p.clone())),
});
let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone())));
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
let here = (self.document, self.reverts);
let style = Target::new(rect, view, covered, |d: &StyleDrag| ((d.document, d.reverts) == here).then(|| Payload::Style(d.clone())));
// A symbol of any open document's current contents.
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| {
self.contents.contains(&(d.grabbed.doc, d.grabbed.reverts)).then(|| Payload::Symbol(d.grabbed.clone()))
});
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| {
(d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone()))
((d.grabbed.doc, d.grabbed.reverts) == here).then(|| Payload::Brush(d.grabbed.clone()))
});
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
let panel = cx.drop_target::<PanelDrag, _>(&panel);
@@ -222,6 +229,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi
BodyKind::Pane => pane_view(app, win, rect),
};
let (Some(view), Some((document, reverts))) = (view, app.session.documents().get(win.0).map(|d| (d.uid, d.reverts))) else { return };
let contents = app.session.documents().iter().map(|d| (d.uid, d.reverts)).collect();
let sources = app.session.documents().iter().map(|d| (d.uid, d.revision)).chain(app.canvas.panes.released_from).collect();
// A tab rest leaves the art to the document it showed while that is the current one: any canvas or pane takes it
// then, and nothing once that document was closed or left by other means.
@@ -234,7 +242,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi
let ctx = ui.ctx().clone();
let covered = |at: Pos2| crate::panel_docking::os_window_at(app, &ctx, at);
let files = (CanvasFiles::new(app, rect, &view), &files_out);
let drops = CanvasDrops { common: Common::new(), view, kind, document, reverts, sources, given_up, covered: &covered, out: &out, files };
let drops =
CanvasDrops { common: Common::new(), view, kind, document, reverts, contents, sources, given_up, covered: &covered, out: &out, files };
drops.id_salt(("canvas-drops", win)).show_at(ui, rect);
if let Some(files) = files_out.take() {
crate::place::canvas_drop(app, ui.ctx(), files);
@@ -330,6 +339,8 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
)
}
}
// A symbol of contents File › Revert replaced places nothing.
Payload::Symbol(key) if !app.session.documents().iter().any(|d| (d.uid, d.reverts) == (key.doc, key.reverts)) => Ok(()),
Payload::Symbol(key) => run(app, "symbol.placeFromDocument", json!({"sourceDocument": key.doc, "name": key.name, "x": at.x, "y": at.y})),
Payload::Library(key) if key.folder => Ok(()),
Payload::Library(key) => match library_panel::parse(&key.panel) {
@@ -346,7 +357,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => {
run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]}))
}
Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() {
Payload::Brush(key) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (key.doc, key.reverts)) => match hit() {
None if brush_has_art(app, key) && no_art_at(app, at, zoom) => {
run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y}))
}
@@ -357,12 +368,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
}
},
Payload::Brush(_) => Ok(()),
Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => {
Payload::Style(style) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (style.document, style.reverts)) => {
let Some(hit) = hit() else { return Ok(()) };
let top = top_object(app, &hit)?;
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
// Swatch rows of contents File › Revert replaced apply and place nothing.
Payload::Panel(drag @ PanelDrag::Paint { .. }) if drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) => Ok(()),
// A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile.
Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. })
if hit().is_none() && no_art_at(app, at, zoom) =>
@@ -385,7 +398,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
{
return Err(tl!("A linked color swatch can only be applied in its own document.").into());
}
let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) };
let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+94 -8
View File
@@ -68,7 +68,7 @@ fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() {
let before = fill(&app);
let history = undo_len(&app);
let at = Point::new(250.0, 70.0);
let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() });
let payload = Payload::Style(StyleDrag { document, reverts: 0, name: "Shared name".into() });
for operation in [DropOperation::Move, DropOperation::Copy] {
drop_at(&mut app, payload.clone(), at, operation).unwrap();
assert_eq!(fill(&app), before);
@@ -135,7 +135,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays");
let st = app.session.active().unwrap();
let name = st.doc.graphic_styles[2].name.clone();
let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() });
let style = Payload::Style(StyleDrag { document: st.uid, reverts: st.reverts, name: name.clone() });
drop_at(&mut app, style.clone(), on_b, Move).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id));
@@ -165,7 +165,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap());
let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone());
let uid = app.session.active().unwrap().uid;
let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, name: name.into(), group: false });
let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, reverts: 0, name: name.into(), group: false });
let library = |kind: &str, id: &str, name: &str| {
Payload::Library(LibraryKey { panel: library_panel::panel_id(kind, id), name: name.into(), folder: false })
};
@@ -200,7 +200,7 @@ fn a_drop_runs_the_effect_of_its_payload() {
drop_at(&mut app, library(SymbolLibraries::KIND, "basic-shapes", "Star"), on_b, Move).unwrap();
assert_eq!(undo_len(&app), n + 1, "a library symbol is added and placed in one step");
symbol_at(&app, on_b);
drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, name: "Star".into() }), empty, Move).unwrap();
drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, reverts: 0, name: "Star".into() }), empty, Move).unwrap();
symbol_at(&app, empty);
}
@@ -215,8 +215,13 @@ fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() {
app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap();
let uid = app.session.active().unwrap().uid;
let n = undo_len(&app);
drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move)
.unwrap();
drop_at(
&mut app,
Payload::Brush(BrushKey { doc: uid, reverts: 0, name: "Arrow".into(), group: false }),
Point::new(300.0, 240.0),
DropOperation::Move,
)
.unwrap();
assert_eq!(undo_len(&app), n, "{}", app.ui.status);
}
@@ -235,6 +240,7 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() {
let swatch = |name: &str, paint: Paint| {
let rows = SwatchRows {
document,
reverts: 0,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -288,7 +294,7 @@ fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() {
let before = brush_of(&app);
assert!(before.is_none());
let history = undo_len(&app);
let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false });
let payload = Payload::Brush(BrushKey { doc: document, reverts: 0, name: "Shared Brush".into(), group: false });
drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap();
assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone");
drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap();
@@ -308,7 +314,7 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let key = |doc| Payload::Symbol(SymbolKey { doc, name: "Leaf".into() });
let key = |doc| Payload::Symbol(SymbolKey { doc, reverts: 0, name: "Leaf".into() });
let at = Point::new(250.0, 180.0);
let n = undo_len(&app);
drop_at(&mut app, key(source), at, DropOperation::Move).unwrap();
@@ -338,6 +344,7 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows {
document: source.uid,
reverts: source.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -734,3 +741,82 @@ fn an_appearance_drop_after_file_revert_leaves_the_restored_object_unchanged() {
panel.release();
assert_eq!(fill(&panel.app()), red, "a drag started after the revert copies the appearance");
}
/// A graphic style, brush or symbol held across File › Revert, released on art on the canvas, makes no edit to the
/// restored contents, both where the canvas takes the drop and where the drop is applied. The same drag started after
/// the revert still applies or places it.
#[test]
fn a_style_brush_or_symbol_held_across_file_revert_is_not_dropped_on_the_canvas() {
use crate::tests::panel_harness::Panel;
use craft::ui::runtime::drag;
fn beside_canvas(app: &mut VectorcraftApp, ui: &mut egui::Ui, panel: fn(&mut VectorcraftApp, &mut egui::Ui)) {
app.sync_views();
egui::Panel::top("source panel").exact_size(220.0).show(ui, |ui| panel(app, ui));
canvas::show(app, ui);
}
fn styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::graphic_styles::show);
}
fn brushes(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::brushes::show);
}
fn symbols(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
beside_canvas(app, ui, crate::panels::symbols::show);
}
type Show = fn(&mut VectorcraftApp, &mut egui::Ui);
let panels: [(&str, Show); 3] = [("style", styles), ("brush", brushes), ("symbol", symbols)];
for (kind, show) in panels {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap();
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
match kind {
"style" => app.run("graphicStyle.new", json!({"name": "Held"})).map(drop),
"brush" => app
.run("brush.new", json!({"name": "Held", "type": "art"}))
.and_then(|_| app.run("brush.setCurrent", json!({"name": null})).map(drop)),
_ => app.run("symbol.new", json!({"name": "Held"})).map(drop),
}
.unwrap();
app.run("path.create", json!({"anchors": [{"x": 200, "y": 150}, {"x": 380, "y": 150}]})).unwrap();
app.run("select.none", json!({})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("canvas-panel-item-drop-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.ellipse", json!({"x": 20, "y": 250, "width": 20, "height": 20})).unwrap();
app.run("select.none", json!({})).unwrap();
let mut panel = Panel::new(app, show);
let hold = |panel: &mut Panel| {
let from = panel.rect("Held").center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(290.0, 150.0));
panel.drag_hold_between(from, to);
};
hold(&mut panel);
assert!(drag::mark(panel.ctx()).is_some(), "{kind}: the canvas takes it from the current contents");
let opening = panel.app().session.active().map(|st| (st.uid, st.reverts)).unwrap();
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
panel.frame();
assert_eq!(panel.app().session.active().map(|st| (st.uid, st.reverts)), Some((opening.0, opening.1 + 1)));
let history = undo_len(&panel.app());
assert!(drag::mark(panel.ctx()).is_none(), "{kind}: the canvas refuses it once the contents it came from are gone");
panel.release();
assert_eq!(undo_len(&panel.app()), history, "{kind}: the stale drop makes no edit");
let stale = match kind {
"style" => Payload::Style(StyleDrag { document: opening.0, reverts: opening.1, name: "Held".into() }),
"brush" => Payload::Brush(BrushKey { doc: opening.0, reverts: opening.1, name: "Held".into(), group: false }),
_ => Payload::Symbol(SymbolKey { doc: opening.0, reverts: opening.1, name: "Held".into() }),
};
drop_at(&mut panel.app(), stale, Point::new(290.0, 150.0), DropOperation::Move).unwrap();
assert_eq!(undo_len(&panel.app()), history, "{kind}: a stale payload that reaches the drop is not applied");
hold(&mut panel);
panel.release();
assert_eq!(undo_len(&panel.app()), history + 1, "{kind}: a drag started after the revert is still dropped");
}
}
+1 -1
View File
@@ -62,7 +62,7 @@ pub(crate) fn units() -> &'static [UnitKind] {
}
/// Lengths stored in points and shown in `unit`, a bare number read as Numbers Without Units Are Points says.
fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits {
pub(crate) fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits {
crate::fields::bare_points(
LengthUnits::new(UnitKind::Points, unit_kind(unit), PIXELS_PER_INCH),
app.session.prefs.numbers_without_units_are_points,
+36 -1
View File
@@ -59,6 +59,9 @@ struct Open {
struct Setting {
cmyk: bool,
units: LengthUnits,
/// Hairline Slivers' widths: the stroke unit (Preferences › Units › Stroke), or points when
/// that unit's field rounds the narrowest width to 0.
sliver_units: LengthUnits,
}
impl Setting {
@@ -67,8 +70,23 @@ impl Setting {
cmyk: app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk),
// PLAN: assumed `canvas::rulers::general_lengths(&VectorcraftApp) -> LengthUnits` (cv.B5)
units: crate::canvas::rulers::general_lengths(app),
sliver_units: crate::canvas::rulers::lengths(app, sliver_unit(app.session.stroke_unit())),
}
}
/// The length units of `command`'s distance rows.
fn units_for(self, command: &str) -> LengthUnits {
match command {
"object.path.cleanUp" | "select.object.hairlineSlivers" => self.sliver_units,
_ => self.units,
}
}
}
/// The unit Hairline Slivers' widths show in for the stroke unit `stroke`: `stroke`, or points
/// when `stroke` rounds the narrowest width to 0.
fn sliver_unit(stroke: vectorcraft_doc::Unit) -> vectorcraft_doc::Unit {
if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke }
}
/// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the
@@ -283,7 +301,7 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option<Para
param = param.bounds(Some(*range.start()), Some(*range.end()));
}
if lengths(command).contains(&key) {
param = param.length(setting.units);
param = param.length(setting.units_for(command));
if let Some(range) = length_range(command, key) {
param = param.bounds(Some(*range.start()), Some(*range.end()));
}
@@ -399,6 +417,8 @@ fn lengths(command: &str) -> &'static [&'static str] {
crate::addons::cutting::BRIDGES => &["width"],
"object.textWrap.options" => &["offset"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"],
"object.path.cleanUp" => &["sliverWidth"],
"select.object.hairlineSlivers" => &["width"],
_ => &[],
}
}
@@ -413,6 +433,7 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option<std::ops::RangeIn
(crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE, "offset") => {
Some(0.0..=vectorcraft_engine::MAX_COORD)
}
("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE),
_ => None,
}
}
@@ -446,6 +467,7 @@ fn order(command: &str) -> &'static [&'static str] {
crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"],
crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"],
"object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"],
_ => &[],
}
}
@@ -1157,4 +1179,17 @@ mod tests {
answer_ok(&mut app);
assert_eq!(fold_angle(&mut app, a), Some(-180.0));
}
/// Hairline Slivers' widths show in the stroke unit, or in points when that unit rounds the
/// narrowest width (0.001 pt) to 0.
#[test]
fn sliver_widths_show_in_the_stroke_unit_unless_it_rounds_them_to_zero() {
use vectorcraft_doc::Unit;
assert_eq!(sliver_unit(Unit::Points), Unit::Points);
assert_eq!(sliver_unit(Unit::Millimeters), Unit::Millimeters);
assert_eq!(sliver_unit(Unit::Inches), Unit::Points);
assert!(lengths("object.path.cleanUp").contains(&"sliverWidth"));
assert!(lengths("select.object.hairlineSlivers").contains(&"width"));
assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE));
}
}
+5 -3
View File
@@ -302,10 +302,11 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc<Menus>, legacy: bool) -
});
return vec![row(ParamKind::choice(entries.collect(), None))];
}
// Only the colour preview can keep transparency.
// Only the colour preview can keep transparency. The options stand with no caption over them; the option's label
// names the group for assistive technology.
if f.id == "eps" && o.name == "transparentPreview" {
let kind = ParamKind::radio(vec![("true".into(), tl!("Transparent").into()), ("false".into(), tl!("Opaque").into())], None);
return vec![Param::new(o.name, "", kind).enabled_when("previewFormat", "tiffColor")];
return vec![Param::new(o.name, label.clone(), kind).stacked_options().enabled_when("previewFormat", "tiffColor")];
}
// Type is written as glyph outlines, which need no fonts: the row is on, and never enabled.
if f.id == "eps" && o.name == "embedFonts" {
@@ -320,7 +321,8 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc<Menus>, legacy: bool) -
let mut rows = vec![check];
if matches!(o.name, "separateArtboards" | "useArtboards") {
let all = ParamKind::radio(vec![("true".into(), tl!("All").into()), ("false".into(), tl!("Range:").into())], None);
rows.push(Param::new("all", "", all).enabled_when(o.name, true));
// Right under the check box, with no caption over the options.
rows.push(Param::new("all", "", all).stacked_options().enabled_when(o.name, true));
rows.push(Param::new("range", "", ParamKind::text("")).hint("1-3, 5").enabled_when("all", "false"));
}
rows
@@ -513,6 +513,60 @@ fn eps_save_transparency_follows_the_color_preview() {
assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true));
}
/// The open dialog's labelled controls with their bounds, as a screen reader is told them, after a few frames of a
/// 1440x900 window.
fn labelled_controls(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
let ctx = app.ui_ctx.clone().unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
let mut nodes = Vec::new();
for _ in 0..4 {
let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() };
nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |u| u.nodes);
}
nodes
.iter()
.filter_map(|(_, node)| {
let b = node.bounds()?;
Some((node.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))))
})
.collect()
}
/// The bounds of the control labelled `label` in `controls`, with or without a final colon.
fn control(controls: &[(String, egui::Rect)], label: &str) -> egui::Rect {
let bare = |l: &str| l.trim_end_matches(':').to_string();
controls
.iter()
.find(|(l, _)| bare(l) == bare(label))
.map(|(_, r)| *r)
.unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::<Vec<_>>()))
}
/// The All and Range radios stand right under the artboard check box, and EPS's Transparent and Opaque radios right
/// under the Preview menu, with no empty caption over them: an empty caption leaves a band about a row tall.
#[test]
fn save_options_radios_have_no_empty_caption_over_them() {
for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] {
let (mut app, _, _) = desktop(picked);
save_as(&mut app, "file.saveAs");
let controls = labelled_controls(&mut app);
let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:"));
assert!(all.top() - check.bottom() <= check.height() / 2.0, "{picked}: All at {all:?}, the check box at {check:?}");
assert!(range.top() - all.bottom() <= all.height() / 2.0, "{picked}: Range at {range:?}, All at {all:?}");
if picked == "art.eps" {
let transparent = control(&controls, "Transparent");
// The Preview menu: the nearest control so named above the radios (the window has other Preview controls).
let preview = controls
.iter()
.filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top())
.map(|(_, r)| *r)
.max_by(|a, b| a.bottom().total_cmp(&b.bottom()))
.expect("the Preview menu above Transparent");
assert!(transparent.top() - preview.bottom() <= check.height() / 2.0, "Transparent at {transparent:?}, Preview at {preview:?}");
}
}
}
#[test]
fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() {
let (mut app, written, _) = desktop("original.vectorcraft");
+1 -1
View File
@@ -93,7 +93,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
#[cfg(test)]
use slots::RECENT_FONT_IDS;
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
pub(crate) use state::{command_shortcuts, why_off};
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
pub(crate) use submenus::PATH_EFFECTS;
pub use tree::{Listed, menu_tree, menu_tree_named};
pub use ui_commands::UI_COMMANDS;
+67 -15
View File
@@ -18,7 +18,7 @@ use craft::ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use super::labels::holds_plugin_commands;
use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off};
use super::{Listed, PLACEHOLDER, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state_with, why_off};
use crate::i18n::LangExt as _;
use crate::{UiState, VectorcraftApp};
@@ -37,6 +37,12 @@ const TODO_TOOLTIP: &str = "Coming soon — tracked in the parity plan";
pub(crate) struct Menus {
key: Option<u64>,
target: Option<Target>,
/// 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>,
/// How many times [`refresh`] built the model.
#[cfg(test)]
pub(crate) rebuilds: 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.
@@ -79,8 +85,9 @@ pub(crate) fn translate_label(english: &'static str) -> String {
/// What the menus' rows depend on, cheaply (no allocation): commands run, the active document,
/// its revision (edits, selection and view changes), history and clipboard, the filter plug-in that ran last, the language,
/// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts
/// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or
/// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an
/// until the installed ones are scanned, then all of them, #5483). `input`, the pass of the last frame with a pointer
/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash
/// doesn't list (panels shown, a tool picked). While an
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
/// the hash changes as the interaction begins and as it ends.
@@ -122,19 +129,34 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
/// when the rows' state ([`state_key`]) or the shell's target changed.
pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) {
let target = Target::of_shell(&WindowHost::of(ctx).shell());
let key = state_key(app, pressed_pass(ctx));
let press = last_press(app, ctx);
let key = state_key(app, press);
if app.menus.key == Some(key) && app.menus.target == Some(target) {
return;
}
rebuild(app, target);
#[cfg(test)]
{
app.menus.rebuilds += 1;
}
app.menus.key = Some(key);
app.menus.target = Some(target);
}
/// The frame's pass number when it has a click or a key press: the `input` of [`state_key`].
pub(crate) fn pressed_pass(ctx: &egui::Context) -> Option<u64> {
let pressed = ctx
.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { pressed: true, .. })));
/// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read
/// last included: the `input` of [`state_key`]. It stays the same over the frames after that one, so each of them
/// changes the key once.
pub(crate) fn last_press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option<u64> {
if let Some(pass) = pressed_pass(ctx) {
app.menus.pressed = Some(pass);
}
app.menus.pressed
}
/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) or a key
/// pressed.
fn pressed_pass(ctx: &egui::Context) -> Option<u64> {
let pressed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { pressed: true, .. })));
pressed.then(|| ctx.cumulative_pass_nr())
}
@@ -424,7 +446,9 @@ fn linked_defaults(command: &CommandRef) -> Option<Vec<Binding>> {
/// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title
/// where the app shows another.
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState {
let (enabled, checked) = shown_state(app, crate::keymap::state_id(command), &command.params).unwrap_or((false, None));
let state_id = crate::keymap::state_id(command);
let why = why_off(app, state_id);
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None));
let mut state = CommandState::new().enabled(enabled);
if let Some(on) = checked {
state = state.checked(on);
@@ -434,7 +458,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
state = state.title(shown.clone());
}
if !enabled {
state = state.hint(off_reason(app, command, &shown));
state = state.hint(off_reason_with(app, command, &shown, why));
}
state
}
@@ -442,9 +466,13 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
/// What the dimmed row `command`, named `label`, says in the interface language: the engine's reason, the panels' in
/// Presentation Mode, else that the command is not available right now.
pub(crate) fn off_reason(app: &VectorcraftApp, command: &CommandRef, label: &str) -> String {
why_off(app, crate::keymap::state_id(command))
.flatten()
.or_else(|| crate::palette::refusal(app, command).filter(|_| command.id == "window.panel"))
off_reason_with(app, command, label, why_off(app, crate::keymap::state_id(command)))
}
/// [`off_reason`] from `why`, what [`why_off`] answered for the command's state id.
fn off_reason_with(app: &VectorcraftApp, command: &CommandRef, label: &str, why: Option<Option<String>>) -> String {
why.flatten()
.or_else(|| if command.id == "window.panel" { crate::palette::refusal(app, command) } else { None })
.map_or_else(|| crate::i18n::msg(&format!("command `{label}` is not available right now")), |why| crate::i18n::msg(&why))
}
@@ -520,7 +548,8 @@ impl Build<'_> {
return Some(item);
}
let (id, params) = (command.id.as_str(), &command.params);
let (enabled, checked) = shown_state(self.app, id, params)?;
let why = why_off(self.app, id);
let (enabled, checked) = shown_state_with(self.app, id, params, &why)?;
let title = self.item_title(id, params, &item.label);
let mut state = CommandState::new().enabled(enabled).title(title.clone());
if let Some(on) = checked {
@@ -532,7 +561,10 @@ impl Build<'_> {
} else if enabled {
None
} else {
Some(off_reason(self.app, &command, &title))
// The reason reads the check of the command's state id, which is `id` but for the framework's own rows.
let state_id = crate::keymap::state_id(&command);
let why = if state_id == id { why } else { why_off(self.app, state_id) };
Some(off_reason_with(self.app, &command, &title, why))
};
if let Some(tip) = tip {
state = state.hint(tip.clone());
@@ -625,4 +657,24 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new("edit.undo")).is_some_and(CommandState::is_enabled), "the states follow the edits");
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
}
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
#[test]
fn a_rebuild_checks_each_dimmed_row_once() {
let (mut app, ctx) = app_with_document();
// `object.group` is a row of the Object menu; `appearance.addFill` is a catalog row only, dimmed with no subject.
let ids = ["object.group", "appearance.addFill"];
for id in ids {
assert!(!app.menus.states.get(&CommandRef::new(id)).is_some_and(CommandState::is_enabled), "{id} is dimmed");
}
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
app.run("select.none", json!({})).unwrap();
super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
refresh(&mut app, &ctx);
let asked = super::super::state::WHY_OFF_ASKED.take();
for id in ids {
assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}");
assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed");
}
}
}
+5 -4
View File
@@ -6,7 +6,7 @@ use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac,
use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder};
use crate::VectorcraftApp;
use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label};
use crate::menus::model::{APP_NAME, item_title, last_press, recording_shortcut, refresh, state_key, translate_label};
use crate::menus::{command_shortcuts, item_shortcut_in, unbound};
/// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its
@@ -40,13 +40,14 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
}
/// Once per frame, after the UI: bring the native menu up to date. Frames with input read the
/// menus again, as input may change state the key doesn't list.
/// Once per frame, after the UI: bring the native menu up to date. A frame with a click or a key
/// press reads the menus again, as input may change state the key doesn't list.
pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.services.native_menu.is_none() {
return;
}
let state = state_key(app, pressed_pass(ctx));
let press = last_press(app, ctx);
let state = state_key(app, press);
let keys = |chord: &_| holder(ctx, chord);
let options = options().keys(&keys);
// Out of the app while the layout reads it.
+15 -1
View File
@@ -173,7 +173,13 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
/// ([`east_asian_hidden`]).
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
let en = enabled(app, id)
shown_state_with(app, id, p, &why_off(app, id))
}
/// [`shown_state`] from `why`, what [`why_off`] answered for `id`: a caller that also writes the reason a dimmed row
/// gives runs the command's check once.
pub(crate) fn shown_state_with(app: &VectorcraftApp, id: &str, p: &Value, why: &Option<Option<String>>) -> Option<(bool, Option<bool>)> {
let en = why.is_none()
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
@@ -252,11 +258,19 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
why_off(app, id).is_none()
}
#[cfg(test)]
thread_local! {
/// The ids [`why_off`] was asked about on this thread, in order.
pub(crate) static WHY_OFF_ASKED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Why command `id` can't run now ([`enabled`]): `None` while it can, else `Some` with the
/// engine's reason when the engine's check of an engine command fails, and with the reason of
/// [`crate::panels::align::why_off`] for an Align panel button. The engine's check runs at most
/// once.
pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option<Option<String>> {
#[cfg(test)]
WHY_OFF_ASKED.with_borrow_mut(|asked| asked.push(id.to_string()));
if waits_for_ime(app, id) {
return Some(None);
}
+23
View File
@@ -164,6 +164,29 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() {
assert_eq!(menu.toggled("Pixel Snapping Options…"), None);
}
/// A key press builds the menus' states again once: the frames after it, with no press, keep them.
#[test]
fn a_key_press_rebuilds_the_menus_once() {
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..3 {
app_frame(&mut app, &ctx, vec![]);
}
let before = app.menus.rebuilds;
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.menus.rebuilds, before, "idle frames keep the menus");
// F20 runs no command and changes nothing the menus show.
let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
app_frame(&mut app, &ctx, vec![press(true), press(false)]);
for _ in 0..4 {
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.menus.rebuilds, before + 1);
}
#[test]
fn help_f1_opens_discover_without_a_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
+12 -1
View File
@@ -299,7 +299,17 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
c("Divide Objects Below", "object.path.divideObjectsBelow"),
c("Split Into Grid…", "object.path.splitIntoGrid"),
Sep,
cp("Clean Up…", "object.path.cleanUp", json!({"strayPoints": true, "unpaintedObjects": true, "emptyTextPaths": true})),
cp(
"Clean Up…",
"object.path.cleanUp",
json!({
"strayPoints": true,
"unpaintedObjects": true,
"emptyTextPaths": true,
"hairlineSlivers": false,
"sliverWidth": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH
}),
),
],
),
sub("Shape", vec![c("Convert to Shape", "object.shape.convertToShape"), c("Expand Shape", "object.expandShape")]),
@@ -580,6 +590,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
c("Clipping Masks", "select.object.clippingMasks"),
c("Slices", "select.object.slices"),
c("Stray Points", "select.object.strayPoints"),
cp("Hairline Slivers…", "select.object.hairlineSlivers", json!({"width": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH})),
c("Open Paths", "select.object.openPaths"),
c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"),
Sep,
+15 -2
View File
@@ -46,6 +46,8 @@ pub enum PanelDrag {
pub struct SwatchRows {
/// The document whose rows the drag started on.
pub document: u64,
/// The document's revert count: rows held across File › Revert name swatches of contents that are gone.
pub reverts: u64,
pub grabbed: String,
pub names: Vec<String>,
/// The names are colour groups.
@@ -93,13 +95,24 @@ impl PanelDrag {
}
}
/// Whether the drag carries swatch rows of `current` (`(uid, reverts)` of the active document) from before
/// File › Revert: their names may now stand for other swatches, so a drop of them applies nothing.
pub(crate) fn stale_rows(&self, current: Option<(u64, u64)>) -> bool {
matches!(self, Self::Paint { rows: Some(r), .. } if current.is_some_and(|(uid, reverts)| uid == r.document && reverts != r.reverts))
}
/// A named process swatch follows the source drawing's swatch. In another drawing its
/// captured process color applies without using a same-name swatch there.
pub(crate) fn paint_drop_params(&self, destination: Option<u64>) -> Option<Value> {
/// captured process color applies without using a same-name swatch there. Swatch rows of the destination's
/// contents from before File › Revert apply nothing.
pub(crate) fn paint_drop_params(&self, destination: Option<(u64, u64)>) -> Option<Value> {
if self.stale_rows(destination) {
return None;
}
let Self::Paint { paint, params, rows, .. } = self else { return None };
if params.is_null() {
return None;
}
let destination = destination.map(|d| d.0);
if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color)
&& destination.is_some_and(|uid| uid != rows.document)
&& let Some(color) = paint.color()
+52 -2
View File
@@ -754,12 +754,13 @@ pub(crate) fn proxy(app: &mut VectorcraftApp, ui: &mut Ui) {
};
let wells = [well(tl!("Fill"), &fill, mixed.0), well(tl!("Stroke"), &stroke, mixed.1).ring(true)];
let active = if app.session.fill_active { Well::Primary } else { Well::Secondary };
let current = app.session.active().map(|st| (st.uid, st.reverts));
let out = SwatchPair::new(tl!("Fill and Stroke"), wells, Bind::given(active))
.swap_button(tl!("Swap Fill and Stroke"))
.default_button(tl!("Default Fill and Stroke"))
.popover(false)
.drags([Some(PanelDrag::paint(fill)), Some(PanelDrag::paint(stroke))])
.accepts(move |well, drag| takes_drop(mixed, well, drag))
.accepts(move |well, drag| takes_drop(mixed, well, drag) && !drag.stale_rows(current))
.show(ui);
proxy_events(app, &out);
if let Some((well, drag)) = &out.dropped {
@@ -813,7 +814,7 @@ fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) {
app.status(tl!("A linked color swatch can only be applied in its own document."));
return;
}
if let Some(params) = drag.paint_drop_params(destination) {
if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) {
let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" };
app.run(cmd, params).ok();
}
@@ -1125,6 +1126,51 @@ mod tests {
assert_eq!(current_paints(&app).0.color().map(|c| c.to_hex()), Some("#00ff00".into()));
}
/// A swatch row held across File › Revert and dropped on a Fill/Stroke well applies nothing to the restored
/// drawing; the same drop from the current contents still applies.
#[test]
fn a_proxy_drop_of_a_swatch_row_held_across_file_revert_applies_nothing() {
use crate::panel_drag::SwatchRows;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let name = "Held Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("proxy-swatch-drop-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
let drag = |app: &VectorcraftApp| {
let st = app.session.active().unwrap();
let paint = st.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows {
document: st.uid,
reverts: st.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
unlinked_process_color: false,
held: Default::default(),
};
PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }
};
app.run("swatch.edit", json!({"name": name, "color": "#00ff00"})).unwrap();
let held = drag(&app);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.all", json!({})).unwrap();
let before = current_paints(&app).0;
let undo = app.session.active().unwrap().history.undo.len();
drop_paint(&mut app, Well::Primary, &held);
assert_eq!(current_paints(&app).0, before, "the stale swatch row paints nothing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the stale drop makes no edit");
let fresh = drag(&app);
drop_paint(&mut app, Well::Primary, &fresh);
assert_eq!(current_paints(&app).0, app.session.active().unwrap().doc.swatch(name).unwrap().paint, "a fresh drag applies");
}
#[test]
fn proxy_drops_keep_the_dragged_process_color_after_switching_documents() {
use crate::panel_drag::SwatchRows;
@@ -1138,6 +1184,7 @@ mod tests {
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows {
document: source.uid,
reverts: source.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -1173,6 +1220,7 @@ mod tests {
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows {
document: source.uid,
reverts: source.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
@@ -1242,6 +1290,8 @@ mod tests_color_wheel_contrast;
#[cfg(test)]
mod tests_color_wheel_contrast_lines;
#[cfg(test)]
mod tests_color_wheel_copy;
#[cfg(test)]
mod tests_color_wheel_document_colors;
#[cfg(test)]
mod tests_color_wheel_gamut;
+2 -1
View File
@@ -439,7 +439,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let order = rows.keys();
let sel = current_sel(app, node.as_deref());
let mut selection = node.as_deref().map_or_else(Selection::default, |n| list_selection(app, n, sel));
let document = app.session.active().map(|st| st.uid);
// The list is keyed by the document's contents: rows held across File › Revert name items of contents that are gone.
let document = app.session.active().map(|st| (st.uid, st.reverts));
let list_id = ui.scope_id().with(("appearance-rows", document));
let has = node.is_some();
// A dragged fill/stroke or effect row lights Duplicate and Delete up, also with nothing picked.
@@ -641,6 +641,42 @@ fn the_selection_summary_is_reused_until_the_document_or_its_subjects_change() {
assert!(fresh_summary(&mut app).mixed(&app).is_some_and(|m| !m.transparency), "the first document's again");
}
/// A fill row held across File › Revert and released on Duplicate Selected Item leaves the restored object's
/// appearance as it is; the same drag started after the revert still duplicates the row.
#[test]
fn an_appearance_row_held_across_file_revert_is_not_dropped_on_the_footer() {
use craft::ui::runtime::drag;
let mut app = app_with_a_selected_rectangle();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let id = app.session.active().unwrap().selection.objects[0];
let folder = vectorcraft_testkit::TempDir::new("appearance-rows-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
let items = |panel: &Panel| node(&panel.app()).appearance.items.len();
let mut panel = Panel::new(app, show);
let hold = |panel: &mut Panel| {
let (from, to) = (panel.rect("Fill").center(), panel.rect("Duplicate Selected Item").center());
panel.drag_hold_between(from, to);
};
hold(&mut panel);
assert!(drag::mark(panel.ctx()).is_some(), "Duplicate Selected Item takes rows of the current contents");
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
panel.app().run("select.set", json!({ "ids": [id.0] })).unwrap();
panel.frame();
let before = items(&panel);
assert!(drag::mark(panel.ctx()).is_none(), "the footer refuses rows of the contents File › Revert replaced");
panel.release();
assert_eq!(items(&panel), before, "the stale row duplicates nothing");
hold(&mut panel);
panel.release();
assert_eq!(items(&panel), before + 1, "a drag started after the revert still duplicates the row");
}
/// The panel's subject is the `Arc` the document holds for the selected object, a targeted group
/// or a targeted layer, not a copy of it; nothing with nothing selected.
#[test]
+16 -10
View File
@@ -312,6 +312,8 @@ pub(crate) struct BrushesView {
pub(crate) struct BrushKey {
/// The uid of the document whose brush it is: a drag from another document's panel names another brush.
pub doc: u64,
/// The document's revert count: a drag held across File › Revert names a brush of contents that are gone.
pub reverts: u64,
/// The brush's name, or the group's type.
pub name: String,
/// Whether the row is a type's group.
@@ -319,15 +321,15 @@ pub(crate) struct BrushKey {
}
impl BrushKey {
fn brush(doc: u64, name: &str) -> Self {
Self { doc, name: name.to_string(), group: false }
fn brush((doc, reverts): (u64, u64), name: &str) -> Self {
Self { doc, reverts, name: name.to_string(), group: false }
}
}
/// The panel's rows: a group per shown type in [`KINDS`] order, without the `hidden` types, each over its brushes of
/// `shown` in library order. Of two brushes with one name only the first, the one a stroke that names it draws with,
/// has a row, so row keys stay unique.
fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec<PresetRow<BrushKey>> {
fn rows(doc: (u64, u64), shown: &[Shown], hidden: &[String]) -> Vec<PresetRow<BrushKey>> {
let first = by_name(shown);
let mut rows = Vec::new();
for (ty, label) in KINDS.iter().filter(|(ty, _)| !hidden.iter().any(|h| h == ty)) {
@@ -335,7 +337,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec<PresetRow<BrushKey>
if of_type.is_empty() {
continue;
}
rows.push(PresetRow::group(BrushKey { doc, name: ty.to_string(), group: true }, tl!(label), 0));
rows.push(PresetRow::group(BrushKey { doc: doc.0, reverts: doc.1, name: ty.to_string(), group: true }, tl!(label), 0));
rows.extend(of_type.into_iter().map(|b| PresetRow::item(BrushKey::brush(doc, &b.name), b.name.clone(), 1)));
}
rows
@@ -346,6 +348,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec<PresetRow<BrushKey>
#[derive(MemoProps)]
struct BrushSource<'a> {
uid: u64,
reverts: u64,
revision: u64,
#[memo_props(covered_by = "revision", reason = "a document version's brushes and resources are fixed")]
doc: Option<&'a Document>,
@@ -356,8 +359,11 @@ struct BrushSource<'a> {
/// The panel's presets: [`rows`]; a brush moves only among those of its type, and paints its stroke preview.
fn brush_source(inputs: BrushSource<'_>) -> PresetSource<'_, BrushKey> {
let fns = PresetFns::<BrushSource<'_>, BrushKey>::new(|s, _| rows(s.uid, s.shown, &s.hidden))
let fns = PresetFns::<BrushSource<'_>, BrushKey>::new(|s, _| rows((s.uid, s.reverts), s.shown, &s.hidden))
.accepts(|s, drag, over, _| {
if (drag.grabbed.doc, drag.grabbed.reverts) != (s.uid, s.reverts) {
return false;
}
let first = by_name(s.shown);
over.and_then(|over| type_of(&first, over)).is_some_and(|ty| type_of(&first, &drag.grabbed) == Some(ty))
})
@@ -531,7 +537,7 @@ fn names_of(sel: &Selection<BrushKey>, doc: u64) -> Selection<String> {
}
/// The keys of the brushes `sel` names in the document `doc`.
fn keys_of(sel: &Selection<String>, doc: u64) -> Selection<BrushKey> {
fn keys_of(sel: &Selection<String>, doc: (u64, u64)) -> Selection<BrushKey> {
let key = |name: &String| BrushKey::brush(doc, name);
Selection::new(sel.items.iter().map(key).collect(), sel.lead.as_ref().map(key), sel.anchor.as_ref().map(key))
}
@@ -558,8 +564,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let sel_brush = selected_brush(app);
let highlighted = sel_brush.clone().or_else(|| current.clone());
let given = match &multi {
Some(sel) => keys_of(sel, uid),
None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush(uid, name))).unwrap_or_default(),
Some(sel) => keys_of(sel, (uid, reverts)),
None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush((uid, reverts), name))).unwrap_or_default(),
};
let hidden = app.ui.brushes_view.hidden.clone();
let view = if app.ui.brushes_view.list { PresetView::List } else { PresetView::Grid };
@@ -572,7 +578,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
};
let ctx = ui.ctx().clone();
let (doc, first, multi_ref, list_ref) = (doc.as_deref(), &first, multi.as_ref(), list.as_slice());
let source = brush_source(BrushSource { uid, revision, doc, shown: &memo, hidden: hidden.clone() });
let source = brush_source(BrushSource { uid, reverts, revision, doc, shown: &memo, hidden: hidden.clone() });
let browser = |ui: &mut Ui| {
let mut state = PresetState::new();
let ctx = ctx.clone();
@@ -639,7 +645,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
PresetEvent::Menu { target, command, .. } => item_command(app, &target, &command, multi.as_ref()),
PresetEvent::Reorder(edit) => move_brush(app, &rows(uid, &memo, &hidden), first, &edit),
PresetEvent::Reorder(edit) => move_brush(app, &rows((uid, reverts), &memo, &hidden), first, &edit),
PresetEvent::Dropped { at, payload, .. } => {
if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::<PanelDrag>().and_then(|p| art_of(p, uid, reverts))) {
crate::dialogs::brush_replace_art::replace(app, &key.name, &ids);
+4 -3
View File
@@ -533,7 +533,8 @@ fn a_brush_dragged_onto_another_of_its_type_moves_before_it() {
let mut t = Trial::new();
let app = t.app();
let st = app.session.active().unwrap();
let order: Vec<String> = rows(st.uid, &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect();
let order: Vec<String> =
rows((st.uid, st.reverts), &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect();
drop(app);
assert_eq!(order[..4], ["3 pt. Round", "6 pt. Flat", "10 pt. Oval", "Dots"]);
let undo = |t: &Trial| undo_count(&t.app());
@@ -886,8 +887,8 @@ fn rows_of_two_brushes_with_one_name_show_the_first() {
let shown = by_name(&raw)["Twin"];
assert_eq!(shown.ty, "art");
assert_eq!(shown.def, got, "the first of two rows of one name is the one shown");
let keys: Vec<BrushKey> = rows(st.uid, &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect();
assert_eq!(keys, [BrushKey::brush(st.uid, "Twin")], "one row, under the first one's type");
let keys: Vec<BrushKey> = rows((st.uid, st.reverts), &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect();
assert_eq!(keys, [BrushKey::brush((st.uid, st.reverts), "Twin")], "one row, under the first one's type");
}
/// A brush's menu acts on it alone, or on the multi-selection when the brush is one of several
+69 -3
View File
@@ -64,6 +64,10 @@
//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule,
//! Show Opacity, Show Hex Field, the contrast settings, Show Color Vision Preview and Show Document
//! Colors are kept with the preferences (`ui.colorWheel`).
//!
//! Panel menu › Copy Color As puts the color on the clipboard as plain text (`color.format`): Hex,
//! Hex with Alpha, CSS rgb(), CSS hsl(), CSS oklch() or CMYK Values. Its items are gray without a
//! solid color, and CSS oklch() also while the active document's RGB space is not sRGB.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
@@ -565,10 +569,23 @@ fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
out
}
/// The items of Copy Color As: the `color.format` notation, which also names the row
/// (`ui.colorWheel.copy.<notation>`), and the label.
fn copy_notations() -> [(&'static str, &'static str); 6] {
[
("hex", tl!("Hex")),
("hexAlpha", tl!("Hex with Alpha")),
("rgb", tl!("CSS rgb()")),
("hsl", tl!("CSS hsl()")),
("oklch", tl!("CSS oklch()")),
("cmyk", tl!("CMYK Values")),
]
}
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows; Show Out-of-Gamut
/// Colors; HSL Sliders and OKLCH Sliders; Show Harmony and Harmony Rule while the wheel shows; Show
/// Opacity and Show Hex Field; Show Contrast, Contrast For and Contrast Background; Show Color
/// Vision Preview; and Show Document Colors.
/// Vision Preview; Show Document Colors; and Copy Color As.
pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
let command = |row: String| PanelRow::Command(CommandRef::new(row_id(&row)));
let mut rows = vec![command("view.wheel".into()), command("view.box".into())];
@@ -589,23 +606,72 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
vec![command("contrastBackground.below".into()), command("contrastBackground.current".into())],
));
rows.extend(["vision", "documentColors"].map(|row| command(row.into())));
rows.push(PanelRow::Separator);
rows.push(PanelRow::Submenu(
Label::from(tl!("Copy Color As").to_string()),
copy_notations().into_iter().map(|(notation, _)| command(format!("copy.{notation}"))).collect(),
));
rows
}
/// The labels, checks and enabled states of [`menu_rows`].
/// The labels, checks and enabled states of [`menu_rows`]. The items of Copy Color As are gray
/// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
for item in items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), target_now(app).color()) {
let srgb = cms::active().rgb_is_srgb();
for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) {
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
if let Some(hint) = item.hint {
state = state.hint(hint);
}
states.set(CommandRef::new(row_id(&item.id)), state);
}
let has_color = target_now(app).color().is_some();
for (notation, label) in copy_notations() {
let oklch = notation == "oklch";
let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch));
if oklch {
state = state.hint(tl!("OKLCH needs sRGB as the working RGB space").to_string());
}
states.set(CommandRef::new(row_id(&format!("copy.{notation}"))), state);
}
}
/// Copy Color As: put `color.format`'s text in `notation` of the color the panel shows on the
/// clipboard, with the opacity of what the row of Show Opacity edits when it has one, and say in
/// the status bar what was copied. Without a solid color nothing is copied and the answer is
/// null; an error of `color.format` goes to the status bar. Without a window to copy through,
/// nothing is copied and the status bar stays as it was, and the answer still holds the text.
/// → `{text}`.
pub(crate) fn copy_color_as(app: &mut VectorcraftApp, notation: &str) -> Result<Value, String> {
let tgt = target_now(app);
let Some(color) = tgt.color() else { return Ok(Value::Null) };
let (o, live) = shown_opacity(app, &tgt);
let mut p = json!({ "color": color_json(&color), "notation": notation });
if live {
p["opacity"] = json!(f64::from(o.clamp(0.0, 1.0)) * 100.0);
}
match app.run("color.format", p) {
Ok(r) => {
let text = r["text"].as_str().unwrap_or_default().to_string();
let Some(ctx) = &app.ui_ctx else { return Ok(json!({ "text": text })) };
ctx.copy_text(text.clone());
app.status(format!("Copied the color as {text}"));
Ok(json!({ "text": text }))
}
Err(e) => {
app.status(e.clone());
Err(e)
}
}
}
/// Run the menu row `id` (`ui.colorWheel.<row>`); `None` when it is not one of this panel's.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option<Result<Value, String>> {
let row = id.strip_prefix("ui.colorWheel.")?;
if let Some(notation) = row.strip_prefix("copy.") {
let (notation, _) = copy_notations().into_iter().find(|(n, _)| *n == notation)?;
return Some(copy_color_as(app, notation));
}
let current = target_now(app).color();
if row == "contrastBackground.current" && current.is_none() {
return Some(Err("Current Color needs a solid color in the active proxy".to_string()));
+2
View File
@@ -846,7 +846,9 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra
open_popover(app, request.index, at);
}
// A colour swatch dropped on the slider: a global or spot colour (or a tint of one) stays linked.
// Swatch rows held across File › Revert change no stop.
if let Some((place, drag)) = &out.dropped
&& !drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts)))
&& let Some(c) = drag.color()
{
let link = match drag {
+44 -8
View File
@@ -56,10 +56,11 @@ use crate::panel_drag::PanelDrag;
/// A style of the panel: its name, which is unique in a document.
pub(crate) type StyleKey = String;
/// A document's graphic style dragged out to the canvas.
/// A document's graphic style dragged out to the canvas. `reverts` identifies the contents it came from.
#[derive(Clone, Debug)]
pub(crate) struct StyleDrag {
pub(crate) document: u64,
pub(crate) reverts: u64,
pub(crate) name: StyleKey,
}
@@ -481,8 +482,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let (alt, linked) = (alt_held(ui), app.session.selection_graphic_style().is_some());
let thumbs = style_thumbs(app, &doc, &looks, panel.preview);
let source = style_source(thumbs);
// The browser's own state (an open rename field, the scroll position) is kept per document.
let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid));
// The browser's own state (an open rename field, the scroll position) is kept per document contents: a style
// dragged from contents File › Revert replaced is not this list's.
let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid, reverts));
let list = PresetBrowser::<StyleKey>::list_id(browser_id);
let takes_object = move |drag: &PanelDrag, _: &DropAt<StyleKey>| dropped_object(drag, uid, reverts).is_some();
// A style dragged from this panel's list.
@@ -524,16 +526,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
.selection(Bind::bound(&mut panel.selection))
.view_lock(view.preset_view())
.reorder(PresetReorder::items())
.drag_payload(move |drag: &ListDrag<StyleKey>| Some(StyleDrag { document: uid, name: drag.grabbed.clone() }))
.drag_payload(move |drag: &ListDrag<StyleKey>| Some(StyleDrag { document: uid, reverts, name: drag.grabbed.clone() }))
.empty(tl!("Select styled art and click New Graphic Style."))
.row_items(items)
.tip(|ui, key| large_tip(app, &thumbs, ui, key))
.takes_drop(PresetDrop::new::<PanelDrag>(DropPlace::Between, takes_object))
.takes_drop(PresetDrop::new::<PanelDrag>(DropPlace::Onto, takes_object))
.takes_drop(PresetDrop::new::<ListDrag<StyleKey>>(
DropPlace::Onto,
|drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)),
))
.takes_drop(PresetDrop::new::<ListDrag<StyleKey>>(DropPlace::Onto, move |drag, at| {
ours(drag) && matches!(at, DropAt::Onto(name) if !drag.keys.contains(name))
}))
.show(ui)
})
};
@@ -1612,6 +1613,41 @@ mod tests {
assert_eq!(names(&p.app()).len(), before.len() + 1, "a thumbnail drag started after the revert still makes a style");
}
/// A style of the list held across File › Revert and released on New Graphic Style duplicates no style of the
/// restored contents; the same drag started after the revert still duplicates it.
#[test]
fn a_style_held_across_file_revert_is_not_dropped_on_the_footer() {
use crate::tests::panel_harness::Panel as PanelHarness;
use craft::ui::runtime::drag;
let mut app = app();
app.run("graphicStyle.new", json!({"name": "Held"})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("graphic-styles-footer-revert");
let path = folder.join("drawing.vectorcraft");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap();
let mut p = PanelHarness::new(app, show);
let hold = |p: &mut PanelHarness| {
let (from, to) = (p.rect("Held").center(), p.rect("New Graphic Style (Alt-click to name it)").center());
p.drag_hold_between(from, to);
};
hold(&mut p);
assert!(drag::mark(p.ctx()).is_some(), "New Graphic Style takes a style of the current contents");
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
p.frame();
let before = names(&p.app());
assert!(drag::mark(p.ctx()).is_none(), "New Graphic Style refuses a style of the contents File › Revert replaced");
p.release();
assert_eq!(names(&p.app()), before, "the stale drop duplicates nothing");
hold(&mut p);
p.release();
assert_eq!(names(&p.app()).len(), before.len() + 1, "a drag started after the revert still duplicates the style");
}
/// A style dropped on another with Alt takes that style's look; on itself it does nothing.
#[test]
fn a_style_dropped_on_another_with_alt_replaces_that_style() {
+3
View File
@@ -205,6 +205,9 @@ impl Membership {
/// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document.
fn grabbed(&self, drag: &PanelDrag) -> Option<Grab> {
if drag.stale_rows(self.active_document) {
return None;
}
let library = &self.library;
match drag {
PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())),
@@ -277,6 +277,49 @@ fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() {
assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added");
}
#[test]
fn a_library_drop_of_a_swatch_row_held_across_file_revert_adds_nothing() {
use crate::panel_drag::SwatchRows;
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("library.create", json!({"name": "Brand"})).unwrap();
let name = "Sunset";
let gradient = json!({"stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]});
app.run("swatch.new", json!({"name": name, "gradient": gradient})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("library-swatch-drop-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
let gradient = json!({"stops": [{"offset": 0, "color": "#00ff00"}, {"offset": 1, "color": "#0000ff"}]});
app.run("swatch.edit", json!({"name": name, "paint": {"gradient": gradient}})).unwrap();
let state = app.session.active().unwrap();
let held = PanelDrag::Paint {
paint: state.doc.swatch(name).unwrap().paint.clone(),
params: json!({"swatch": name}),
rows: Some(SwatchRows {
document: state.uid,
reverts: state.reverts,
grabbed: name.into(),
names: vec![name.into()],
groups: false,
unlinked_process_color: false,
held: Default::default(),
}),
library: None,
};
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
let membership = Membership::of("Brand", app.session.libraries.get("Brand").unwrap(), Some((state.uid, state.reverts)));
assert!(membership.landing(&held, None).is_none(), "hover refuses the stale swatch row");
let mut panel = Harness::new(app, with_source);
panel.frame();
let at = panel.rect("This library is empty").center();
drop_at(&mut panel, held, at);
assert!(panel.app().session.libraries.get("Brand").unwrap().gradients.is_empty(), "release adds no gradient");
}
#[test]
fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() {
let mut app = app();
app.run("library.create", json!({"name": "Brand"})).unwrap();
+7 -5
View File
@@ -429,7 +429,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
let state = &mut model.state;
// The browser fills the room the footer leaves, so the footer stays in view under the swatches. The body can run
// more than once in a pass, so each run builds its own browser. A list drag is keyed by its browser ID. Each
// document has its own browser.
// document's contents have their own browser, so rows held across File › Revert are not this list's.
let mut footed = None;
let out = Stack::new()
.label(tl!("Swatches"))
@@ -452,7 +452,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
.search(search)
.reveal(focus.clone().map(SwatchKey::Swatch))
.footer(None);
ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner
ui.push_id(("swatch-rows", document, reverts), |ui| browser.show(ui)).inner
})
.inner;
app.ui.swatches_panel = model;
@@ -806,7 +806,8 @@ struct Footer {
opts: Option<String>,
group: Option<String>,
libraries_open: bool,
document: Option<u64>,
/// The uid and revert count of the document the panel shows.
document: Option<(u64, u64)>,
/// Whether a drag from the list still has rows the document holds unchanged ([`dnd::follow`]).
held: bool,
}
@@ -822,7 +823,7 @@ impl Footer {
Footer {
kind: model.kind,
libraries_open: library_panel::any_open::<SwatchLibraries>(&app.ui),
document: app.session.active().map(|state| state.uid),
document: app.session.active().map(|state| (state.uid, state.reverts)),
held,
sel,
del,
@@ -836,7 +837,8 @@ impl Footer {
let icon = |id: &'static str| IconSpec::svg(IconId::new(id));
let document = self.document;
let held = self.held;
let rows_drag = move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document);
let rows_drag =
move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some((rows.document, rows.reverts)) == document);
let edit = if self.group.is_some() {
FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group"))
} else {
+4 -4
View File
@@ -8,10 +8,10 @@ use craft::ui::contract::{DropAt, ReorderMove};
use vectorcraft_color::SwatchGroup;
use vectorcraft_engine::{DocState, History, HistoryEntry};
/// Swatches take paints, and take swatch rows or canvas art from the current document.
/// Swatches take paints, and take swatch rows or canvas art from the current document's current contents.
pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool {
match drag {
PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document,
PanelDrag::Paint { rows: Some(rows), .. } => (rows.document, rows.reverts) == (document, reverts),
PanelDrag::Paint { .. } => true,
_ => drag.artwork_for(document, reverts).is_some(),
}
@@ -72,7 +72,7 @@ pub(super) fn drag_of(start: &DragStart, key: &SwatchKey, names: Vec<String>) ->
};
let held = Arc::new(start.rows(&names));
let groups = matches!(key, SwatchKey::Group(_));
let rows = SwatchRows { document: start.uid, grabbed: name.to_string(), names, groups, unlinked_process_color, held };
let rows = SwatchRows { document: start.uid, reverts: start.reverts, grabbed: name.to_string(), names, groups, unlinked_process_color, held };
PanelDrag::Paint { paint, params, rows: Some(rows), library: None }
}
@@ -320,7 +320,7 @@ pub(super) enum FooterTarget {
/// started in another document, is left alone. Other drags are left to their own targets.
pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) {
let PanelDrag::Paint { rows: Some(r), .. } = drag else { return };
if !app.session.active().is_some_and(|state| state.uid == r.document) {
if !app.session.active().is_some_and(|state| (state.uid, state.reverts) == (r.document, r.reverts)) {
return;
}
let held = follow(app, r);
@@ -157,6 +157,53 @@ fn a_swatch_row_drag_reorders_only_its_source_document() {
assert_eq!(names_of(&panel.app(), None), before_source);
}
/// Swatch rows held across File › Revert move nothing in the restored swatches, and drop nothing on New Swatch or
/// Delete Swatch; the same drag started after the revert still moves them.
#[test]
fn a_swatch_row_drag_held_across_file_revert_moves_nothing() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::runtime::drag;
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let folder = vectorcraft_testkit::TempDir::new("swatch-rows-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap();
let stale = rows_drag(&app, "Red", &["Red"]);
let before = names_of(&app, None);
let mut panel = Panel::new(app, show);
let drag_red = |panel: &mut Panel| {
let red = "Red, #ed1c24";
let from = panel.rect(red).center();
let to = panel.rect("Green, #39b54a").center();
panel.drag_hold_role(red, Role::LIST_ITEM, to - from);
};
drag_red(&mut panel);
assert!(drag::mark(panel.ctx()).is_some(), "the list takes rows of the current contents");
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
panel.frame();
assert!(drag::mark(panel.ctx()).is_none(), "the list refuses rows of the contents File › Revert replaced");
panel.release();
assert_eq!(names_of(&panel.app(), None), before, "the stale rows move nothing");
let restored = doc(&panel.app());
let undo = undo_steps(&panel.app());
for target in [dnd::FooterTarget::New, dnd::FooterTarget::Delete] {
dnd::on_footer_drop(&mut panel.app(), target, &stale);
assert_eq!(doc(&panel.app()), restored);
assert_eq!(undo_steps(&panel.app()), undo);
assert!(!dialog_open(&panel.app(), crate::dialogs::confirm::KIND));
}
drag_red(&mut panel);
panel.release();
assert_ne!(names_of(&panel.app(), None), before, "a drag started after the revert still moves the rows");
}
#[test]
fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() {
let mut app = app();
+14 -6
View File
@@ -58,6 +58,8 @@ fn thumb_px(size: f32, pixels_per_point: f32) -> u32 {
pub(crate) struct SymbolKey {
/// The uid of the document whose Symbols panel showed the symbol.
pub doc: u64,
/// The document's revert count: a drag held across File › Revert names a symbol of contents that are gone.
pub reverts: u64,
/// The symbol's name.
pub name: String,
}
@@ -496,6 +498,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
#[derive(MemoProps)]
struct SymbolSource<'a> {
uid: u64,
reverts: u64,
revision: u64,
#[memo_props(covered_by = "revision", reason = "a document version's symbols are fixed")]
doc: &'a Document,
@@ -506,7 +509,11 @@ struct SymbolSource<'a> {
/// The panel's presets: a row per symbol of the document, in its order, each with its thumbnail.
fn symbol_source(inputs: SymbolSource<'_>) -> PresetSource<'_, SymbolKey> {
let fns = PresetFns::<SymbolSource<'_>, SymbolKey>::new(|s, _| {
s.doc.symbols.iter().map(|sym| PresetRow::item(SymbolKey { doc: s.uid, name: sym.name.clone() }, sym.name.clone(), 0)).collect()
s.doc
.symbols
.iter()
.map(|sym| PresetRow::item(SymbolKey { doc: s.uid, reverts: s.reverts, name: sym.name.clone() }, sym.name.clone(), 0))
.collect()
})
.thumb(|s, cx, rect, info| paint_symbol(cx, rect, s.doc, s.keys, &info.key.name));
PresetSource::new(inputs, fns)
@@ -540,8 +547,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let marked = marked(app);
let inst = has_instances_selected(app);
let linked = linked_symbols(app);
let key = |name: &str| SymbolKey { doc: uid, name: name.to_string() };
let source = symbol_source(SymbolSource { uid, revision, doc: &doc, keys: &keys });
let key = |name: &str| SymbolKey { doc: uid, reverts, name: name.to_string() };
let source = symbol_source(SymbolSource { uid, reverts, revision, doc: &doc, keys: &keys });
// The symbols drawn selected: the ones Select All Unused picked, which further picks change,
// else the current one.
let (mut selection, select) = if marked.is_empty() {
@@ -552,8 +559,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let (view, zoom) = app.ui.symbols_view.preset();
let browser_id = ui.make_persistent_id("symbols-browser");
let list = PresetBrowser::<SymbolKey>::list_id(browser_id);
// A symbol dragged from this panel's list, of the document it shows.
let ours = move |drag: &ListDrag<SymbolKey>| drag.list == list && drag.grabbed.doc == uid;
// A symbol dragged from this panel's list, of the contents of the document it shows.
let ours = move |drag: &ListDrag<SymbolKey>| drag.list == list && (drag.grabbed.doc, drag.grabbed.reverts) == (uid, reverts);
let svg = |name: &'static str| IconSpec::svg(IconId::new(name));
let actions = [
FooterAction::new(svg("library"), tl!(SymbolLibraries::MENU))
@@ -656,7 +663,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(out) = footer else { return };
match &out.dropped {
Some(dropped) => {
let Some(drag) = dropped.payload::<ListDrag<SymbolKey>>() else { return };
// A symbol of other contents, another document's or the ones File › Revert replaced, drops nothing.
let Some(drag) = dropped.payload::<ListDrag<SymbolKey>>().filter(|drag| ours(drag)) else { return };
let name = &drag.grabbed.name;
// A symbol deleted while it was dragged drops nothing.
if !doc.symbols.iter().any(|s| s.name == *name) {
@@ -0,0 +1,219 @@
//! The Color Wheel panel's Copy Color As: the text each item puts on the clipboard, the opacity it
//! carries, the status bar message, and that `color.parse` reads each text back.
use craft::keymap::CommandRef;
use craft::ui::menu::PanelRow;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use serde_json::{Value, json};
use vectorcraft_color::cms;
use vectorcraft_engine::Session;
use super::color_wheel::{menu_rows, menu_states, run};
use crate::VectorcraftApp;
/// The command ids of Copy Color As's items, in the menu's order.
const ITEMS: [&str; 6] = [
"ui.colorWheel.copy.hex",
"ui.colorWheel.copy.hexAlpha",
"ui.colorWheel.copy.rgb",
"ui.colorWheel.copy.hsl",
"ui.colorWheel.copy.oklch",
"ui.colorWheel.copy.cmyk",
];
/// An app with a selected rectangle filled with #336699 at `opacity` %.
fn app(opacity: f64) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": "#336699", "opacity": opacity})).unwrap();
app
}
/// Run Copy Color As › `notation` in one frame: its answer and the texts it put on the clipboard.
fn copy(app: &mut VectorcraftApp, notation: &str) -> (Result<Value, String>, Vec<String>) {
let ctx = crate::testing::ui_context();
let mut answer = None;
let out =
crate::testing::part_frame(app, &ctx, Default::default(), |app, _| answer = run(app, &format!("ui.colorWheel.copy.{notation}"), &json!({})));
let copied =
out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect();
(answer.expect("a Copy Color As item"), copied)
}
/// The texts Copy Color As › `notation` puts on the clipboard.
fn copied(app: &mut VectorcraftApp, notation: &str) -> Vec<String> {
copy(app, notation).1
}
fn undo_count(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
/// Whether the panel menu's command `id` is enabled.
fn enabled(app: &VectorcraftApp, id: &str) -> bool {
let mut states = CommandStates::new();
menu_states(app, &mut states);
states.get(&CommandRef::new(id.to_string())).is_some_and(CommandState::is_enabled)
}
/// Copy Color As › CSS rgb() puts CSS Color 4's space-separated form on the clipboard, with the
/// opacity after a slash, answers it and says what it copied; the document does not change.
#[test]
fn css_rgb_copies_the_color_and_the_opacity() {
let mut app = app(50.0);
let before = undo_count(&app);
let (answer, texts) = copy(&mut app, "rgb");
assert_eq!(texts, ["rgb(51 102 153 / 50%)"]);
assert_eq!(answer, Ok(json!({"text": "rgb(51 102 153 / 50%)"})));
assert_eq!(app.ui.status, "Copied the color as rgb(51 102 153 / 50%)");
assert_eq!(undo_count(&app), before, "copying records no undo step");
}
/// Without a window to copy through, an item answers its text and the status bar does not say it
/// was copied.
#[test]
fn without_a_window_the_text_is_answered_and_not_reported_as_copied() {
let mut app = app(50.0);
app.ui_ctx = None;
app.ui.status.clear();
assert_eq!(run(&mut app, "ui.colorWheel.copy.hex", &json!({})), Some(Ok(json!({"text": "#336699"}))));
assert_eq!(app.ui.status, "");
}
/// Hex and CMYK Values never carry the opacity; Hex with Alpha always does, as `ff` at 100 %; CSS
/// adds it only under 100 %.
#[test]
fn each_item_writes_its_notation() {
let mut half = app(50.0);
assert_eq!(copied(&mut half, "hex"), ["#336699"]);
assert_eq!(copied(&mut half, "hexAlpha"), ["#33669980"]);
assert_eq!(copied(&mut half, "hsl"), ["hsl(210 50% 40% / 50%)"]);
let oklch = copied(&mut half, "oklch");
assert!(oklch[0].starts_with("oklch(") && oklch[0].ends_with(" / 50%)"), "{oklch:?}");
let mut full = app(100.0);
assert_eq!(copied(&mut full, "hexAlpha"), ["#336699ff"]);
assert_eq!(copied(&mut full, "rgb"), ["rgb(51 102 153)"]);
let cmyk = copied(&mut full, "cmyk");
assert_eq!(copied(&mut half, "cmyk"), cmyk, "CMYK Values leaves the opacity out");
// The working CMYK numbers through the color settings, as color.convert gives them.
let r = full.run("color.convert", json!({"color": "#336699", "to": "cmyk"})).unwrap();
let pct: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect();
assert_eq!(cmyk, [format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3])]);
}
/// A CMYK fill copies its own CMYK values.
#[test]
fn a_cmyk_fill_copies_its_own_values() {
let mut app = app(100.0);
app.run("paint.setFill", json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap();
assert_eq!(copied(&mut app, "cmyk"), ["C=10 M=20 Y=30 K=0"]);
}
/// `color.parse` reads every copied text but CMYK Values back to the color the hex field shows,
/// and the alpha to the fill's opacity.
#[test]
fn color_parse_reads_each_copied_text_back() {
let mut app = app(25.0);
for notation in ["hex", "hexAlpha", "rgb", "hsl", "oklch"] {
let text = copied(&mut app, notation).pop().unwrap();
let r = app.run("color.parse", json!({"text": text})).unwrap();
assert_eq!(r["hex"], "#336699", "{notation}: {text}");
let opacity = r["opacity"].as_f64();
match notation {
"hex" => assert_eq!(opacity, None, "{text}"),
// 64 of 255.
"hexAlpha" => assert_eq!(opacity, Some(25.1), "{text}"),
_ => assert_eq!(opacity, Some(25.0), "{text}"),
}
}
}
/// With nothing selected the panel shows the color for new art, which has no opacity of its own:
/// the copied text carries none.
#[test]
fn with_nothing_selected_the_color_for_new_art_is_copied_without_an_opacity() {
let mut app = app(50.0);
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"color": "#336699"})).unwrap();
assert_eq!(copied(&mut app, "hexAlpha"), ["#336699ff"]);
assert_eq!(copied(&mut app, "rgb"), ["rgb(51 102 153)"]);
}
/// Without a solid color (a fill of None) nothing is copied, the status bar stays as it was and
/// the item answers null.
#[test]
fn nothing_is_copied_without_a_solid_color() {
let mut app = app(100.0);
app.run("paint.setFill", json!({"none": true})).unwrap();
app.ui.status.clear();
let (answer, texts) = copy(&mut app, "hex");
assert!(texts.is_empty());
assert_eq!(answer, Ok(Value::Null));
assert_eq!(app.ui.status, "");
}
/// The panel menu ends with a separator and the Copy Color As submenu, which holds the six items in
/// order; another `copy.` row is not one of the panel's.
#[test]
fn the_menu_ends_with_copy_color_as() {
let mut app = app(100.0);
let rows = menu_rows(&app);
let [.., PanelRow::Separator, PanelRow::Submenu(_, items)] = &rows[..] else { panic!("Copy Color As last: {} rows", rows.len()) };
let ids: Vec<String> = items
.iter()
.map(|row| match row {
PanelRow::Command(c) => c.key().to_string(),
_ => panic!("a command row"),
})
.collect();
assert_eq!(ids, ITEMS);
assert!(run(&mut app, "ui.colorWheel.copy.lab", &json!({})).is_none());
}
/// The items of Copy Color As are gray without a solid color and available with one.
#[test]
fn copy_color_as_is_gray_without_a_solid_color() {
let app = app(100.0);
for id in ITEMS {
assert!(enabled(&app, id), "{id}");
}
let mut none = self::app(100.0);
none.run("paint.setFill", json!({"none": true})).unwrap();
for id in ITEMS {
assert!(!enabled(&none, id), "{id}");
}
}
/// While the working RGB space is not sRGB, Copy Color As › CSS oklch() is gray, the other items are
/// not, and copying as oklch() puts the error in the status bar and nothing on the clipboard.
#[test]
fn css_oklch_is_gray_while_the_working_space_is_not_srgb() {
const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_COPY_P3";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: change them in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "panels::tests_color_wheel_copy::css_oklch_is_gray_while_the_working_space_is_not_srgb", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated working space test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
return;
}
let mut app = app(100.0);
assert!(enabled(&app, "ui.colorWheel.copy.oklch"), "sRGB");
app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap();
let (answer, texts) = copy(&mut app, "oklch");
assert!(texts.is_empty());
assert!(answer.is_err(), "{answer:?}");
assert!(app.ui.status.ends_with("OKLCH needs sRGB as the working RGB space"), "{}", app.ui.status);
assert!(!enabled(&app, "ui.colorWheel.copy.oklch"));
for id in ITEMS.into_iter().filter(|id| !id.ends_with("oklch")) {
assert!(enabled(&app, id), "{id}");
}
}
+53 -9
View File
@@ -721,7 +721,6 @@ saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color
`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB.
A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped
to sRGB first.
The answer of `ui.colorWheel` and the settings also carry `sliders`.
`ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu
does: a row of four chips under the wheel or the box shows the current color through the protanopia, deuteranopia
@@ -755,13 +754,33 @@ angles and `none`, so `calc()`, `var()`, `color-mix()`, relative color syntax an
errors, as are named colors and the functions and color spaces not listed above (`hwb()`, `lab()`, `oklab()` and
`color()`). A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as
`#rrggbb` does in every command, and `oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH
Sliders lower it; `oklch()` is an error while the working RGB space is not sRGB. Values are clamped where CSS clamps
Sliders lower it; `oklch()` is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB. Values are clamped where CSS clamps
them when it parses them (red, green and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH
lightness to 0 to 1 and a negative chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is
clipped. An `hsl()` color whose saturation and lightness are so large that a channel overflows to an infinity is an
error. `opacity` is the alpha as a percentage, or `null` when the text gives none. Any other text is an error. The
color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`.
`color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`.
`notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl`
(`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the
default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity, rounded to two decimal places, is under 100 (`99.999` writes no suffix);
`hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers
the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not
sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two
more where fewer would read back to another color. `cmyk` is the color in the working CMYK space
through the color settings, written as a new swatch is named; a CMYK color keeps its own values. `color.parse` reads
every notation but `cmyk` back to the same `#rrggbb`. `opacity` is 0 to 100, and any other value, or another
`notation`, is an error.
The Color Wheel panel menu's Copy Color As puts the panel's color on the clipboard as Hex, Hex with Alpha, CSS
rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, with the opacity that Show Opacity
edits when it has one (whether or not that row shows), and the status bar shows what was copied. Its items are the
menu commands `ui.colorWheel.copy.hex`, `ui.colorWheel.copy.hexAlpha`, `ui.colorWheel.copy.rgb`,
`ui.colorWheel.copy.hsl`, `ui.colorWheel.copy.oklch` and `ui.colorWheel.copy.cmyk`, which answer `{text}`, or null without a solid color. They are gray without a solid color, and CSS oklch() is also gray
while the active document's RGB space is not sRGB. Without a window to copy through, an item puts nothing on the clipboard and
leaves the status bar as it was, and still answers `{text}`.
In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's
screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop
portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html)
@@ -974,7 +993,7 @@ its own. A color for a grayscale or 1-bit image's drawing color creates no fill
to a fill row the image has. With New Art Has Basic Appearance off, the next shape copies the first selected object's
appearance after any command, its opacity included. Without a new paint, `objects` counts only the targets that took the opacity. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has
that row (a selected path of a compound path answers with its compound path's row, which the commands edit, and a
selected Live Paint group answers with its faces' fills and its edges' strokes). It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it),
selected Live Paint group answers with its faces' fills and its edges' strokes). With a layer targeted, it reads the layer's visible, unlocked art, as the commands do. It answers null with nothing selected, for an object selected in a symbol instance, while the Live Paint Bucket paints (it is the active tool, or a Cmd+click or an Eyedropper pick works for it),
while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that
row are selected. Live effects take the same `item` to apply to one fill or
stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and
@@ -2912,8 +2931,12 @@ through `$`:
- `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/
describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one),
`app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`,
`app.redraw()`,
`app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `executeMenuCommand` runs the command of a menu item
`app.redraw()`, `app.undo()`, `app.redo()`,
`app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing
anything. `app.undo()` and `app.redo()` run `edit.undo` and `edit.redo` in the active document and reach
only the steps the run made; with no such step they change nothing, and with no document open they throw
`No active document` (VectorCraft's own rules). After a run that succeeds, each document that was open
before it, is still open and whose content changed has one new undo step. `executeMenuCommand` runs the command of a menu item
on the active document, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts
describe the method, and takes these names from the list at
https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510:
@@ -2949,8 +2972,8 @@ through `$`:
`addDocument` checks the ranges of the values. `documentBleedLink`, `documentBleedOffsetRect` and
`transparencyGrid` also take `null` and can be assigned, but `addDocument` throws an error that says they are not available yet when
the preset it is given holds one of them with a value other than `null`, and makes no document. A
`presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a
`TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the
`presetSettings` that is omitted, `undefined` or `null` gives the preset's settings unchanged; any other value
that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the
automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the
profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it
that cannot be used, for example) goes to the Script Console as a line `addDocument: <warning>`. A `previewMode` of
@@ -6044,7 +6067,8 @@ Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush.
`brush.placeArt {name, x?, y?}` places a copy of the art a scatter, art or pattern brush is made of, centered on
(`x`, `y`) (default: the center of the first artboard), and selects it, in one undo step. The app runs it when a
brush is dragged from the Brushes panel onto an empty part of the canvas; dropped on a path, a brush is applied to it
(`brush.apply`). A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner
(`brush.apply`). A brush, graphic style, symbol, swatch or appearance whose drag started before File › Revert is not
dropped on the restored drawing. A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner
corner, start, end (only the tiles it has art for), each in a group named Side Tile, Outer Corner Tile, Inner Corner
Tile, Start Tile or End Tile. A tile with a repeat frame has an unpainted rectangle at the back of its group that marks
the frame. A symbol instance in the art is measured by its symbol's art. A calligraphic or bristle brush is refused
@@ -7192,7 +7216,8 @@ the panel shows) is meant.
takes them), `fillColor` / `strokeColor` (the first selected object's solid colour, else the default one, or `color`),
`charStyle` / `paraStyle` (the selected text's attributes). The new item goes into `group` (by default into none) and,
with `before` or `after` (another item of its kind), just before or after that item, as `library.moveItem` places one;
art and swatches dropped among the panel's items are added this way. An item the library already has is reported as
art and swatches dropped among the panel's items are added this way (a swatch dragged before File › Revert of its
drawing is not added). An item the library already has is reported as
`existing`, and stays where it is. `library.use {library?, kind, item,
center?, to?}` uses one: a graphic is placed centred on `center` (pasted with its resources; a swatch name the document
gives another colour merges into the document's), a colour paints the selection's fill or stroke, and a style is added
@@ -8451,6 +8476,25 @@ the dialog on those settings next time.
`"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit
(`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default.
`object.path.cleanUp` with `hairlineSlivers: true` also removes hairline slivers: closed paths and compound paths with
a visible fill, no visible stroke and no effect, so thin that no circle `sliverWidth` across fits inside their fill
(Unpainted Objects covers shapes with no paint). A compound path is measured as one fill, so a compound path with one
sliver member and one real shape stays. `sliverWidth` is a distance from 0.001 to 3 pt; it defaults to 0.03 mm,
VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop app the Clean Up dialog has a Hairline
Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round
0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean
Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command
takes hidden or locked objects, objects at 0% opacity or in a group or layer at 0% opacity, objects in template
layers, art on locked artboards, guides, the clipping paths of groups and layers, what a group or compound path used as
a clipping path holds, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape
that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is
every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were:
```json
{"name":"run_command","arguments":{"command":"object.path.cleanUp","params":{"strayPoints":false,"unpaintedObjects":false,"emptyTextPaths":false,"hairlineSlivers":true,"sliverWidth":"0.03 mm"}}}
{"name":"run_command","arguments":{"command":"select.object.hairlineSlivers","params":{"width":0.1}}}
```
## Smooth
`object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo
+3 -2
View File
@@ -1,7 +1,7 @@
# Roadmap: milestones and what's next
> Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged.
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a gLine truncated
> Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged.
@@ -193,7 +193,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|---|---|---|---|
| M0 | Skeleton + vertical slice | ✅ done | — |
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; 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 (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 |
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; 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 (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 |
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 |
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF importLine truncated
| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 |
@@ -257,6 +257,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours
| 2026-11-21 | minor | G13: View › Snapping groups five existing toggles and Pixel Snapping Options…; top-level commands and shortcuts remain; headless click/checkmark coverage added; scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Properties Quick Actions offer Ungroup when any selected object is a group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path. Headless regressions: `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`. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-20 | minor | M2: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. |
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
| 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. |
+6 -2
View File
@@ -3,7 +3,7 @@
Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written.
> Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged.
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previoLine truncated
> Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged.
>
@@ -132,6 +132,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. |
| 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. |
| 2026-11-20 | minor | Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. |
@@ -938,6 +939,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged.
- **Artboard guides with Cmd/Ctrl + ruler drag:** VectorCraft's own option, Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag (`cmdRulerDragArtboardGuides`), off by default. With it on, Cmd/Ctrl held when a drag leaves a ruler makes a guide of the active artboard, and with the Artboard tool a canvas guide; the key is read when the drag starts. The guide is made only where it lies within the active artboard. The documented way to limit a guide to one artboard, dragging it out with the Artboard tool ([Align objects with guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html)), is unchanged when the option is off. Tests `rulerguide::tests::a_guide_within_its_artboard_is_made_only_inside_it`, `tests::menucmds::cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on` and `canvas::tests::cmd_ruler_drags_make_artboard_guides_with_the_preference_on`.
- **Smart Guides targets in documents with many anchors (#8531):** the snap targets for a dragged ruler guide, a moved, scaled or drawn object and the other gestures that gather the art's targets are gathered topmost first, in reverse paint order, so when the 20,000 anchors and 20,000 path segments they gather run out, the objects in front, the newest, keep their anchors, edges and centre, and the oldest objects at the back are the ones left out (the walk used to start at the back, so in a document with more anchors the topmost and newest objects gave no targets at all). The budgets, cost and memory are unchanged: on the 50,000-path document of the deep `vectorcraft-cli perf` run, "smart guide targets in view" stays at about 1.9 ms. Tests: `a_new_guide_snaps_to_the_newest_object_over_many_anchors` in `crates/tools/src/rulerguide/tests.rs` and `the_topmost_object_keeps_its_targets_past_the_anchor_budget` in `crates/tools/src/guides/tests.rs`.
- **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged.
- **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html).
@@ -1118,6 +1120,7 @@ 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: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- 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`.
@@ -1821,6 +1824,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Geometry and effects:**
- **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged.
- Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635).
Clean Up has a Hairline Slivers option, VectorCraft's own and off by default: it removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle as wide as its Sliver Width (0.03 mm by default) fits inside their fill, and Select › Object › Hairline Slivers… selects them (`crates/engine/src/tests/pathops.rs`, `crates/pathops/src/thickness.rs` tests).
Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow.
Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests).
Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`).
@@ -2152,7 +2156,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged.
- **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`.
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged.
VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged.
VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the active document's RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged.
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents.
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents. With the row shown, the wheel's square and the box's field draw the AA and AAA lines, and a chip in the row offers the closest color of the same hue that passes, which `color.contrast` answers as `fix`.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
+3 -2
View File
@@ -1,7 +1,7 @@
# UI and interaction parity
> Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged.
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previouLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolutionLine truncated
> Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged.
>
@@ -292,7 +292,7 @@ tools, never checked side by side) isn't captured row by row.
| Behaviour | Status | Notes |
|---|---|---|
| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide |
| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide; in a heavy document, past the 20,000 anchors gathered, the topmost, newest objects keep their anchors, edges and centre (#8531) |
| Anchor/Path labels ("anchor", "center", "path", "align") | done | |
| "intersect" label and snapping to path intersections | partial | #1658 (part of #1602): a point drawn with the Pen, the shape tools or the other drawing tools and an anchor dragged with Direct Selection snap to where paths and ruler guides cross; a moved selection's own anchors and the Width tool don't |
| Construction guides at preference angles while drawing | done | #506 |
@@ -667,6 +667,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra
| 2026-11-21 | minor | G13: View › Snapping groups five existing toggles and Pixel Snapping Options…; top-level commands and shortcuts remain; headless click/checkmark coverage added; scores and estimates unchanged. |
| 2026-11-21 | minor | G12: Properties Quick Actions offer Ungroup when any selected object is a group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path. Headless regressions: `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`. Scores and estimates unchanged. |
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
| 2026-11-20 | minor | Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |
| 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. |
| 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. |