Merge main into feat/print-custom-scale-link

This commit is contained in:
dotCooCoo
2026-11-16 08:07:02 -08:00
35 changed files with 2399 additions and 189 deletions
@@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
};
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
}
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center()));
// Centers closer than a billionth of the larger path's size count as one point: no line.
let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center()));
let fill = Paint::None;
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1));
@@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() {
}
}
#[test]
fn tiny_paths_close_together_still_get_the_centerline() {
// Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four
// tangents, and centers apart by far more than their sizes' rounding.
let mut s = session();
let a = circle(&mut s, 1.0, 1.0, 1e-10);
let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10);
let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap();
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}");
assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}");
assert_eq!(r["centerline"], r["ids"][4]);
}
#[test]
fn the_lines_take_the_current_stroke_and_no_fill() {
let mut s = session();
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
has_doc,
screens::export_for_screens
),
+9 -3
View File
@@ -350,8 +350,8 @@ struct ScreenParams {
/// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as
/// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`.
folders: Option<String>,
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or
/// `multiple` (a file per artboard, the default).
/// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file; refused
/// with assets, layers or `selection: "each"`) or `multiple` (a file per artboard, the default).
pdfs: Option<String>,
}
@@ -399,12 +399,18 @@ impl ScreenParams {
if p.is_object() { Self::deserialize(p).map_err(|e| bad(C, e.to_string())) } else { Ok(Self::default()) }
}
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given.
/// An error when more than one of `assets`, `layers`, `selection` and `fullDocument` is given,
/// and when `pdfs: "single"` is given with `assets`, `layers` or `selection: "each"`, whose
/// files each hold the art of one item.
fn one_source(&self) -> Result<()> {
let sources = [self.full_document, self.assets.is_some(), self.layers.is_some(), self.selection.is_some()].iter().filter(|b| **b).count();
if sources > 1 {
return Err(bad(C, "give one of assets, layers, selection or fullDocument"));
}
let per_piece = self.assets.is_some() || self.layers.is_some() || self.selection.as_deref() == Some("each");
if per_piece && self.pdfs.as_deref() == Some("single") {
return Err(bad(C, "pdfs `single` writes artboards as the pages of one PDF: assets, layers and selection `each` write a PDF each"));
}
Ok(())
}
@@ -1245,6 +1245,41 @@ fn single_file_pdfs_hold_every_chosen_artboard() {
assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err());
}
/// Export PDFs As › Single file holds artboards: with assets, layers or a file per selected object,
/// whose files each hold one item's art, it is refused (the Example line too) instead of writing
/// the first item alone under the document's name; Multiple files writes a PDF of each item. The
/// selection as one file is one PDF either way.
#[test]
fn single_file_pdfs_are_refused_for_assets_layers_and_each_object() {
let mut s = session(1);
s.execute("layer.new", &json!({"name": "Second"})).unwrap();
s.execute("shape.ellipse", &json!({"x": 30, "y": 5, "width": 8, "height": 8})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let layers: Vec<u64> = doc.layers.iter().map(|l| l.id.0).collect();
let art: Vec<u64> = doc.layers.iter().filter_map(|l| l.children()).flatten().map(|c| c.id.0).collect();
assert_eq!((layers.len(), art.len()), (2, 2));
let a = s.execute("assets.add", &json!({"ids": [art[0]], "name": "Square"})).unwrap()["assets"][0].as_u64().unwrap();
let b = s.execute("assets.add", &json!({"ids": [art[1]], "name": "Dot"})).unwrap()["assets"][0].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let pdf = json!([{"format": "pdf"}]);
for source in [json!({"assets": [a, b]}), json!({"layers": layers}), json!({"selection": "each"})] {
let mut p = source.clone();
p["formats"] = pdf.clone();
p["pdfs"] = json!("multiple");
let r = export(&mut s, p.clone());
assert_eq!(names(&r).len(), 2, "a PDF each: {:?} ({source})", names(&r));
for (name, bytes) in files(&r) {
assert_eq!(vectorcraft_pdf::import(&bytes).unwrap().artboards.len(), 1, "{name}");
}
p["pdfs"] = json!("single");
let e = s.execute("document.exportForScreens", &p).unwrap_err().to_string();
assert!(e.contains("pdfs `single`"), "{e} ({source})");
assert!(super::screens::first_file(&s, &p).is_err(), "{source}");
}
let r = export(&mut s, json!({"selection": "one", "pdfs": "single", "formats": pdf}));
assert_eq!(names(&r), ["Selection.pdf"]);
}
/// The warnings of reply `r` that name an option the file doesn't read.
fn unused(r: &Value) -> Vec<String> {
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
+1 -1
View File
@@ -58,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show Similar Fonts",
[],
None,
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind; a family that shares none of these numbers with it comes after those that share one); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
always,
similar_fonts
),
+222 -31
View File
@@ -5,13 +5,14 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind};
use super::select::selectable_ids;
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, has_doc, object_param, str_param, switch_or};
/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in
/// points, opacity in percent.
/// Magic Wand panel settings. Tolerances: colors as a Euclidean distance, 0–255 between RGB
/// values in an RGB document and 0–100 between CMYK percentages in a CMYK document; stroke
/// weight in points; opacity in percent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WandSettings {
@@ -58,33 +59,68 @@ pub fn specs() -> Vec<CommandSpec> {
"Magic Wand Options",
["Window", "Magic Wand"],
None,
"{fillColor?, fillTolerance?: 0-255, strokeColor?, strokeTolerance?: 0-255, strokeWeight?, weightTolerance?: pt, opacity?, opacityTolerance?: %, blendingMode?, reset?: bool} → the settings",
"{fillColor?, fillTolerance?: 0-255 in an RGB document or 0-100 in a CMYK one, strokeColor?, strokeTolerance?: as fillTolerance, strokeWeight?, weightTolerance?: 0-1000 pt, opacity?, opacityTolerance?: 0-100 %, blendingMode?, reset?: bool} → the settings; a value out of range is an error and changes nothing, and an omitted one keeps its setting",
always,
set
),
cmd!(query "magicWand.options", "Magic Wand Settings", [], None, "{} → the Magic Wand settings", always, |s, _| Ok(json!(s.menu.wand))),
cmd!(
query "magicWand.options",
"Magic Wand Settings",
[],
None,
"{} → the Magic Wand settings (color tolerances at most 100 in a CMYK document)",
always,
|s, _| Ok(json!(s.menu.wand.effective(active_mode(s))))
),
]
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
if bool_or(p, "reset", false) {
s.menu.wand = WandSettings::default();
/// The active document's color mode, RGB with no document open.
fn active_mode(s: &Session) -> ColorMode {
s.doc().map(|st| st.doc.color_mode).unwrap_or_default()
}
/// The largest Fill Color and Stroke Color tolerance in a document of `mode`.
pub fn color_tolerance_max(mode: ColorMode) -> f64 {
match mode {
ColorMode::Rgb => 255.0,
ColorMode::Cmyk => 100.0,
}
let mut v = serde_json::to_value(&s.menu.wand).map_err(|e| EngineError::Other(e.to_string()))?;
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
for (k, val) in src {
if o.contains_key(k) {
o.insert(k.clone(), val.clone());
}
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "magicWand.set";
let mode = active_mode(s);
let color_max = color_tolerance_max(mode);
let mut w = if switch_or(p, "reset", false, CMD)? { WandSettings::default() } else { s.menu.wand.clone() };
for (key, flag) in [
("fillColor", &mut w.fill_color),
("strokeColor", &mut w.stroke_color),
("strokeWeight", &mut w.stroke_weight),
("opacity", &mut w.opacity),
("blendingMode", &mut w.blending_mode),
] {
// Only a missing key keeps the setting; null, like any other value that isn't true or
// false, is an error.
if let Some(v) = p.get(key) {
*flag = v.as_bool().ok_or_else(|| bad(CMD, format!("`{key}` must be true or false")))?;
}
}
let mut w: WandSettings = serde_json::from_value(v).map_err(|e| bad("magicWand.set", e.to_string()))?;
w.fill_tolerance = w.fill_tolerance.clamp(0.0, 255.0);
w.stroke_tolerance = w.stroke_tolerance.clamp(0.0, 255.0);
w.weight_tolerance = w.weight_tolerance.clamp(0.0, 1000.0);
w.opacity_tolerance = w.opacity_tolerance.clamp(0.0, 100.0);
for (key, value, max) in [
("fillTolerance", &mut w.fill_tolerance, color_max),
("strokeTolerance", &mut w.stroke_tolerance, color_max),
("weightTolerance", &mut w.weight_tolerance, 1000.0),
("opacityTolerance", &mut w.opacity_tolerance, 100.0),
] {
let Some(v) = p.get(key) else { continue };
let n = v.as_f64().ok_or_else(|| bad(CMD, format!("`{key}` must be a number, not {v}")))?;
if !(n.is_finite() && (0.0..=max).contains(&n)) {
return Err(bad(CMD, format!("`{key}` must be from 0 to {max}, not {n}")));
}
*value = n;
}
s.menu.wand = w;
Ok(json!(s.menu.wand))
Ok(json!(s.menu.wand.effective(mode)))
}
/// The fill an object shows: type's comes from its characters (the first run speaks for all; type
@@ -104,25 +140,48 @@ pub(crate) fn stroke_of(n: &Node) -> (Paint, f64) {
}
}
/// Are two paints within `tol` (0–255 Euclidean RGB distance)? Non-solid paints must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64) -> bool {
/// Are two paints within `tol`? In an RGB document `tol` is a 0–255 Euclidean distance between
/// the display RGB values; in a CMYK document it is a 0–100 Euclidean distance between the CMYK
/// percentages (a CMYK color's own values, any other color converted to CMYK). Non-solid paints
/// must match exactly.
pub fn similar_paint(a: &Paint, b: &Paint, tol: f64, mode: ColorMode) -> bool {
match (a.color(), b.color()) {
(Some(x), Some(y)) => {
let (x, y) = (x.to_rgb(), y.to_rgb());
let d: f64 = (0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt();
d <= tol + 1e-6
let (d, margin) = match mode {
ColorMode::Rgb => {
let (x, y) = (x.to_rgb(), y.to_rgb());
((0..3).map(|i| ((x[i] - y[i]) as f64 * 255.0).powi(2)).sum::<f64>().sqrt(), 1e-6)
}
// CMYK components are f32 fractions, so a distance of exactly `tol` points can come
// out a few millionths over.
ColorMode::Cmyk => {
let (x, y) = (x.to_cmyk(), y.to_cmyk());
((0..4).map(|i| ((x[i] - y[i]) as f64 * 100.0).powi(2)).sum::<f64>().sqrt(), 1e-4)
}
};
d <= tol + margin
}
_ => a == b,
}
}
impl WandSettings {
/// Does `n` match `reference` on every enabled attribute?
pub fn matches(&self, reference: &Node, n: &Node) -> bool {
/// The settings in effect in a document of `mode`: the color tolerances are capped at that
/// mode's maximum, so a larger value set in an RGB document applies as 100 in a CMYK one and
/// comes back in an RGB one.
pub fn effective(&self, mode: ColorMode) -> WandSettings {
let max = color_tolerance_max(mode);
WandSettings { fill_tolerance: self.fill_tolerance.min(max), stroke_tolerance: self.stroke_tolerance.min(max), ..self.clone() }
}
/// Does `n` match `reference` on every enabled attribute, comparing colors as in a document of
/// `mode`?
pub fn matches(&self, reference: &Node, n: &Node, mode: ColorMode) -> bool {
let w = self.effective(mode);
let (rs, rw) = stroke_of(reference);
let (ns, nw) = stroke_of(n);
(!self.fill_color || similar_paint(&fill_of(reference), &fill_of(n), self.fill_tolerance))
&& (!self.stroke_color || similar_paint(&rs, &ns, self.stroke_tolerance))
(!w.fill_color || similar_paint(&fill_of(reference), &fill_of(n), w.fill_tolerance, mode))
&& (!w.stroke_color || similar_paint(&rs, &ns, w.stroke_tolerance, mode))
&& (!self.stroke_weight || (rw - nw).abs() <= self.weight_tolerance + 1e-9)
&& (!self.opacity || ((reference.opacity - n.opacity).abs() as f64 * 100.0) <= self.opacity_tolerance + 1e-6)
&& (!self.blending_mode || reference.blend == n.blend)
@@ -156,12 +215,13 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
let w = s.menu.wand.clone();
let mode = st.doc.color_mode;
// In isolation mode only the isolated group's contents can be picked, as for Select Same.
let inside = st.isolation.map(|iso| selectable_ids(&st.doc, Some(iso)));
let hits: Vec<NodeId> = paintable(&st.doc)
.into_iter()
.filter(|i| inside.as_ref().is_none_or(|set| set.contains(i)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n)))
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
.collect();
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
@@ -232,6 +292,137 @@ mod tests {
assert_eq!(selected(&s), [b]);
}
/// A 10 × 10 rectangle at `x` filled and stroked with the given colors (JSON color values).
fn painted(s: &mut Session, x: f64, fill: Value, stroke: Value) -> u64 {
let id = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({ "color": fill })).unwrap();
s.execute("paint.setStroke", &json!({ "color": stroke })).unwrap();
id
}
fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value {
json!({"model": "cmyk", "c": c, "m": m, "y": y, "k": k})
}
#[test]
fn cmyk_document_compares_fill_and_stroke_colors_in_cmyk() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let white = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.1, 0.0, 0.0, 0.0), white.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.0), white.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.1, 0.0, 0.0), white.clone());
// a to b is 10 points of cyan; a to c is 10 points of cyan and 10 of magenta (14.1).
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
s.execute("magicWand.set", &json!({"fillTolerance": 14.2})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
// Stroke Color alone, the same rule: d's stroke is 5 points of black from a's.
let d = painted(&mut s, 60.0, cmyk(1.0, 1.0, 1.0, 1.0), cmyk(0.0, 0.0, 0.0, 0.05));
s.execute("magicWand.set", &json!({"fillColor": false, "strokeColor": true, "strokeTolerance": 5})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [a, b, c, d]);
s.execute("magicWand.set", &json!({"strokeTolerance": 4.9})).unwrap();
s.execute("select.magicWand", &json!({"id": d})).unwrap();
assert_eq!(selected(&s), [d]);
}
#[test]
fn cmyk_document_compares_gray_as_black_ink() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, json!({"gray": 0.5}), none.clone());
let b = painted(&mut s, 20.0, cmyk(0.0, 0.0, 0.0, 0.5), none.clone());
let c = painted(&mut s, 40.0, cmyk(0.0, 0.0, 0.0, 0.6), none);
s.execute("magicWand.set", &json!({"fillTolerance": 0})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b, c]);
}
#[test]
fn rgb_document_keeps_the_rgb_distance() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
let a = rect(&mut s, 0.0, "#000000", 1.0);
let b = rect(&mut s, 20.0, "#0a0000", 1.0);
s.execute("magicWand.set", &json!({"fillTolerance": 10})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
s.execute("magicWand.set", &json!({"fillTolerance": 9.9})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a]);
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 255})).unwrap()["fillTolerance"], 255.0);
}
#[test]
fn set_rejects_tolerances_out_of_range_and_changes_nothing() {
let mut s = Session::new();
// With no document the color range is the RGB one.
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 256})).is_err());
s.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 40, "strokeTolerance": 50})).unwrap();
let before = s.execute("magicWand.options", &json!({})).unwrap();
for bad_value in [
json!({"fillTolerance": 101}),
json!({"strokeTolerance": 100.5}),
json!({"fillTolerance": -1}),
json!({"fillTolerance": "40"}),
json!({"weightTolerance": 1001}),
json!({"opacityTolerance": -0.5}),
json!({"fillColor": "yes"}),
json!({"fillTolerance": null}),
json!({"strokeColor": null}),
json!({"reset": "yes", "fillColor": false}),
json!({"reset": true, "fillTolerance": 101}),
json!({"fillColor": false, "strokeTolerance": 101}),
] {
let e = s.execute("magicWand.set", &bad_value).unwrap_err().to_string();
assert!(e.contains("magicWand.set"), "{bad_value}: {e}");
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap(), before, "{bad_value} changed the settings");
}
assert!(s.execute("magicWand.set", &json!({"fillTolerance": 101})).unwrap_err().to_string().contains("from 0 to 100"));
assert_eq!(s.execute("magicWand.set", &json!({"fillTolerance": 100})).unwrap()["fillTolerance"], 100.0);
// An omitted value keeps its setting.
assert_eq!(s.execute("magicWand.set", &json!({"strokeColor": true})).unwrap()["strokeTolerance"], 50.0);
}
#[test]
fn a_larger_rgb_tolerance_applies_as_100_in_a_cmyk_document_and_comes_back() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
s.execute("magicWand.set", &json!({"fillTolerance": 200, "strokeTolerance": 60})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap();
let o = s.execute("magicWand.options", &json!({})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(100.0), Some(60.0)));
// Setting another field does not overwrite the stored fill tolerance.
assert_eq!(s.execute("magicWand.set", &json!({"opacity": true})).unwrap()["fillTolerance"], 100.0);
// 100 applies: two colors 100 points apart in one channel match, 100 apart in two do not.
let none = cmyk(0.0, 0.0, 0.0, 0.0);
let a = painted(&mut s, 0.0, cmyk(0.0, 0.0, 0.0, 0.0), none.clone());
let b = painted(&mut s, 20.0, cmyk(1.0, 0.0, 0.0, 0.0), none.clone());
let c = painted(&mut s, 40.0, cmyk(1.0, 1.0, 0.0, 0.0), none);
s.execute("magicWand.set", &json!({"opacity": false})).unwrap();
s.execute("select.magicWand", &json!({"id": a})).unwrap();
assert_eq!(selected(&s), [a, b]);
assert!(!selected(&s).contains(&c));
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.execute("magicWand.options", &json!({})).unwrap()["fillTolerance"], 200.0);
// Reset gives 32 in either mode.
s.execute("document.activate", &json!({"index": 1})).unwrap();
let o = s.execute("magicWand.set", &json!({"reset": true})).unwrap();
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
}
#[test]
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
let mut s = Session::new();
+66
View File
@@ -149,6 +149,72 @@ fn a_shape_tool_turns_the_shape_from_just_outside_a_corner() {
assert_eq!(angle(&s, id), 0.0, "rounding does not turn it");
}
/// How many objects the first layer holds.
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers[0].children().map(|c| c.len()).unwrap_or_default()
}
/// Feed the pointer events `(kind, x, y, backtick held)` to the active tool, with no modifier.
fn quote_gesture(s: &mut Session, events: &[(PointerKind, f64, f64, bool)]) {
for (k, x, y, held) in events {
s.pointer(&PointerEvent { backquote: *held, ..PointerEvent::new(*k, *x, *y) }, view()).unwrap();
}
}
/// A Rectangle tool drag from (50, 50) with Backtick held from (100, 100) to (140, 100), let go
/// before (160, 120), all moved by `o` along both axes: two copies, 70 × 50 and 90 × 50 pt, and
/// the 110 × 70 pt rectangle it ends with. With `release`, the drag is let go; without, it is
/// still in progress.
fn trail(s: &mut Session, o: f64, release: bool) {
use PointerKind::{Down, Drag, Up};
quote_gesture(
s,
&[
(Down, 50.0 + o, 50.0 + o, false),
(Drag, 100.0 + o, 100.0 + o, true),
(Drag, 120.0 + o, 100.0 + o, true),
(Drag, 140.0 + o, 100.0 + o, true),
],
);
quote_gesture(s, &[(Drag, 160.0 + o, 120.0 + o, false)]);
if release {
quote_gesture(s, &[(Up, 160.0 + o, 120.0 + o, false)]);
}
}
/// The sizes of the first layer's objects, back to front.
fn sizes(s: &Session) -> Vec<(f64, f64)> {
let ids: Vec<NodeId> = s.doc().unwrap().doc.layers[0].children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default();
ids.into_iter().map(|id| bounds(s, id)).map(|r| (r.width(), r.height())).collect()
}
/// Backtick held while a rectangle is dragged out leaves copies of it along the drag: each its own
/// object, and the release keeps them with the last rectangle as one undo step, with Real-time
/// Drawing and Editing on or off. Escape takes the copies back with the shape being drawn.
#[test]
fn a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step() {
for real_time in [true, false] {
let mut s = new_doc();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap();
s.select_tool("rectangle", view()).unwrap();
let steps = undo_steps(&s);
trail(&mut s, 0.0, true);
assert_eq!(sizes(&s), vec![(70.0, 50.0), (90.0, 50.0), (110.0, 70.0)], "real time {real_time}");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s), 0, "Undo takes all three back");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(objects(&s), 3, "Redo puts all three back");
// Escape takes back the copies and the shape being drawn, away from the selection.
let steps = undo_steps(&s);
trail(&mut s, 200.0, false);
s.tool_key(ToolKey::Escape, NONE, view()).unwrap();
quote_gesture(&mut s, &[(PointerKind::Up, 360.0, 320.0, false)]);
assert_eq!(objects(&s), 3, "real time {real_time}: nothing new");
assert_eq!(undo_steps(&s), steps, "no step");
}
}
/// The Selection tool takes the centre point of an unfilled shape too: a drag there moves it
/// instead of starting a marquee.
#[test]
+27 -1
View File
@@ -2888,6 +2888,32 @@ proptest! {
paste_from_elsewhere("clipboard.importEps", json!({"dataBase64": vectorcraft_format::base64_encode(ps.as_bytes())}))?;
}
/// Any bytes read by `readhexstring` or `readline` into strings of any length, from the
/// program's own file, through a filter decoded when first read, or from a file being run:
/// read as data, or as an error.
#[test]
fn eps_readhexstring_and_readline_data_never_panic(
data in prop::collection::vec(prop::sample::select(vec![b'0', b'9', b'a', b'F', b'g', b' ', b'\t', b'\r', b'\n', b'>', b'%', b'(', 0u8, 0xff]), 0..300),
len in 0usize..40,
line in any::<bool>(),
source in 0usize..3,
) {
let op = if line { "readline" } else { "readhexstring" };
let file = if source == 1 { "currentfile /ASCIIHexDecode filter" } else { "currentfile" };
let reads = format!("/s {len} string def /f {file} def 30 {{ f s {op} pop pop }} repeat");
let mut bytes = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
if source == 2 {
bytes.extend_from_slice(format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nendstream\nshowpage\n");
} else {
bytes.extend_from_slice(format!("{reads}\n").as_bytes());
bytes.extend_from_slice(&data);
bytes.extend_from_slice(b"\nshowpage\n");
}
survive("readhexstring and readline data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?;
}
/// Damaged or hostile CMYK images (a CMYK JPEG, an image with a key color): read as images,
/// or as an error.
#[test]
@@ -3133,7 +3159,7 @@ fn arb_ps_token() -> impl Strategy<Value = String> {
"gsave", "grestore", "save", "restore", "concat", "translate", "scale", "rotate", "setlinewidth", "setdash", "setgray",
"setrgbcolor", "setcmykcolor", "sethsbcolor", "setcolorspace", "setcolor", "setpattern", "makepattern", "shfill", "arc", "arcn",
"arct", "arcto", "rectfill", "rectclip", "rectstroke", "image", "imagemask", "colorimage", "currentfile", "filter",
"readhexstring", "readstring", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"readhexstring", "readstring", "readline", "show", "stringwidth", "charpath", "findfont", "scalefont", "makefont", "setfont", "selectfont",
"def", "bind", "load", "dup", "exch", "pop", "roll", "index", "copy", "for", "repeat", "loop", "exit", "if", "ifelse", "exec",
"stopped", "begin", "end", "dict", "array", "string", "get", "put", "getinterval", "putinterval", "aload", "astore", "forall",
"[", "]", "<<", ">>", "{", "}", "matrix", "currentmatrix", "setmatrix", "transform", "itransform", "invertmatrix", "pathbbox",
+2
View File
@@ -68,6 +68,8 @@ mod tests_images;
#[cfg(test)]
mod tests_native;
#[cfg(test)]
mod tests_reads;
#[cfg(test)]
mod tests_type1;
#[cfg(test)]
mod tests_type42;
+60 -42
View File
@@ -31,6 +31,7 @@ pub(super) enum Source {
}
impl Interp<'_> {
#[allow(clippy::cognitive_complexity)] // One arm for each file operator, most of them a few lines.
pub fn data_op(&mut self, op: Op) -> Res {
use Op::*;
match op {
@@ -50,23 +51,7 @@ impl Interp<'_> {
ReadLine => {
let s = self.pop_str()?;
let Obj::File { stream: f, .. } = self.pop()? else { return ps_err("typecheck", "") };
let n = s.len();
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match self.read(&f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
self.skip_lf(&f);
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
let (line, ended) = self.read_line(&f, s.len())?;
self.fill(s, &line)?;
self.push(Obj::Bool(ended))?;
}
@@ -219,38 +204,71 @@ impl Interp<'_> {
})
}
/// After `readline` consumes CR, consume only an immediately following LF. PostScript
/// treats CR/LF as one line ending (PLRM §3.8); raw reads must keep every other byte.
/// The preceding `read` has already materialized any pending filter.
fn skip_lf(&mut self, f: &Rc<RefCell<Stream>>) {
match &mut *f.borrow_mut() {
/// Run `scan` over the bytes left in file `f`, in one slice, and consume as many of them as
/// it says it used. A file still pending after `materialize` has no bytes left.
fn scan<T>(&mut self, f: &Rc<RefCell<Stream>>, scan: impl FnOnce(&[u8]) -> (T, usize)) -> Res<T> {
self.materialize(f)?;
Ok(match &mut *f.borrow_mut() {
Stream::Current => {
if self.lex.rest().first() == Some(&b'\n') {
self.lex.advance(1);
}
let (found, used) = scan(self.lex.data());
self.lex.advance(used);
found
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
let start = (*pos).min(data.len());
let (found, used) = scan(data.get(start..).unwrap_or_default());
*pos = start.saturating_add(used).min(data.len());
found
}
Stream::Pending { .. } => {}
}
Stream::Pending { .. } => scan(&[]).0,
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped).
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = self.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
/// `readline` from `f` into a string of `n` bytes: the line, and whether it ended at a line
/// ending or at the end of the data. The line ending is consumed and left out of the line.
/// CR LF is one line ending (PLRM §3.8), and a lone CR leaves the byte after it unread. A
/// line that fills the string leaves the bytes after it unread, a line ending included.
pub(in super::super) fn read_line(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<(Vec<u8>, bool)> {
if n == 0 {
return Ok((vec![], false));
}
Ok(out)
self.scan(f, |data| {
let room = data.get(..n).unwrap_or(data);
match room.iter().position(|b| matches!(b, b'\n' | b'\r')) {
Some(i) => {
let crlf = room.get(i) == Some(&b'\r') && data.get(i + 1) == Some(&b'\n');
((room.get(..i).unwrap_or_default().to_vec(), true), i + 1 + usize::from(crlf))
}
None if room.len() == n => ((room.to_vec(), false), n),
None => ((room.to_vec(), true), room.len()),
}
})
}
/// Up to `n` bytes read as hexadecimal digits from `f` (other characters skipped). The read
/// stops at the digit that completes the `n`th byte and leaves what follows unread. A lone
/// digit at the end of the data gives no byte.
pub(in super::super) fn read_hex(&mut self, f: &Rc<RefCell<Stream>>, n: usize) -> Res<Vec<u8>> {
if n == 0 {
return Ok(vec![]);
}
self.scan(f, |data| {
let mut out = Vec::with_capacity(n.min(data.len() / 2));
let mut high: Option<u8> = None;
let mut used = 0;
for &b in data {
if out.len() == n {
break;
}
used += 1;
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
(out, used)
})
}
/// Skip the whitespace and the `>` that end hexadecimal data in `f`, if a `>` is next: the
+17
View File
@@ -106,6 +106,23 @@ fn image_data_comes_from_the_file_being_run() {
);
}
/// An image whose procedure reads its rows with `readhexstring` comes out with the same pixels as
/// the same samples given as one hexadecimal string, with the digits broken by CR LF, LF, tabs,
/// spaces and characters that are not digits, read from the program's own file and from a file
/// being run.
#[test]
fn hex_rows_read_by_a_procedure_match_a_hexadecimal_string() {
let rgb: Vec<u8> = (0..36u32).map(|i| (i * 37 % 256) as u8).collect();
let digits = hex(&rgb);
let breaks = ["\r\n", "\n", "\t", " z", "%"];
let broken: String = digits.as_bytes().chunks(5).zip(breaks.iter().cycle()).map(|(d, b)| format!("{}{b}", String::from_utf8_lossy(d))).collect();
let want = pixels(&read(&format!("10 10 scale 4 3 8 [4 0 0 -3 0 3] <{digits}> false 3 colorimage")), 4, 3);
assert_eq!(want, rgb.chunks(3).map(|p| [p[0], p[1], p[2], 255]).collect::<Vec<_>>());
let image = "10 10 scale 4 3 8 [4 0 0 -3 0 3] {currentfile 12 string readhexstring pop} false 3 colorimage";
assert_eq!(pixels(&read(&format!("{image}\r\n{broken}\n")), 4, 3), want);
assert_eq!(pixels(&read(&format!("currentfile 0 (endstream) /SubFileDecode filter cvx exec\n{image}\n{broken}\nendstream\n")), 4, 3), want);
}
/// A filter waits until it is first read, then reads the file it was made over, wherever the
/// program runs by then: one over the program's own file, read in a file being run, and one over
/// a file being run, read in a file that one runs.
+359
View File
@@ -0,0 +1,359 @@
//! `readhexstring` and `readline` (PLRM 3rd ed., §8.2) read the data left in a file in one pass.
//! The tests run the one-pass readers next to reference readers that take one byte per call, on the
//! same data in the same interpreter state: the program's own file after the whitespace that ends
//! the last token, a decoded buffer read from its start or part way in, and a filter decoded when it
//! is first read. The bytes, the result or error, and every byte left unread must agree.
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{Duration, Instant};
use vectorcraft_doc::Document;
use vectorcraft_geom::{Affine, Rect};
use super::data::Stream;
use super::graphics::{GState, Out};
use super::interp::Interp;
use super::obj::{Obj, Res};
type File = Rc<RefCell<Stream>>;
/// Bytes as hexadecimal digits.
fn hex(data: &[u8]) -> String {
data.iter().map(|b| format!("{b:02x}")).collect()
}
/// An interpreter that has run `src` up to its `quit`, and the file object the program left on the
/// operand stack. What follows `quit` in `src` is still unread.
fn file_after(src: &[u8]) -> (Interp<'_>, File) {
let mut doc = Document::new(100.0, 100.0);
doc.layers.clear();
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
let Ok(Obj::File { stream, .. }) = it.pop() else { panic!("no file on the stack: {}", String::from_utf8_lossy(src)) };
(it, stream)
}
/// The reference `readline`: one byte per call, a CR followed by an LF ending the line once.
fn line_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
let mut line = vec![];
let mut ended = false;
while line.len() < n {
match it.read(f, 1)?.first() {
Some(b'\n') | None => {
ended = true;
break;
}
Some(b'\r') => {
match &mut *f.borrow_mut() {
Stream::Current => {
if it.lex.rest().first() == Some(&b'\n') {
it.lex.advance(1);
}
}
Stream::Buf { data, pos, .. } => {
if data.get(*pos) == Some(&b'\n') {
*pos += 1;
}
}
Stream::Pending { .. } => {}
}
ended = true;
break;
}
Some(b) => line.push(*b),
}
}
Ok((line, ended))
}
/// The reference `readhexstring`: one byte per call, characters that are not hexadecimal digits
/// skipped.
fn hex_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let mut out = Vec::with_capacity(n);
let mut high: Option<u8> = None;
while out.len() < n {
let Some(&b) = it.read(f, 1)?.first() else { break };
let Some(v) = char::from(b).to_digit(16) else { continue };
match high.take() {
Some(h) => out.push(h << 4 | v as u8),
None => high = Some(v as u8),
}
}
Ok(out)
}
fn line_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<(Vec<u8>, bool)> {
it.read_line(f, n)
}
fn hex_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
it.read_hex(f, n)
}
/// Hexadecimal data as CID `StartData` reads it: the digits, then a closing `>` if one is next.
fn hex_and_end_one_pass(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = it.read_hex(f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
fn hex_and_end_by_bytes(it: &mut Interp, f: &File, n: usize) -> Res<Vec<u8>> {
let d = hex_by_bytes(it, f, n)?;
it.skip_hex_end(f)?;
Ok(d)
}
/// How the program reaches the data.
#[derive(Clone, Copy, Debug)]
enum Form {
/// `currentfile`, with this whitespace after the token before the data.
Current(&'static [u8]),
/// A buffer decoded at once, with this many bytes of it read before the data.
Buf(usize),
/// An `ASCIIHexDecode` filter over `currentfile`, decoded when it is first read, with this
/// whitespace after the token before the digits.
Pending(&'static [u8]),
}
const FORMS: [Form; 13] = [
Form::Current(b" "),
Form::Current(b"\n"),
Form::Current(b"\r"),
Form::Current(b"\r\n"),
Form::Current(b"\r\r\n"),
Form::Current(b"\n\r"),
Form::Current(b"\t\t"),
Form::Buf(0),
Form::Buf(2),
Form::Buf(3),
Form::Pending(b"\n"),
Form::Pending(b"\r\n"),
Form::Pending(b" "),
];
/// A program that leaves a file over `data` on the operand stack, in form `form`.
fn program(form: Form, data: &[u8]) -> Vec<u8> {
match form {
Form::Current(lead) => [b"currentfile quit".as_slice(), lead, data].concat(),
Form::Buf(0) => format!("<{}> /ReusableStreamDecode filter quit", hex(data)).into_bytes(),
Form::Buf(skip) => {
let before = b"\r\n\r".get(..skip).unwrap_or(b"\r\n\r".as_slice());
format!("<{}{}> /ReusableStreamDecode filter dup {skip} string readstring pop pop quit", hex(before), hex(data)).into_bytes()
}
Form::Pending(lead) => [b"currentfile /ASCIIHexDecode filter quit".as_slice(), lead, hex(data).as_bytes(), b"> tail"].concat(),
}
}
type Reader<T> = fn(&mut Interp, &File, usize) -> Res<T>;
/// Read `data` in `form` with `one_pass` and with `by_bytes` in two interpreters in the same state,
/// and check that they agree on the result and on everything left to read.
fn agree<T: PartialEq + Debug>(form: Form, data: &[u8], n: usize, one_pass: Reader<T>, by_bytes: Reader<T>) {
let src = program(form, data);
let (mut a, fa) = file_after(&src);
let (mut b, fb) = file_after(&src);
let at = || format!("{form:?}, {:?}, n = {n}", String::from_utf8_lossy(data));
assert_eq!(one_pass(&mut a, &fa, n), by_bytes(&mut b, &fb, n), "result: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left unread: {}", at());
assert_eq!(a.read(&fa, usize::MAX), b.read(&fb, usize::MAX), "file left unread: {}", at());
assert_eq!(a.lex.rest(), b.lex.rest(), "program left after the file: {}", at());
a.release();
b.release();
}
/// A fixed sequence of pseudo-random numbers (xorshift), so a failure repeats.
struct Rng(u64);
impl Rng {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % n.max(1) as u64) as usize
}
}
/// `chosen`, then `count` strings of up to 24 bytes from `alphabet`.
fn samples(chosen: &[&[u8]], alphabet: &[u8], count: usize, rng: &mut Rng) -> Vec<Vec<u8>> {
let random = (0..count).map(|_| {
let len = rng.below(25);
(0..len).filter_map(|_| alphabet.get(rng.below(alphabet.len())).copied()).collect()
});
chosen.iter().map(|s| s.to_vec()).chain(random).collect()
}
/// String lengths to read `data` with: none, one, past its end, exactly its length and one more,
/// and one at random.
fn lengths(data: &[u8], rng: &mut Rng) -> [usize; 6] {
[0, 1, 3, data.len(), data.len() + 1, rng.below(data.len() + 3)]
}
#[test]
fn readline_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let chosen: [&[u8]; 16] = [
b"",
b"\n",
b"\r",
b"\r\n",
b"\n\r",
b"\r\r\n",
b"abc",
b"abc\n",
b"abc\r",
b"abc\rX",
b"abc\r\nX",
b"abc\n\nX",
b"abcdefgh\r\nX",
b"abcdefgh\nX",
b"a\0b\xff\rX",
b"abc\r\n",
];
for data in samples(&chosen, b"ab\r\n\r\n x\0\xff", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, line_one_pass, line_by_bytes);
}
}
}
}
#[test]
fn readhexstring_reads_in_one_pass_as_byte_by_byte() {
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let chosen: [&[u8]; 14] = [
b"",
b"0",
b"a",
b"0a",
b"0a1",
b"0 a\r\n1b>X",
b"zz0g1",
b"ff\r\n00\nAA",
b"0a1b2c3d",
b"0a1b\r\n2c>",
b"\r\n0a",
b"a b c d e",
b"0a>",
b"0a \r\n >X",
];
for data in samples(&chosen, b"0123456789abcdefABCDEFg \r\n\t>z%", 40, &mut rng) {
for form in FORMS {
for n in lengths(&data, &mut rng) {
agree(form, &data, n, hex_one_pass, hex_by_bytes);
agree(form, &data, n, hex_and_end_one_pass, hex_and_end_by_bytes);
}
}
}
}
/// `readline` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `line` and `ended`
/// and leaves `left` unread.
fn line_case(data: &[u8], n: usize, line: &[u8], ended: bool, left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_line(&f, n), Ok((line.to_vec(), ended)), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.read(&f, usize::MAX), Ok(left.to_vec()), "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// `readhexstring` of `data` into `n` bytes, after `currentfile` and a CR LF, gives `bytes` and
/// leaves `left` unread in the program.
fn hex_case(data: &[u8], n: usize, bytes: &[u8], left: &[u8]) {
let src = program(Form::Current(b"\r\n"), data);
let (mut it, f) = file_after(&src);
assert_eq!(it.read_hex(&f, n), Ok(bytes.to_vec()), "{:?}", String::from_utf8_lossy(data));
assert_eq!(it.lex.rest(), left, "{:?}", String::from_utf8_lossy(data));
it.release();
}
/// The results the one-pass readers give at the edges of the data, stated directly.
#[test]
fn one_pass_reads_stop_where_their_data_ends() {
// A CR LF ends one line; a lone CR leaves the next byte unread.
line_case(b"ab\r\nX", 8, b"ab", true, b"X");
line_case(b"ab\rX", 8, b"ab", true, b"X");
line_case(b"ab\nX", 8, b"ab", true, b"X");
// A line that fills the string leaves its line ending unread.
line_case(b"abcd\nX", 4, b"abcd", false, b"\nX");
line_case(b"abc\r\nX", 3, b"abc", false, b"\r\nX");
// The end of the data ends the line.
line_case(b"ab", 8, b"ab", true, b"");
line_case(b"", 8, b"", true, b"");
// The read stops on the digit that completes the last byte.
hex_case(b"0a\r\n1b>X", 2, &[0x0a, 0x1b], b">X");
// Characters that are not digits are skipped.
hex_case(b"z0 g\ta%", 1, &[0x0a], b"%");
// A lone digit at the end of the data gives no byte.
hex_case(b"0a1", 2, &[0x0a], b"");
hex_case(b"\r\n", 2, &[], b"");
// No byte to read takes nothing, not even the whitespace after the token.
hex_case(b"0a", 0, &[], b"\r\n0a");
}
/// The median of `runs`.
fn median(runs: &[Duration]) -> Duration {
let mut sorted = runs.to_vec();
sorted.sort();
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
}
/// Read all of `src`'s data with `reader` in strings of `n` bytes, `calls` times, and how long it
/// took. The interpreter is made before the clock starts.
fn timed<T>(src: &[u8], reader: Reader<T>, n: usize, calls: usize) -> (Vec<T>, Duration) {
let (mut it, f) = file_after(src);
let start = Instant::now();
let got: Vec<T> = (0..calls).map(|_| reader(&mut it, &f, n).unwrap_or_else(|e| panic!("{e:?}"))).collect();
let took = start.elapsed();
it.release();
(got, took)
}
/// Time both readers on `src` in 7 runs, alternating which goes first, check that they read the
/// same, and print every run and the medians.
fn compare<T: PartialEq>(what: &str, src: &[u8], one_pass: Reader<T>, by_bytes: Reader<T>, n: usize, calls: usize) {
let (mut old, mut new) = (vec![], vec![]);
for run in 0..7 {
let order: [bool; 2] = if run % 2 == 0 { [false, true] } else { [true, false] };
let mut got = vec![];
for one in order {
let (read, took) = timed(src, if one { one_pass } else { by_bytes }, n, calls);
if one {
new.push(took)
} else {
old.push(took)
}
got.push(read);
}
assert!(got.first() == got.get(1), "{what}: the readers differ");
}
let ms = |d: &Duration| format!("{:.1}", d.as_secs_f64() * 1000.0);
println!("{what}: {} bytes of data, {calls} calls of {n} bytes", src.len());
println!(" byte by byte, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
println!(" one pass, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
let (o, w) = (median(&old), median(&new));
println!(" median: byte by byte {} ms, one pass {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
}
/// Times the one-pass readers against the byte-at-a-time reference readers on the same data in one
/// process: the hexadecimal samples of a 1000 × 1000 RGB image in lines of 64 digits, read a row
/// of 3,000 bytes at a time, and 200,000 lines of 40 bytes read by `readline` into an 80-byte
/// string. Run it in release:
/// `cargo test --release -p vectorcraft-eps --lib tests_reads::one_pass_reads_timed -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn one_pass_reads_timed() {
let rgb: Vec<u8> = (0..3_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
let digits = hex(&rgb);
let mut data = Vec::with_capacity(digits.len() + digits.len() / 64 + 1);
for line in digits.as_bytes().chunks(64) {
data.extend_from_slice(line);
data.push(b'\n');
}
compare("readhexstring", &program(Form::Current(b"\n"), &data), hex_one_pass, hex_by_bytes, 3_000, 1_000);
let lines: Vec<u8> = (0..200_000).flat_map(|i| format!("{:<39}\n", format!("line {i}")).into_bytes()).collect();
compare("readline", &program(Form::Current(b"\n"), &lines), line_one_pass, line_by_bytes, 80, 200_000);
}
+2 -2
View File
@@ -209,7 +209,7 @@ pub fn tool_definitions() -> Vec<Value> {
"x": num("Document x (pt)"),
"y": num("Document y (pt)"),
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
"pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on, and the pressure the Paintbrush records"),
"tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"),
"tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"),
@@ -218,7 +218,7 @@ pub fn tool_definitions() -> Vec<Value> {
}), &["kind", "x", "y"]),
},
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"},
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint; Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment drags leave copies of the shape being drawn"},
}),
&["events"],
),
+146 -22
View File
@@ -77,7 +77,10 @@ impl Outline {
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
let [a, b, c, d, e, f] = unit.as_coeffs();
let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm {
// The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may
// belong to a map with no area. An ellipse whose determinant is larger is measured
// exactly.
if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm {
return Err(OutlineError::Empty);
}
Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] })
@@ -153,6 +156,16 @@ impl Outline {
if segments.iter().any(|s| bends_against(s, sign)) {
return Err(OutlineError::NotConvex);
}
// A corner can also turn inward between two of the points: each join is checked by the
// directions the segments leave and reach it in. Segments of no length are passed over.
let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot());
let ends: Vec<(Vec2, Vec2)> = segments
.iter()
.filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])))
.collect();
if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) {
return Err(OutlineError::NotConvex);
}
let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point();
if !center.x.is_finite() || !center.y.is_finite() {
return Err(OutlineError::Empty);
@@ -246,7 +259,7 @@ impl Outline {
}
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
fn size(&self) -> f64 {
pub fn size(&self) -> f64 {
match self {
Outline::Ellipse { m, .. } => {
let [a, b, c, d] = *m;
@@ -270,11 +283,13 @@ impl Outline {
}
}
/// The points of the outline on the line `p · n = h`, its support value: the point where
/// `p · n` is largest, and the ends of any straight side along the line. Another point counts
/// when it lies within `tol` of the line plus `slope` times its distance from that largest
/// point, where `slope` is how far off the normal's angle may be.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec<Point> {
/// The points of the outline on the line `p · n = h`, its support value, which is reached on
/// segment `at`: the point where `p · n` is largest, and the ends of any straight side along
/// the line. Another point counts when it lies within `tol` of the line plus `slope` times its
/// distance from that largest point, where `slope` is how far off the normal's angle may be.
/// On a convex outline the points that count form one run around the largest one, so the
/// segments are measured from `at` outward both ways until a segment's end does not count.
fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec<Point> {
match self {
Outline::Ellipse { center, m: [a, b, c, d] } => {
let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y);
@@ -282,9 +297,25 @@ impl Outline {
vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)]
}
Outline::Convex { segments, .. } => {
let len = segments.len();
let mut all = vec![];
for s in segments {
each_extreme(s, n, |p, v| all.push((p, v)));
let Some(first) = segments.get(at % len.max(1)) else { return vec![] };
each_extreme(first, n, |p, v| all.push((p, v)));
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot();
let mut ahead = 0;
for j in 1..len {
match segments.get((at + j) % len) {
Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
ahead = j;
}
for j in 1..len - ahead {
match segments.get((at + len - j) % len) {
Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))),
_ => break,
}
}
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
@@ -293,8 +324,6 @@ impl Outline {
}
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product
/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared
/// with the segment's control polygon length squared.
@@ -321,7 +350,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool {
low < -1e-9 * scale
}
#[cfg(test)]
thread_local! {
/// How many times [`each_extreme`] has measured a segment on this thread, for the tests.
static EXTREMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where
/// the curve runs square to `n`) and the value there.
fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) {
#[cfg(test)]
EXTREMES.with(|n| n.set(n.get() + 1));
let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n));
f(s.p0, v0);
f(s.p3, v3);
@@ -396,10 +435,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincid
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb });
let mut out = Vec::with_capacity(external.len() + internal.len());
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
for root in list {
let t = tangent_at(a, b, kind, dir(root.angle), root.double, size);
let t = tangent_at(&a, &b, kind, root.angle, root.double, size);
out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t });
}
}
@@ -414,21 +454,47 @@ struct Root {
double: bool,
}
/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value,
/// and `b` on the same side (external) or the other side (internal). `double` when the outlines
/// touch there.
fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent {
/// An outline with the segment it is touched on at each sampled normal angle.
struct Hinted<'a> {
o: &'a Outline,
at: &'a [f64],
hints: &'a [usize],
}
impl Hinted<'_> {
/// The support value at the normal angle `angle` and the segment it is reached on, walking on
/// from the segment of the sample at or before `angle`.
fn support(&self, angle: f64) -> (f64, usize) {
let angle = angle.rem_euclid(TAU);
// Before the first sample, the last one (taken 2π back) comes before `angle`.
let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1));
self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0))
}
}
/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's
/// value, and `b` on the same side (external) or the other side (internal). `double` when the
/// outlines touch there.
fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent {
let n = dir(angle);
// The rounding allowed in `p · n` grows with each outline's own size and its distance from the
// origin.
let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size());
let (tol_a, tol_b) = (rounding(a), rounding(b));
let (tol_a, tol_b) = (rounding(a.o), rounding(b.o));
// Bisection finds a simple root's angle to about the rounding of the support values; the
// golden-section search finds a double root's to about 1e-8 radians.
let slope = if double { 1e-7 } else { 1e-10 };
let ha = a.support(n);
let (on_a, on_b) = match kind {
TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)),
TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)),
let (ha, sa) = a.support(angle);
let on_a = a.o.touching(n, ha, tol_a, slope, sa);
let on_b = match kind {
TangentKind::External => {
let (hb, sb) = b.support(angle);
b.o.touching(n, hb, tol_b, slope, sb)
}
TangentKind::Internal => {
let (hb, sb) = b.support(angle + TAU / 2.0);
b.o.touching(-n, hb, tol_b, slope, sb)
}
};
// Positions along the line, which runs square to `n` through `n * ha`.
let t = Vec2::new(-n.y, n.x);
@@ -441,7 +507,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool
// stand a little apart.
let (from, to) = if double && hi - lo <= 1e-6 * size {
// Touching at one point: the narrower outline's width along the line, centered there.
let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min);
let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min);
let mid = (lo + hi) / 2.0;
(mid - width / 2.0, mid + width / 2.0)
} else if mean(&on_a) <= mean(&on_b) {
@@ -575,6 +641,8 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use kurbo::Rect;
use vectorcraft_geom::shapes;
@@ -850,6 +918,53 @@ mod tests {
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn each_tangent_measures_only_the_segments_near_where_it_touches() {
// Two regular 2,000-gons about one center, one turned half a step: 4,000 external
// tangents. Measuring every segment of both outlines for every tangent takes about 8,000
// measurements per tangent.
let sides = 2_000;
let gon = |turn: f64| {
let pts: Vec<Point> = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect();
SubPath::polyline(&pts, true)
};
let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap());
EXTREMES.with(|c| c.set(0));
let all = common_tangents(&a, &b).unwrap();
let calls = EXTREMES.with(Cell::get);
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides);
assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len());
let r = 100.0 * (TAU / (4 * sides) as f64).sin();
assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first());
}
#[test]
fn a_very_thin_ellipse_is_measured_exactly() {
// Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned
// 30 degrees: the tangents run from the ellipse's tips to the circle.
for deg in [0.0, 30.0] {
let turn = Affine::rotate(f64::to_radians(deg));
let thin = turn * Affine::scale_non_uniform(1e6, 1e-7);
let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]);
let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap();
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}");
assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}");
let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000));
for t in &all {
check_against_samples(t, &sa, &sb, 1e-3);
// The end on the ellipse, taken back to the unturned figure.
let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to);
let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to };
assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}");
}
}
// A determinant a few times its rounding is taken; one lost in the rounding of the map's
// entries is still refused.
assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok());
assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty));
}
#[test]
fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() {
// p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is
@@ -877,6 +992,15 @@ mod tests {
bp.close_path();
let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex));
// A triangle whose first side is a cubic that leaves its start a little the wrong way: the
// corner there turns inward, though the checked points and the curve itself turn one way.
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((0.0, 0.0));
bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0));
bp.line_to((50.0, 100.0));
bp.close_path();
let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone();
assert_eq!(Outline::convex(&notch).err(), Some(OutlineError::NotConvex));
// A square traced twice around winds around twice.
let twice: Vec<Point> = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect();
assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex));
+3 -1
View File
@@ -153,7 +153,9 @@ impl FontDb {
/// neither, as [`FontTraits`] tells), then the others, each group nearest first by
/// [`FontLikeness::distance`](super::FontLikeness::distance) of their
/// [`family_traits`](Self::family_traits), a family of another kind ([`FontTraits::class`])
/// counting 2 further. Families equally far keep their order in `families`. Reads no font
/// counting 2 further. A family that shares none of those numbers with `family` comes after
/// every family that shares one in its group. Families equally far keep their order in
/// `families`. Reads no font
/// file, as `family_traits` does not.
pub fn similar_families(&self, family: &str, families: &[String]) -> Vec<String> {
let base = self.family_traits(family);
+10 -2
View File
@@ -174,11 +174,15 @@ impl FontLikeness {
/// How unlike two faces look: 0 for faces whose numbers are all the same, more the further
/// apart they are. A number one of the faces does not give is left out. PANOSE digits are
/// compared only between faces of the same PANOSE family kind; faces of different kinds count
/// 3 apart. The weights and scales are VectorCraft's own.
/// 3 apart. Faces that share no number to compare (neither a PANOSE family kind, a weight, a
/// width, a height, an average width nor an italic angle) are `f32::INFINITY` apart, further
/// than any faces that share one. The weights and scales are VectorCraft's own.
pub fn distance(&self, other: &Self) -> f32 {
let mut d = 0.0;
let mut compared = false;
let (kind, other_kind) = (self.panose[0], other.panose[0]);
if kind > 1 && other_kind > 1 {
compared = true;
if kind == other_kind {
for (a, b) in self.panose.iter().zip(&other.panose).skip(1) {
if *a > 1 && *b > 1 {
@@ -190,21 +194,25 @@ impl FontLikeness {
}
}
if self.weight != 0 && other.weight != 0 {
compared = true;
d += f32::from(self.weight.abs_diff(other.weight)) / 200.0;
}
if self.width != 0 && other.width != 0 {
compared = true;
d += f32::from(self.width.abs_diff(other.width)) * 0.5;
}
for (a, b, scale) in [(self.x_height, other.x_height, 10.0), (self.cap_height, other.cap_height, 5.0), (self.avg_width, other.avg_width, 8.0)]
{
if a != 0 && b != 0 {
compared = true;
d += f32::from(a.abs_diff(b)) / 1000.0 * scale;
}
}
if let (Some(a), Some(b)) = (self.italic_angle, other.italic_angle) {
compared = true;
d += f32::from(a.abs_diff(b)) / 50.0;
}
d
if compared { d } else { f32::INFINITY }
}
}
+24
View File
@@ -365,6 +365,30 @@ pub fn height_outside_font() -> Option<Vec<u8>> {
heights_font(HEIGHT_OUTSIDE_FAMILY, Some((HEIGHT_OUTSIDE_X, HEIGHT_OUTSIDE_CAP)), false)
}
/// The family of [`numberless_font`].
pub const NUMBERLESS_FAMILY: &str = "Numberlesstest Sans";
/// The bundled Source Sans 3 Regular as family [`NUMBERLESS_FAMILY`], without its OS/2 and `post`
/// tables, so it gives none of the numbers Show Similar Fonts compares faces by. `None` when it
/// can't be built.
pub fn numberless_font() -> Option<Vec<u8>> {
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let full = format!("{NUMBERLESS_FAMILY} Regular");
let postscript = format!("{}-Regular", NUMBERLESS_FAMILY.replace(' ', ""));
let name = name_table(&[(1, NUMBERLESS_FAMILY), (2, "Regular"), (4, &full), (6, &postscript)])?;
let mut builder = FontBuilder::new();
builder.add_raw(Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
if builder.contains(tag) || tag == Tag::new(b"OS/2") || tag == Tag::new(b"post") {
continue;
}
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes().to_vec());
}
Some(builder.build())
}
/// The bundled Source Sans 3 Regular as `family`: with the x height and cap height `heights` in
/// its OS/2 table, else a version 1 OS/2 table, which holds neither; with `base`, the `BASE`
/// table of [`height_font`].
+30 -2
View File
@@ -3,7 +3,9 @@
use skrifa::raw::TableProvider;
use crate::test_fonts::{HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, VARIABLE_FAMILY, height_font, variable_font};
use crate::test_fonts::{
HEIGHT_CAP, HEIGHT_FAMILY, HEIGHT_X, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY, VARIABLE_FAMILY, height_font, numberless_font, variable_font,
};
use crate::*;
/// A database of the bundled fonts and the two copies of Source Sans 3 Regular with and without
@@ -88,8 +90,14 @@ fn likeness_is_a_distance() {
assert_eq!(sans.distance(&serif), serif.distance(&sans), "symmetric");
assert!(sans.distance(&serif) > 0.0 && sans.distance(&mono) > 0.0);
// A number a face does not give is left out, not counted as 0.
assert_eq!(sans.distance(&FontLikeness { x_height: 0, cap_height: 0, ..sans }), 0.0);
// Faces that share no number are further apart than any faces that share one, not alike.
let unknown = FontLikeness::default();
assert_eq!(sans.distance(&unknown), 0.0);
assert_eq!(sans.distance(&unknown), f32::INFINITY);
assert_eq!(unknown.distance(&sans), f32::INFINITY, "symmetric");
assert_eq!(unknown.distance(&unknown), f32::INFINITY);
let weight_only = FontLikeness { weight: 400, ..unknown };
assert_eq!(sans.distance(&weight_only), 0.0, "the weight alone is compared");
let lighter = FontLikeness { weight: 300, ..sans };
assert!((sans.distance(&lighter) - 0.5).abs() < 1e-6, "100 weight units apart");
}
@@ -117,3 +125,23 @@ fn families_are_ordered_by_likeness() {
assert_eq!(without[0], HEIGHTLESS_FAMILY);
assert!(db.similar_families("Source Sans 3", &[]).is_empty());
}
/// A family that gives none of the numbers comes after every family that shares one with the
/// family asked about, instead of first as though it looked the same.
#[test]
fn a_family_without_numbers_comes_after_the_measured_ones() {
let db = db();
assert_eq!(db.add_font(numberless_font().expect("the test font builds")), 1);
assert_eq!(db.family_traits(NUMBERLESS_FAMILY).likeness, FontLikeness::default());
let families = names(&[NUMBERLESS_FAMILY, "JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3"]);
let order = db.similar_families("Source Sans 3", &families);
assert_eq!(order[..2], names(&["Source Sans 3", HEIGHTLESS_FAMILY]), "{order:?}");
assert_eq!(order.last().map(String::as_str), Some(NUMBERLESS_FAMILY), "{order:?}");
// The measured families keep the order they have without it.
let measured: Vec<String> = order.iter().filter(|f| *f != NUMBERLESS_FAMILY).cloned().collect();
assert_eq!(measured, db.similar_families("Source Sans 3", &families[1..]));
// Asked about itself, it comes first even from the end of the list, and the families it shares
// no number with keep their order in the list.
let last = names(&["JetBrains Mono", "Source Serif 4", "Inter", HEIGHTLESS_FAMILY, "Source Sans 3", NUMBERLESS_FAMILY]);
assert_eq!(db.similar_families(NUMBERLESS_FAMILY, &last), families);
}
+88 -2
View File
@@ -9,6 +9,10 @@
//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a
//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]).
//! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed.
//! Backtick (`` ` ``, the grave accent) held while dragging leaves a copy of the shape being drawn
//! every [`COPY_SPACING`] screen points the pointer travels, up to [`MAX_COPIES`] in one drag; the
//! release keeps the copies and the last shape as one undo step
//! (<https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469>).
//!
//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle,
//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at
@@ -38,6 +42,14 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
/// value stop there too.
pub const MAX_CORNER_RADIUS: f64 = 1296.0;
/// How far (screen points) the pointer travels with Backtick held between two copies a shape drag
/// leaves: VectorCraft's own spacing.
pub const COPY_SPACING: f64 = 8.0;
/// The most copies one shape drag with Backtick held leaves, besides the shape it ends with:
/// VectorCraft's own limit.
pub const MAX_COPIES: usize = 128;
/// How far (screen points, along each axis) from a bounding-box handle's centre a shape tool's
/// press scales the selection: half the drawn handle square, which is 6 points wide at the default
/// Selection & Anchor Display › Size 3 and a point wider or narrower per step. The Selection tool
@@ -124,6 +136,12 @@ pub struct ShapeTool {
/// The move of the selection snapped to a point, a guide or the grid at its last step: the
/// arrow turns hollow, as the Selection tool's does.
snapped: bool,
/// The copies the drag has left with Backtick held, oldest first: each shape's command and
/// params as the drag showed it when the copy was left.
copies: Vec<(String, Value)>,
/// While Backtick is held in a drag, the pointer position the next copy is measured from: where
/// the last copy was left, or where the drag first had the key down.
copy_from: Option<Point>,
}
/// The options that keys and Ctrl/Cmd change while a shape is dragged out.
@@ -177,9 +195,56 @@ impl ShapeTool {
guides: vec![],
measure: None,
snapped: false,
copies: vec![],
copy_from: None,
}
}
/// With Backtick `held` at pointer `raw`, leave a copy of the shape the drag shows (`cmd` and
/// `params`) once the pointer is [`COPY_SPACING`] screen points from the last copy, or from
/// where the key was first held. A shape with no width, height or length, one the same as the
/// last copy, and any past [`MAX_COPIES`] are not left. Without the key, the next copy is
/// measured from where it goes down again.
fn leave_copy(&mut self, cx: &ToolContext, raw: Point, held: bool, cmd: &str, params: &Value) {
if !held {
self.copy_from = None;
return;
}
let Some(from) = self.copy_from else {
self.copy_from = Some(raw);
return;
};
let (x, y) = screen_offset(cx, raw - from);
if x.hypot(y) < COPY_SPACING || self.copies.len() >= MAX_COPIES || !draws_something(cmd, params) {
return;
}
self.copy_from = Some(raw);
if self.copies.last().is_some_and(|(c, p)| c == cmd && p == params) {
return;
}
self.copies.push((cmd.to_owned(), params.clone()));
}
/// The preview of the shape `cmd` with `params`: with copies left, a `command.batch` that draws
/// them and then the shape, unless it has no size or is the same as the last copy.
fn preview(&self, cmd: String, params: Value) -> Action {
if self.copies.is_empty() {
return Action::Preview(cmd, params);
}
let step = |c: &str, p: &Value| json!({ "command": c, "params": p });
let mut commands: Vec<Value> = self.copies.iter().map(|(c, p)| step(c, p)).collect();
if draws_something(&cmd, &params) && self.copies.last().is_none_or(|(c, p)| *c != cmd || *p != params) {
commands.push(step(&cmd, &params));
}
Action::Preview("command.batch".into(), json!({ "label": self.label(), "commands": commands }))
}
/// Forget the copies of the drag that ended.
fn clear_copies(&mut self) {
self.copies.clear();
self.copy_from = None;
}
fn drag_options(&self) -> DragOptions {
DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio }
}
@@ -500,6 +565,19 @@ impl ShapeTool {
}
}
/// Does the shape command `cmd` with `params` draw something: a box with a width and a height, a
/// polygon or star with a radius, a line with a length?
fn draws_something(cmd: &str, params: &Value) -> bool {
let n = |k: &str| params.get(k).and_then(Value::as_f64).unwrap_or(0.0);
match cmd {
// The drag gives a polygon or star a radius of at least 0.01 pt, even on its centre.
"shape.polygon" => n("radius") > 0.01,
"shape.star" => n("radius1") > 0.01,
"shape.line" => (n("x2") - n("x1")).hypot(n("y2") - n("y1")) > 0.0,
_ => n("width").abs() > 0.0 && n("height").abs() > 0.0,
}
}
/// The box a drag from `start` to `p` draws (from its centre with Alt, square with Shift),
/// measured along the page axes turned by Constrain Angle `base`: the box in those axes, and the
/// axes (`None` for the page's own: 0° or a whole turn, where the box is on the page exactly).
@@ -597,6 +675,11 @@ impl Tool for ShapeTool {
self.began = false;
self.inner = None;
self.before_drag = None;
self.clear_copies();
// Backtick already held at the press: the copies are measured from there.
if ev.backquote {
self.copy_from = Some(ev.pos);
}
vec![]
}
PointerKind::Drag => {
@@ -653,7 +736,8 @@ impl Tool for ShapeTool {
};
let (a, b) = tangent.unwrap_or((s, ev.pos));
let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle);
out.push(Action::Preview(c, v));
self.leave_copy(cx, raw, ev.backquote, &c, &v);
out.push(self.preview(c, v));
out
}
PointerKind::Up => {
@@ -662,6 +746,7 @@ impl Tool for ShapeTool {
self.tangent_line.clear();
self.inner = None;
self.before_drag = None;
self.clear_copies();
if self.began {
self.began = false;
vec![Action::Commit]
@@ -724,11 +809,12 @@ impl Tool for ShapeTool {
};
if changed {
let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle);
vec![Action::Preview(c, v)]
vec![self.preview(c, v)]
} else if key == ToolKey::Escape {
self.start = None;
self.began = false;
self.inner = None;
self.clear_copies();
if let Some(o) = self.before_drag.take() {
self.restore_drag_options(o);
}
+182
View File
@@ -1372,3 +1372,185 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() {
assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}");
assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow);
}
/// A drag event to `(x, y)` with Backtick held or not.
fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent {
PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) }
}
/// The shapes the last preview in `a` draws, as their commands and params: the steps of a
/// `command.batch`, or the one shape. The bool says whether it was a batch.
fn previewed_shapes(a: &[Action]) -> (bool, Vec<(String, Value)>) {
match a.last() {
Some(Action::Preview(c, v)) if c == "command.batch" => {
assert!(v.get("commands").and_then(Value::as_array).is_some(), "{v}");
let steps = v["commands"].as_array().into_iter().flatten();
(true, steps.map(|s| (s["command"].as_str().unwrap_or_default().to_owned(), s["params"].clone())).collect())
}
Some(Action::Preview(c, v)) => (false, vec![(c.clone(), v.clone())]),
_ => panic!("no preview: {a:?}"),
}
}
/// The widths of the rectangles the last preview in `a` draws, and whether it was a batch.
fn previewed_widths(a: &[Action]) -> (bool, Vec<f64>) {
let (batch, shapes) = previewed_shapes(a);
(batch, shapes.iter().map(|(_, p)| p["width"].as_f64().unwrap_or(f64::NAN)).collect())
}
/// Backtick held while a rectangle is dragged out leaves a copy every 8 screen points the pointer
/// travels from where the key was first held or the last copy was left; the shape being drawn
/// still follows the pointer. A key press without pointer travel leaves none, letting go stops
/// the copies and keeps those left, and pressing it again starts measuring afresh. The release
/// commits once.
#[test]
fn backtick_drag_leaves_copies_of_the_rectangle_being_drawn() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
// The key goes down with the pointer still: no copy.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, true))), (false, vec![40.0]));
// 4 pt of travel is short of the spacing.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(54.0, 30.0, true))), (false, vec![44.0]));
// 10 pt: a copy, the same as the shape shown, so the batch draws it once.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(60.0, 30.0, true))), (true, vec![50.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(70.0, 30.0, true))), (true, vec![50.0, 60.0]));
// 5 pt past the last copy: none left, and the live shape follows.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(75.0, 30.0, true))), (true, vec![50.0, 60.0, 65.0]));
// Let go of the key: the copies stay and no more are left.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(90.0, 30.0, false))), (true, vec![50.0, 60.0, 80.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(120.0, 30.0, false))), (true, vec![50.0, 60.0, 110.0]));
// Pressed again: measured from where it went down.
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(125.0, 30.0, true))), (true, vec![50.0, 60.0, 115.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(135.0, 30.0, true))), (true, vec![50.0, 60.0, 125.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 135.0, 30.0) }), vec![Action::Commit]);
// The next drag starts with no copies.
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(50.0, 30.0, false))), (false, vec![40.0]));
}
/// Backtick already held at the press measures the first copy from the pressed spot: the first
/// drag 10 pt away leaves one, and 5 pt more leaves none.
#[test]
fn backtick_held_at_the_press_measures_copies_from_there() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Down, 0.0, 0.0) });
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(10.0, 10.0, true))), (true, vec![10.0]));
assert_eq!(previewed_widths(&t.pointer(&c, &quote_drag(15.0, 10.0, true))), (true, vec![10.0, 15.0]));
assert_eq!(t.pointer(&c, &PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 15.0, 10.0) }), vec![Action::Commit]);
}
/// Every shape tool leaves copies of its own shape, drawn with the modifiers held when each copy
/// was left: Shift's square stays square, and Alt's from the centre stays centred.
#[test]
fn backtick_drag_leaves_copies_with_every_shape_tool_and_its_modifiers() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
for (id, cmd) in [
("rectangle", "shape.rectangle"),
("roundedRectangle", "shape.rectangle"),
("ellipse", "shape.ellipse"),
("polygon", "shape.polygon"),
("star", "shape.star"),
("lineSegment", "shape.line"),
] {
let mut t = ShapeTool::new(id);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 130.0, true));
t.pointer(&c, &quote_drag(160.0, 130.0, true));
let (batch, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(180.0, 140.0, true)));
assert!(batch, "{id}");
assert_eq!(shapes.len(), 2, "{id}: two copies, the second the shape shown: {shapes:?}");
assert!(shapes.iter().all(|(c, _)| c == cmd), "{id}: {shapes:?}");
assert_ne!(shapes[0].1, shapes[1].1, "{id}: each copy as the drag showed it then");
}
// Shift and Alt: each copy is the square drawn from the centre at that moment.
let shift_alt = Mods { shift: true, alt: true, ..Default::default() };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(130.0, 120.0, true).with_mods(shift_alt));
let (_, shapes) = previewed_shapes(&t.pointer(&c, &quote_drag(150.0, 120.0, true).with_mods(shift_alt)));
let (_, r) = &shapes[0];
assert_eq!(r["width"], r["height"], "square: {r}");
assert_eq!(r["x"].as_f64().unwrap_or_default() + r["width"].as_f64().unwrap_or_default() / 2.0, 100.0, "centred: {r}");
}
/// ↑ during a polygon drag with copies left changes only the shape being drawn; Escape cancels
/// the copies with it, and the next drag starts without them.
#[test]
fn backtick_copies_keep_their_sides_and_escape_cancels_them() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("polygon");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&c, &quote_drag(140.0, 100.0, true));
t.pointer(&c, &quote_drag(150.0, 100.0, true));
let (batch, shapes) = previewed_shapes(&t.key(&c, ToolKey::Up, Mods::default()));
assert!(batch);
let sides: Vec<_> = shapes.iter().map(|(_, p)| p["sides"].clone()).collect();
assert_eq!(sides, vec![json!(6), json!(7)], "the copy keeps its sides");
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
let (batch, _) = previewed_shapes(&t.pointer(&c, &quote_drag(140.0, 100.0, false)));
assert!(!batch, "no copies after Escape");
}
/// No copy is left of a shape without a height or a length, and one drag leaves at most
/// [`MAX_COPIES`] copies while the shape being drawn still follows the pointer.
#[test]
fn backtick_copies_skip_empty_shapes_and_stop_at_the_limit() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
// A rectangle with no height: nothing is left.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
for x in [30.0, 40.0, 50.0, 60.0] {
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(x, 10.0, true))).0, "{x}");
}
// A line back on its start: no copy there.
let mut t = ShapeTool::new("lineSegment");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(30.0, 10.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(10.0, 10.0, true))).0);
// The limit.
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &quote_drag(10.0, 10.0, true));
let mut last = vec![];
for i in 1..=(MAX_COPIES as u32 + 20) {
let at = 10.0 + f64::from(i) * 10.0;
last = t.pointer(&c, &quote_drag(at, at, true));
}
let (batch, widths) = previewed_widths(&last);
assert!(batch);
assert_eq!(widths.len(), MAX_COPIES + 1, "the copies and the shape being drawn");
assert_eq!(widths.last(), Some(&(10.0 + f64::from(MAX_COPIES as u32 + 20) * 10.0)), "the shape follows the pointer");
}
/// The spacing is measured on screen: at 400% zoom, 2 pt of travel is 8 screen points.
#[test]
fn backtick_copy_spacing_is_measured_on_screen() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let c = ToolContext { smart_guides: false, zoom: 4.0, ..cx(&d, &s, &p) };
let mut t = ShapeTool::new("rectangle");
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
t.pointer(&c, &quote_drag(20.0, 20.0, true));
assert!(!previewed_shapes(&t.pointer(&c, &quote_drag(21.5, 20.0, true))).0, "6 screen points");
assert!(previewed_shapes(&t.pointer(&c, &quote_drag(22.0, 20.0, true))).0, "8 screen points");
}
+194
View File
@@ -966,6 +966,168 @@ fn a_gray_between_black_and_white_is_one_shape() {
}
}
/// Flat Logo with the black of the tests below, `gray` and white named exactly.
fn black_gray_white(gray: [u8; 3]) -> TraceParams {
let logo_colors = vec!["#040403".into(), format!("#{:02X}{:02X}{:02X}", gray[0], gray[1], gray[2]), "#FFFFFF".into()];
TraceParams { logo_colors, ..logo_params() }
}
/// A black disc and a gray square on white, blurred by 1 to 3 pixels: the edge pixels around the
/// disc as light as the gray read as blends of black and white, so the gray is one shape (the
/// square) and no gray lines the disc, with the colors found or named. At a blur of 3 pixels, with
/// the colors named, a gray of 128 is still one shape, a gray of 200 leaves 4 slivers of no area,
/// and a light gray (230) leaves at most 8 slivers, touching the disc's edge at no more than 4 of
/// 192 samples. (Without named colors, an image blurred by 3 pixels traces without its gray.)
#[test]
fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [1.0, 1.5, 2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 30.0).hypot(y - 30.0) <= 20.0 {
INK
} else if (60.0..=110.0).contains(&x) && (10.0..=50.0).contains(&y) {
gray
} else {
WHITE
})
});
for by_name in [false, true] {
if !by_name && blur > 2.0 {
continue;
}
let res = trace(&img, &if by_name { black_gray_white(gray) } else { logo_params() });
let what = format!("gray {}, blur {blur}, named {by_name}", gray[0]);
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(top_color(&res, Point::new(85.0, 30.0)), Some(gray), "{what}: the square; {paths:?}");
let mut rim = 0;
for r in [19.0, 20.0, 21.0] {
for k in 0..64 {
let a = f64::from(k) * std::f64::consts::TAU / 64.0;
if top_color(&res, Point::new(30.0 + r * a.cos(), 30.0 + r * a.sin())) == Some(gray) {
rim += 1;
}
}
}
let mut grays: Vec<_> = res.paths.iter().filter(|t| t.color == gray).map(|t| t.pixels).collect();
grays.sort_unstable();
grays.pop();
match (gray[0], blur == 3.0) {
(230, true) => {
assert!(grays.len() <= 8, "{what}: {} slivers; {paths:?}", grays.len());
assert!(rim <= 4, "{what}: {rim} of 192 samples along the disc's edge traced gray");
}
(200, true) => {
assert!(grays.len() <= 4 && grays.iter().all(|&n| n == 0), "{what}: slivers {grays:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
_ => {
assert!(grays.is_empty(), "{what}: slivers {grays:?}; {paths:?}");
assert_eq!(rim, 0, "{what}: samples along the disc's edge traced gray");
}
}
}
}
}
}
/// A soft-edged gray band 2 to 4 pixels wide lying along a black disc, blurred by 1.5 or 2 pixels,
/// traces as black and white: its pixels are reached from the disc and from the white through
/// pixels that keep getting darker and lighter, as across a blurred black-to-white edge. A band 8
/// pixels wide keeps at least half of its gray. With sharp edges every band stays gray.
#[test]
fn a_soft_gray_band_along_black_traces_as_black_and_white() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
for blur in [0.0, 1.5, 2.0] {
for wide in [2u8, 3, 4, 8] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
// The band's samples: 16 rows of its `wide` columns outside the disc.
let kept = (0..wide)
.flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5)))
.filter(|&at| top_color(&res, at) == Some(gray))
.count();
let all = 16 * usize::from(wide);
let what = format!("gray {}, blur {blur}, {wide} px band: {kept} of {all} samples traced gray", gray[0]);
if blur == 0.0 {
assert_eq!(kept, all, "{what}");
} else if wide <= 4 {
assert_eq!(kept, 0, "{what}");
} else {
assert!(2 * kept >= all, "{what}");
}
}
}
}
}
/// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest.
#[test]
fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
const INK: [u8; 3] = [4, 4, 3];
for gray in [[230u8, 230, 230], [128, 128, 128]] {
for blur in [1.0, 1.5] {
for wide in [2.0, 3.0] {
let img = render(120, 60, blur, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (38.0..90.0).contains(&x) && (27.0..27.0 + wide).contains(&y) {
gray
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(gray));
let at = |x: i32| Point::new(f64::from(x) + 0.5, 27.0 + wide / 2.0);
let near = (44..60).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let far = (60..86).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
let what = format!("gray {}, blur {blur}, {wide} px spoke", gray[0]);
assert!((12..=13).contains(&near), "{what}: {near} of the 16 samples nearest the disc traced gray");
assert_eq!(far, 26, "{what}: the rest of the spoke");
}
}
}
}
/// A soft-edged light gray stroke 2 pixels wide beside a black disc, blurred by 1.5 pixels: 2
/// pixels from the disc it keeps less than half of its gray, 4 pixels away it loses a few pixels,
/// and 6 or 8 pixels away it keeps all of it.
#[test]
fn a_soft_gray_stroke_near_black_loses_gray_by_its_distance() {
const INK: [u8; 3] = [4, 4, 3];
const GRAY: [u8; 3] = [230, 230, 230];
for gap in [2, 4, 6, 8] {
let x0 = 43.0 + f64::from(gap);
let img = render(120, 60, 1.5, |x, y| {
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
INK
} else if (x0..x0 + 2.0).contains(&x) && (8.0..50.0).contains(&y) {
GRAY
} else {
WHITE
})
});
let res = trace(&img, &black_gray_white(GRAY));
let kept = (12..46).filter(|&y| top_color(&res, Point::new(x0 + 1.0, f64::from(y) + 0.5)) == Some(GRAY)).count();
let what = format!("{gap} px from the disc: {kept} of 34 samples traced gray");
match gap {
2 => assert!(2 * kept < 34, "{what}"),
4 => assert!((24..34).contains(&kept), "{what}"),
_ => assert_eq!(kept, 34, "{what}"),
}
}
}
/// A one-pixel gray line between flat black and flat white, with the three colors named, stays a
/// gray line along its whole length, beside a black disc whose edge pixels are as light as the gray.
#[test]
@@ -1158,3 +1320,35 @@ fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() {
}
}
}
#[test]
fn a_disc_on_a_gray_panel_on_a_paler_ground_has_no_slivers_of_the_ground() {
// The panel's gray lies on the line from the ground's gray to the disc's charcoal, so the disc's
// edge pixels are also a mix of the ground and the disc.
let (ground, panel, disc) = ([240, 240, 240], [200, 200, 200], [60, 60, 60]);
for blur in [0.0, 0.7] {
let grays = render(150, 150, blur, move |x, y| {
let (cx, cy) = (x.clamp(35.0, 115.0), y.clamp(35.0, 115.0));
Some(if (x - 75.0).hypot(y - 75.0) < 30.0 {
disc
} else if (20.0..130.0).contains(&x) && (20.0..130.0).contains(&y) && (x - cx).hypot(y - cy) < 15.0 {
panel
} else {
ground
})
});
for named in [false, true] {
let logo_colors = if named { vec!["#F0F0F0".into(), "#C8C8C8".into(), "#3C3C3C".into()] } else { Vec::new() };
let res = trace(&grays, &TraceParams { logo_colors, ..logo_params() });
let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect();
assert_eq!(res.paths.len(), 3, "blur {blur}, named {named}: one path per color; {paths:?}");
for k in 0..16 {
let a = f64::from(k) * std::f64::consts::TAU / 16.0;
let at = Point::new(75.0 + 31.0 * a.cos(), 75.0 + 31.0 * a.sin());
assert_eq!(top_color(&res, at), Some(panel), "blur {blur}, named {named}: beside the disc at {at:?}");
}
assert_eq!(top_color(&res, Point::new(8.0, 75.0)), Some(ground), "blur {blur}, named {named}: the ground");
assert_eq!(top_color(&res, Point::new(75.0, 75.0)), Some(disc), "blur {blur}, named {named}: the disc");
}
}
}
+217 -31
View File
@@ -5,8 +5,10 @@
//! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix
//! reproduces the pixel best. When another mix also reproduces it (with a gray between black and
//! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of
//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! when its neighbors show an edge between those classes.
//! black and white, and a gray-to-black edge pixel is a mix of white and black as well as of gray
//! and black), the pixel takes the mix whose classes lie nearest it in the flat areas around it,
//! or, on an edge blurred over several pixels, along the pixels that lead across the edge, when its
//! neighbors show an edge between those classes.
use std::collections::{HashMap, HashSet};
@@ -21,6 +23,8 @@ const PURE: f64 = 4.0 / 255.0;
const REPRODUCES: f64 = PURE * PURE;
/// How far (in pixels, each way) a class is looked for around a pixel that two mixes reproduce.
const NEARBY: usize = 6;
/// How many steps a path across an edge takes at most ([`across_edge`]).
const WALK: usize = 5;
/// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area.
const FLAT: f64 = 1.5 / 255.0;
/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a
@@ -199,9 +203,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
if tied.is_empty() {
return (planes, residual, switched);
}
// A pixel two mixes reproduce takes another mix of two classes whose farthest class lies nearer
// it than the best mix's does, in the flat areas around it ([`flat_classes`], [`RowDistances::around`]),
// when the pixel lies on an edge between that mix's classes ([`across_edge`]). For the best mix,
// A pixel two mixes reproduce takes another mix of two classes, when the pixel lies on an edge
// between that mix's classes ([`across_edge`]) and that mix lies nearer it than the best mix
// does. A mix lies as near as its farthest class in the flat areas around the pixel
// ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that
// `across_edge` counts when those are fewer. For the best mix,
// the classes held by flat areas between two classes count as well ([`between_classes`]). A
// pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class
// (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white.
@@ -217,7 +223,11 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
continue;
}
let Some(mixes) = mixed.get(&key) else { continue };
let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect();
let edges: Vec<(&Weights, usize)> = mixes
.tied
.iter()
.filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r)))
.collect();
if edges.is_empty() {
continue;
}
@@ -230,8 +240,8 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
}
let now = farthest(&mixes.best, &kept);
let other = edges.into_iter().filter(|m| farthest(m, &dist) < now).min_by_key(|m| farthest(m, &dist));
if let Some(other) = other {
let other = edges.into_iter().map(|(m, r)| (m, farthest(m, &dist).min(r))).filter(|&(_, d)| d < now).min_by_key(|&(_, d)| d);
if let Some((other, _)) = other {
switched.push((i, planes.iter().map(|pl| pl.get(i).copied().unwrap_or(0.0)).collect()));
// (`residual` keeps the best mix's error; the mix taken comes within `REPRODUCES` of the
// pixel as well.)
@@ -243,17 +253,39 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
}
/// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of
/// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond
/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as
/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor
/// darker than the gray.)
fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool {
let [(a, _), (b, _)] = other.as_slice() else { return false };
let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false };
/// a class of `best` that `other` leaves out. For a class left out that lies between the classes of
/// `other` on the line between them, a path of pixels from `i` that keeps going toward one class of
/// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so
/// does one that keeps going toward the other. For a class left out that lies beyond both classes of
/// `other` on that line, the pixel has a neighbor on each side of that class, or a neighbor on each
/// side of the pixel itself, none past the class of `other` nearer the class left out, and a chain
/// of neighbors from the pixel to that nearer class or a flat area of it (`flat`), each nearer it
/// than the one before. (A black-to-white edge pixel as light as a gray has a darker neighbor and a
/// lighter one, or, on an edge blurred over several pixels, reaches darker and lighter pixels through
/// pixels that keep getting darker or lighter; from a gray stroke on white, a path that keeps getting
/// darker ends in the stroke, at the gray; a gray-to-black edge pixel has a lighter neighbor and a
/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has only
/// darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a white
/// gap between black and gray has a neighbor lighter than the gray.)
///
/// When it does, the number of steps the longer of the two paths takes to a pixel that stands for its
/// class of `other` (`stands_for`), the largest over the classes left out. It is `NEARBY + 1` when a
/// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`.
fn across_edge(
pix: &[Px],
(flat, stands_for): (&[Option<usize>], &[Option<usize>]),
(width, height): (usize, usize),
i: usize,
classes: &[[f64; 4]],
best: &Weights,
other: &Weights,
) -> Option<usize> {
let [(a, _), (b, _)] = other.as_slice() else { return None };
let (ca, cb) = (classes.get(*a)?, classes.get(*b)?);
let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]);
let len2: f64 = ab.iter().map(|v| v * v).sum();
if len2 <= 1e-12 {
return false;
return None;
}
let len = len2.sqrt();
// Where `v` lies along the line from `a` to `b` (0 at `a`, 1 at `b`), and how far off it.
@@ -262,22 +294,102 @@ fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f6
let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::<f64>().sqrt();
(t, off)
};
let (x, y) = (i % width.max(1), i / width.max(1));
let neighbors: Vec<f64> = (y.saturating_sub(1)..(y + 2).min(height))
.flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(|&j| j != i)
.filter_map(|j| pix.get(j))
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
.collect();
// Where pixel `j` lies along the line, when it lies within `2 * PURE` of it.
let at = |j: usize| {
pix.get(j)
.map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])]))
.filter(|&(_, off)| off <= 2.0 * PURE)
.map(|(t, _)| t)
};
// The pixels around pixel `j`.
let around = |j: usize| {
let (x, y) = (j % width.max(1), j / width.max(1));
(y.saturating_sub(1)..(y + 2).min(height))
.flat_map(move |yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx))
.filter(move |&n| n != j)
};
let neighbors: Vec<f64> = around(i).filter_map(at).collect();
let left_out: Vec<usize> = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect();
!left_out.is_empty()
&& left_out.iter().all(|&c| {
let Some(&cv) = classes.get(c) else { return false };
let (tc, _) = place(cv);
neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE)
})
// Whether the pixel has a neighbor on each side of place `t` along the line.
let straddled = |t: f64| neighbors.iter().any(|&tn| (t - tn) * len > PURE) && neighbors.iter().any(|&tn| (tn - t) * len > PURE);
// Whether pixel `j`, at place `t`, lies within `PURE` of class `c` (at place `to`), or in a flat
// area of class `c` ([`flat_classes`]), or beside one and within `PURE` of its color along the
// line (as when `c` is named some levels off the area's color).
let touches = |j: usize, t: f64, c: usize, to: f64| {
let in_c = |n: usize| flat.get(n).copied().flatten() == Some(c);
(t - to).abs() * len <= PURE || in_c(j) || around(j).any(|n| in_c(n) && at(n).is_some_and(|tn| (tn - t).abs() * len <= PURE))
};
// Whether a chain of neighbors from the pixel, each nearer place `to` than the one before and
// none past it (`past`), comes to class `c` ([`touches`]) in at most `NEARBY` steps. (From a
// pixel beside a pale line's middle, the middle is the only neighbor nearer the gray, and it has
// none, and it is far from the gray.)
let reaches = |to: f64, c: usize, past: &dyn Fn(f64) -> bool| {
let Some(t) = at(i) else { return false };
let mut front = vec![(i, t)];
let mut seen = HashSet::from([i]);
for step in 0..=NEARBY {
let mut next = Vec::new();
for &(j, t) in &front {
if touches(j, t, c, to) {
return true;
}
if step < NEARBY {
for n in around(j) {
if let Some(tn) = at(n).filter(|&tn| !past(tn) && (tn - to).abs() < (t - to).abs())
&& seen.insert(n)
{
next.push((n, tn));
}
}
}
}
if next.is_empty() {
return false;
}
front = next;
}
false
};
// A path from `i` toward `a` (`toward` -1) or `b` (`toward` 1): each step goes to the neighbor
// near the line that lies farthest that way, while it lies farther than the pixel before (the
// first step is taken whatever `i` itself is). `None` when it does not get more than `PURE` past
// `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that stands for `class`
// (`stands_for`), or `NEARBY + 1`.
let walk = |toward: f64, tc: f64, class: usize| {
let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward);
let mut past = false;
for step in 1..=WALK {
match around(cur).filter_map(|j| at(j).map(|tj| (j, tj))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))) {
Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj),
_ => break,
}
past = past || (t - tc) * toward * len > PURE;
if past && stands_for.get(cur).copied().flatten() == Some(class) {
return Some(step);
}
}
past.then_some(NEARBY + 1)
};
if left_out.is_empty() {
return None;
}
let mut reach = 0;
for &c in &left_out {
let (tc, _) = place(*classes.get(c)?);
if (0.0..=1.0).contains(&tc) {
let ra = walk(-1.0, tc, *a)?;
let rb = walk(1.0, tc, *b)?;
reach = reach.max(ra.max(rb));
continue;
}
let beyond = |tn: f64| if tc < 0.0 { -tn * len > PURE } else { (tn - 1.0) * len > PURE };
let (to, near) = if tc < 0.0 { (0.0, *a) } else { (1.0, *b) };
if !(straddled(tc) || !neighbors.iter().any(|&tn| beyond(tn)) && at(i).is_some_and(straddled) && reaches(to, near, &beyond)) {
return None;
}
reach = NEARBY + 1;
}
Some(reach)
}
/// How far the farthest class of `mix` lies, by the distances `dist` ([`RowDistances::around`]).
@@ -670,6 +782,80 @@ mod tests {
}
}
#[test]
fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() {
// A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway
// to charcoal, flat charcoal. The edge pixel is a mix of the gray and the charcoal, with none
// of the ground in it.
let g = |v: f64| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let classes = vec![g(240.0), g(200.0), g(60.0), [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]];
let px = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0];
let mut pix = vec![px(200.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix, 11, 1, &classes);
assert_eq!(pl[0][5], 0.0, "ground in the edge pixel");
assert!((pl[1][5] - 0.5).abs() < 0.02 && (pl[2][5] - 0.5).abs() < 0.02, "gray {} charcoal {}", pl[1][5], pl[2][5]);
// The cases below are vertical lines: three rows alike, read in the middle row.
// The same edge with the panel's pixels three levels darker than the named gray.
let mut pix = vec![px(197.0); 5];
pix.push(px(130.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert_eq!(pl[0][11 + 5], 0.0, "ground in the edge pixel beside a gray three levels off");
// An edge pixel whose lightest neighbor leads nowhere, with another chain of lighter pixels
// to the gray.
let outer = [vec![px(200.0); 5], vec![px(170.0)], vec![px(60.0); 7]].concat();
let middle = [vec![px(200.0); 5], vec![px(170.0), px(130.0), px(180.0)], vec![px(60.0); 5]].concat();
let (pl, _, _) = unmix(&[outer.clone(), middle, outer].concat(), 13, 3, &classes);
assert_eq!(pl[0][13 + 6], 0.0, "ground in the edge pixel beside a dead end");
// A pixel half ground and half charcoal between charcoal pixels, flat gray three pixels off:
// a thin pale line on the charcoal, kept.
let mut pix = vec![px(200.0); 3];
pix.extend([px(60.0); 2]);
pix.push(px(150.0));
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes);
assert!((pl[0][11 + 5] - 0.5).abs() < 0.02, "the line: ground {}", pl[0][11 + 5]);
// A gap of the ground's color one pixel wide between flat charcoal and flat gray: the pixel
// half charcoal and half ground beside it keeps its ground.
let mut pix = vec![px(60.0); 5];
pix.extend([px(150.0), px(236.0)]);
pix.extend([px(200.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 12, 3, &classes);
assert!((pl[0][12 + 5] - 0.5).abs() < 0.02, "the gap: ground {}", pl[0][12 + 5]);
// A pale line blurred over three pixels on the charcoal, flat gray five pixels off: the pixels
// beside its middle have a lighter neighbor and a darker one, and keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(103.0), px(154.0), px(103.0)]);
pix.extend([px(60.0); 9]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for j in [20 + 8, 20 + 10] {
assert!((pl[0][j] - 43.0 / 180.0).abs() < 0.02 && pl[1][j] == 0.0, "the blurred line at {j}: ground {} gray {}", pl[0][j], pl[1][j]);
}
// A pale line one pixel wide that falls between two pixels, covering half of one and three
// quarters of the other: both pixels keep their ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(60.0); 3]);
pix.extend([px(150.0), px(195.0)]);
pix.extend([px(60.0); 10]);
let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes);
for (j, want) in [(20 + 8, 0.5), (20 + 9, 0.75)] {
let (ground, gray) = (pl[0][j], pl[1][j]);
assert!((ground - want).abs() < 0.02 && gray == 0.0, "the line between pixels at {j}: ground {ground} gray {gray}");
}
// An edge from the gray to the charcoal blurred by 0.7 pixel: the pixels between take no
// ground.
let mut pix = vec![px(200.0); 5];
pix.extend([px(199.97), px(197.8), px(166.7), px(93.3), px(62.2)]);
pix.extend([px(60.0); 5]);
let (pl, _, _) = unmix(&pix.repeat(3), 15, 3, &classes);
for j in [15 + 7, 15 + 8] {
assert_eq!(pl[0][j], 0.0, "the blurred edge at {j}: ground");
}
}
#[test]
fn row_distances_match_a_scan_of_the_window_around_each_pixel() {
// Three classes scattered over 23 x 17 pixels, some pixels holding two, most none.
+29 -1
View File
@@ -339,7 +339,9 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
}
let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0));
// Keeps the pointer off the canvas; not focusable (`click_and_drag` is), so Tab skips it.
ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG);
// A click on it, the current object's name included, outside the back arrow, the crumbs of
// the levels above and the pattern buttons leaves isolation mode.
let background = ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG);
ui.painter().rect_filled(bar, 0.0, t.panel);
let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0));
let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click());
@@ -406,12 +408,38 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
});
}
}
// A click on the background leaves isolation mode altogether, symbol editing mode included.
// While a pattern is edited it does nothing: Save a Copy, Done and Cancel end pattern editing.
let leave = background.clicked() && nav_cmd.is_none() && pattern_cmd.is_none() && pattern_edit.is_none();
if let Some((cmd, params)) = nav_cmd {
app.run(cmd, params).ok();
}
if let Some(cmd) = pattern_cmd {
app.run(cmd, json!({})).ok();
}
if leave {
leave_isolation(app);
}
}
}
/// Runs `object.exitIsolation` until the current document is out of isolation mode. Leaving symbol
/// editing mode from a group isolated inside the symbol's art first goes back to the art, and leaving
/// the mode restores the isolation it was entered from; each of these is left in turn. It stops at
/// pattern editing, which only its own buttons end, and when a step fails or changes nothing.
fn leave_isolation(app: &mut VectorcraftApp) {
// Each step leaves one level; a document has far fewer levels than this.
const MAX_STEPS: usize = 64;
let state = |app: &VectorcraftApp| {
app.session
.active()
.map(|d| (d.isolation, d.doc.symbol_edit.as_ref().map(|e| e.layer), d.doc.mask_edit.is_some(), d.doc.pattern_edit.is_some()))
};
for _ in 0..MAX_STEPS {
let Some(before) = state(app) else { return };
if before.0.is_none() || before.3 || app.run("object.exitIsolation", json!({})).is_err() || state(app) == Some(before) {
return;
}
}
}
+149
View File
@@ -1508,6 +1508,155 @@ fn isolation_bar_navigation_and_back_button_steps_up() {
assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2)));
}
/// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press
/// at `from`, a move to `to` and a release there. `from == to` is a click.
fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0));
let press = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for events in [vec![egui::Event::PointerMoved(from)], vec![press(from, true)], vec![egui::Event::PointerMoved(to)], vec![press(to, false)]] {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| {
super::isolation_bar(app, ui, screen);
});
out.textures_delta.clear();
}
}
/// A context for `isolation_bar_gesture`.
fn isolation_bar_context() -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
egui_extras::install_image_loaders(&ctx);
ctx
}
/// A click on the isolation bar's empty space leaves nested isolation mode altogether, selects the
/// isolated object as Exit Isolation Mode does and adds no undo step. A drag across the bar does not
/// leave it.
#[test]
fn isolation_bar_background_click_exits_nested_isolation() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let rect = |app: &mut crate::VectorcraftApp, x: f64| {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap()
};
let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0));
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let g1 = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
let c = rect(&mut app, 90.0);
app.run("select.set", json!({"ids": [g1, c]})).unwrap();
app.run("object.group", json!({})).unwrap();
app.run("object.isolate", json!({"id": a})).unwrap();
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, egui::pos2(900.0, 14.0));
assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(a)), "a drag across the bar stays in isolation mode");
let steps = app.session.doc().unwrap().history.undo.len();
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert_eq!((st.isolation, st.selection.objects.clone()), (None, vec![NodeId(a)]), "the click leaves isolation mode");
assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step");
}
/// While a pattern is edited, a click on the isolation bar's empty space leaves pattern editing
/// open; the back arrow still ends it as Done does.
#[test]
fn isolation_bar_background_click_leaves_pattern_edit_open() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let f = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [f]})).unwrap();
app.run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap();
assert!(app.session.active().unwrap().doc.pattern_edit.is_some());
let ctx = isolation_bar_context();
let empty = egui::pos2(500.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open");
let back = egui::pos2(15.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, back, back);
let st = app.session.active().unwrap();
assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing");
}
/// While an opacity mask is edited, a click on the isolation bar's empty space stops editing the
/// mask as Exit Isolation Mode does: the masked object is selected again.
#[test]
fn isolation_bar_background_click_stops_mask_editing() {
use vectorcraft_doc::NodeId;
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let obj = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap();
let m = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 200})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [obj, m]})).unwrap();
app.run("transparency.makeOpacityMask", json!({})).unwrap();
app.run("transparency.editOpacityMask", json!({})).unwrap();
assert!(app.session.active().unwrap().doc.mask_edit.is_some());
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.mask_edit.is_none() && st.isolation.is_none(), "mask editing ends");
assert_eq!(st.selection.objects, vec![NodeId(obj)]);
}
/// In symbol editing mode, a click on the isolation bar's empty space leaves the mode, also while a
/// group inside the symbol's art is isolated, and the symbol keeps the art drawn while editing.
#[test]
fn isolation_bar_background_click_leaves_nested_symbol_editing() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
app.run("symbol.new", json!({"name": "Box"})).unwrap();
app.run("symbol.edit", json!({"name": "Box"})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let b = app.run("shape.rectangle", json!({"x": 130, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let g = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": g})).unwrap();
let ctx = isolation_bar_context();
let empty = egui::pos2(700.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "symbol editing mode ends");
let symbol = st.doc.symbols.iter().find(|s| s.name == "Box").expect("the symbol");
assert!(symbol.art.children().is_some_and(|c| c.len() >= 2), "the edit reached the symbol");
// Symbol editing entered while a group was isolated: the click leaves that isolation too.
let c = app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let d = app.run("shape.rectangle", json!({"x": 250, "y": 150, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [c, d]})).unwrap();
let h = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": h})).unwrap();
app.run("symbol.edit", json!({"name": "Box"})).unwrap();
assert!(app.session.active().unwrap().doc.symbol_edit.is_some());
isolation_bar_gesture(&mut app, &ctx, empty, empty);
let st = app.session.active().unwrap();
assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none(), "the isolation from before symbol editing ends too");
}
/// A click on the current object's name at the end of the breadcrumbs, which is not a link, leaves
/// isolation mode as a click on the bar's empty space does.
#[test]
fn isolation_bar_click_on_the_current_name_exits() {
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("object.isolate", json!({"id": a})).unwrap();
let ctx = isolation_bar_context();
// The crumbs are "Layer 1 › <Path>"; the leaf's name starts after the layer crumb and separator.
let layer = app.session.active().unwrap().doc.ancestry(vectorcraft_doc::NodeId(a)).unwrap()[0];
let layer_name = app.session.active().unwrap().doc.node(layer).unwrap().display_name();
let mut start = 0.0;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let width = |s: &str| ui.painter().layout_no_wrap(s.to_string(), egui::FontId::proportional(12.0), egui::Color32::WHITE).size().x;
start = 30.0 + width(&layer_name) + 6.0 + width("›") + 6.0;
});
out.textures_delta.clear();
let leaf = egui::pos2(start + 4.0, 12.0);
isolation_bar_gesture(&mut app, &ctx, leaf, leaf);
assert_eq!(app.session.active().unwrap().isolation, None);
}
/// Tab goes to the isolation bar's back button and breadcrumbs and does not stop on the bar
/// behind them, which only keeps the pointer off the canvas.
#[test]
+176 -10
View File
@@ -6,7 +6,9 @@
//! ("Set base color to the current color") takes the current color, such as a cell applied from
//! the guide or the selected artwork's color. A click on a cell applies it to the active proxy,
//! without changing the base, and selects it; Shift- or Cmd/Ctrl-click adds
//! cells to the selection that Save Colors as Swatches saves. Limit to Library (the library button,
//! cells to the selection that Save Colors as Swatches saves as swatches and Save Color Group to
//! Swatches saves as one group (without a selection, the group holds the harmony colors). The
//! selection lasts until the guide changes. Limit to Library (the library button,
//! `ui.colorGuideLimit`) snaps every colour to a swatch library or the document's swatches; Edit or
//! Apply Colors opens Recolor Artwork with the harmony colours, limited the same way.
@@ -50,6 +52,33 @@ fn clear_selection(ctx: &egui::Context) {
set_pstate(ctx, "cg-sel", Vec::<(usize, usize)>::new());
}
/// The guide a cell selection was made in: its base, options, harmony rule, library limit and the
/// colors of its grid (which change when the document's swatches limit the guide and are edited).
#[derive(Clone, PartialEq)]
struct SelKey {
base: Color,
opts: GuideOptions,
rule: usize,
limit: String,
grid: Vec<Vec<Color>>,
}
fn sel_key(app: &VectorcraftApp, ctx: &egui::Context, g: &Guide) -> SelKey {
SelKey {
base: base_color(app),
opts: app.ui.color_guide,
rule: pstate(ctx, "cg-harmony"),
limit: app.ui.color_guide_limit.clone(),
grid: g.grid.clone(),
}
}
/// The selected cells while they belong to the guide `g` shown now; none once the base, the
/// options, the harmony rule, the library limit or the grid's colors changed since they were picked.
fn live_selection(app: &VectorcraftApp, ctx: &egui::Context, g: &Guide) -> Vec<(usize, usize)> {
if pstate::<Option<SelKey>>(ctx, "cg-sel-key") == Some(sel_key(app, ctx, g)) { selected(ctx) } else { Vec::new() }
}
/// What the panel's guide is made from: with a library limit, snapping every cell is too slow to
/// redo each frame, so the guide is cached until one of these changes.
#[derive(Clone, PartialEq)]
@@ -128,12 +157,28 @@ fn edit_or_apply(app: &mut VectorcraftApp, g: &Guide) {
/// Save the selected cells' colors as swatches (one undo step), each in its own model.
fn save_selected(app: &mut VectorcraftApp, ctx: &egui::Context) {
let g = guide(app, ctx);
let colors: Vec<Value> = selected(ctx).into_iter().filter_map(|(r, c)| g.grid.get(r)?.get(c)).map(color_json).collect();
let colors: Vec<Value> = live_selection(app, ctx, &g).into_iter().filter_map(|(r, c)| g.grid.get(r)?.get(c)).map(color_json).collect();
if !colors.is_empty() {
app.run("swatch.new", json!({ "colors": colors, "keepModel": true })).ok();
}
}
/// Save Color Group to Swatches: the selected cells as one swatch group, in grid order (row by
/// row, left to right), each cell once; with no cell of the shown guide selected, the harmony
/// colors. The group is named after the harmony rule, saved in one undo step, and each color
/// keeps its own model.
fn save_group(app: &mut VectorcraftApp, ctx: &egui::Context) {
let g = guide(app, ctx);
let mut cells = live_selection(app, ctx, &g);
cells.sort_unstable();
cells.dedup();
let mut colors: Vec<Value> = cells.into_iter().filter_map(|(r, c)| g.grid.get(r)?.get(c)).map(color_json).collect();
if colors.is_empty() {
colors = g.colors.iter().map(color_json).collect();
}
app.run("swatch.newGroup", json!({"name": rule(ctx).label(), "colors": colors, "keepModel": true})).ok();
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = crate::theme::Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
@@ -141,13 +186,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// leaves it as it is.
let first = base_color(app);
let set = *app.ui.color_guide_base.get_or_insert(first);
// Selected cells belong to the guide they were picked from: a new base clears them.
if pstate::<Option<Color>>(&ctx, "cg-sel-base") != Some(set) {
set_pstate(&ctx, "cg-sel-base", Some(set));
clear_selection(&ctx);
}
let h = rule(&ctx);
let g = guide(app, &ctx);
// Selected cells belong to the guide they were picked from: a new base, new options, another
// harmony rule, another library limit or new grid colors clear them.
let key = SelKey { base: set, ..sel_key(app, &ctx, &g) };
if pstate::<Option<SelKey>>(&ctx, "cg-sel-key").as_ref() != Some(&key) {
set_pstate(&ctx, "cg-sel-key", Some(key));
clear_selection(&ctx);
}
let base = g.colors[0];
let mut chosen: Option<Color> = None;
ui.horizontal(|ui| {
@@ -245,8 +292,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
save_selected(app, &ctx);
}
if widgets::icon_button(ui, "dc-folder", tl!("Save color group to Swatch panel"), false, 24.0).clicked() {
let cs: Vec<_> = g.colors.iter().map(color_json).collect();
app.run("swatch.newGroup", json!({"name": h.label(), "colors": cs, "keepModel": true})).ok();
save_group(app, &ctx);
}
});
if let Some(c) = chosen {
@@ -267,7 +313,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
ui.separator();
let ctx = ui.ctx().clone();
if menu_item(ui, tl!("Save Colors as Swatches"), !selected(&ctx).is_empty(), false) {
if menu_item(ui, tl!("Save Colors as Swatches"), !live_selection(app, &ctx, &guide(app, &ctx)).is_empty(), false) {
save_selected(app, &ctx);
}
if menu_item(ui, tl!("Color Guide Options…"), true, false) {
@@ -420,6 +466,126 @@ mod tests {
assert_eq!(saved, [g.grid[0][0], g.grid[0][6]]);
}
/// The colors of the document's newest swatch group, and the group's name.
fn last_group(app: &VectorcraftApp) -> (String, Vec<Color>) {
let g = app.session.doc().unwrap().doc.swatch_groups.last().cloned().expect("a swatch group");
(g.name, g.swatches.iter().filter_map(|w| w.paint.color()).collect())
}
/// With cells selected, Save Color Group to Swatches saves exactly those cells as one group, in
/// grid order and each cell once, in one undo step that Undo removes.
#[test]
fn save_color_group_saves_the_selected_cells_in_grid_order() {
let mut app = app();
let ctx = egui::Context::default();
frame(&mut app, &ctx);
let st = app.session.doc().unwrap();
let (groups, swatches, undo) = (st.doc.swatch_groups.len(), st.doc.swatches.len(), st.history.undo.len());
set_pstate(&ctx, "cg-sel", vec![(1usize, 4usize), (0, 8), (0, 0), (1, 4)]);
save_group(&mut app, &ctx);
let g = guide(&app, &ctx);
let st = app.session.doc().unwrap();
assert_eq!(st.doc.swatch_groups.len(), groups + 1, "one new group");
assert_eq!(st.doc.swatches.len(), swatches, "no loose swatches");
assert_eq!(st.history.undo.len(), undo + 1, "one undo step");
let (name, made) = last_group(&app);
assert_eq!(name, rule(&ctx).label());
assert_eq!(made, [g.grid[0][0], g.grid[0][8], g.grid[1][4]]);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.doc().unwrap().doc.swatch_groups.len(), groups, "Undo removes the group");
}
/// With no cell selected, or only cells outside the shown grid, the group holds the harmony
/// colors.
#[test]
fn save_color_group_without_a_selection_saves_the_harmony_colors() {
let mut app = app();
let ctx = egui::Context::default();
frame(&mut app, &ctx);
let g = guide(&app, &ctx);
save_group(&mut app, &ctx);
assert_eq!(last_group(&app).1, g.colors);
set_pstate(&ctx, "cg-sel", vec![(99usize, 0usize), (0, 99)]);
save_group(&mut app, &ctx);
assert_eq!(last_group(&app).1, g.colors, "cells outside the grid are ignored");
}
/// A guide limited to a library saves its snapped cells, and an RGB cell stays RGB in a CMYK
/// document.
#[test]
fn save_color_group_saves_limited_cells_in_their_own_model() {
let mut app = app();
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
app.run("paint.setFill", json!({"color": "#c04020", "keepModel": true})).unwrap();
app.run("ui.colorGuideLimit", json!({"library": "web-safe-216"})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx);
set_pstate(&ctx, "cg-sel", vec![(0usize, 1usize), (0, 7)]);
save_group(&mut app, &ctx);
let g = guide(&app, &ctx);
let made = last_group(&app).1;
assert_eq!(made, [g.grid[0][1], g.grid[0][7]]);
assert!(made.iter().all(|c| matches!(c, Color::Rgb { .. })), "{made:?}");
let members = library_hexes(&app, "web-safe-216");
assert!(made.iter().all(|c| members.contains(&c.to_hex())), "the snapped colors");
}
/// A selection made in one guide is not saved from another: new options, the variation-mode
/// menu, the harmony rule or the library limit clear it.
#[test]
fn a_changed_guide_drops_the_cell_selection() {
let mut app = app();
let ctx = egui::Context::default();
frame(&mut app, &ctx);
let pick = |ctx: &egui::Context| set_pstate(ctx, "cg-sel", vec![(0usize, 1usize), (0, 2)]);
type Change = fn(&mut VectorcraftApp, &egui::Context);
let changes: [Change; 4] = [
|app, _| app.ui.color_guide.steps = 6,
|app, _| app.ui.color_guide.variation = Variation::WarmCool,
|_, ctx| set_pstate(ctx, "cg-harmony", 3usize),
|app, _| {
app.run("ui.colorGuideLimit", json!({"library": "web-safe-216"})).unwrap();
},
];
for (i, change) in changes.iter().enumerate() {
frame(&mut app, &ctx);
pick(&ctx);
assert_eq!(live_selection(&app, &ctx, &guide(&app, &ctx)).len(), 2, "change {i}: the selection holds");
change(&mut app, &ctx);
let g = guide(&app, &ctx);
assert!(live_selection(&app, &ctx, &g).is_empty(), "change {i}: nothing is saved from the old guide");
save_group(&mut app, &ctx);
assert_eq!(last_group(&app).1, g.colors, "change {i}: the harmony colors");
frame(&mut app, &ctx);
assert!(selected(&ctx).is_empty(), "change {i}: the panel clears the selection");
}
}
/// Limited to the document's swatches, painting art keeps the cell selection, and a new swatch
/// that changes the grid's colors drops it.
#[test]
fn a_new_document_swatch_drops_the_cell_selection() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
choose_base(&mut app, Color::from_hex("#3a7bd5").unwrap());
app.run("ui.colorGuideLimit", json!({"library": "document"})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx);
set_pstate(&ctx, "cg-sel", vec![(0usize, 1usize), (0, 2)]);
app.run("paint.setFill", json!({"color": "#102030"})).unwrap();
frame(&mut app, &ctx);
assert_eq!(selected(&ctx).len(), 2, "an edit that leaves the grid as it is keeps the selection");
let before = guide(&app, &ctx);
app.run("swatch.new", json!({"colors": ["#3a7bd5"]})).unwrap();
let g = guide(&app, &ctx);
assert_ne!(g.grid, before.grid, "the new swatch changes the grid");
assert!(live_selection(&app, &ctx, &g).is_empty(), "nothing is saved from the old grid");
save_group(&mut app, &ctx);
assert_eq!(last_group(&app).1, g.colors);
frame(&mut app, &ctx);
assert!(selected(&ctx).is_empty(), "the panel clears the selection");
}
/// Every colour of the panel's guide.
fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
let g = guide(app, ctx);
+187 -11
View File
@@ -1,5 +1,6 @@
//! Graphic Styles panel: the document's styles as rendered thumbnails (Thumbnail View) or rows
//! (Small and Large List View), shown on a square or on type. Clicking a style applies it to the
//! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke
//! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the
//! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from
//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one;
//! double-click opens Graphic Style Options. Dragging a style moves it in the list, or applies it
@@ -15,10 +16,10 @@ use std::sync::Arc;
use egui::{Color32, Rect, Response, Sense, Stroke, StrokeKind, TextureHandle, Ui, pos2, vec2};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::style_libs::STYLE_LIBRARIES;
use vectorcraft_doc::text::{CharStyle, TextObject};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StyleLibrary};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer, StyleLibrary};
use vectorcraft_engine::cmd::stylelib;
use vectorcraft_engine::cmd::swatchlib::LibraryInfo;
use vectorcraft_geom::{Affine, Point, shapes};
@@ -80,6 +81,50 @@ fn uses_brush(g: &GraphicStyle) -> bool {
g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some()))
}
/// Does `g` have no fill and no stroke? A fill or stroke row whose paint is None does not count; a
/// hidden row or one with zero opacity does. The thumbnails of such a style show the preview shape
/// with a black outline, a white fill and a red slash ([`backing`], [`slash`]).
fn paints_nothing(g: &GraphicStyle) -> bool {
g.appearance.items.iter().all(|i| i.paint().is_none())
}
/// `g` with a white fill below its rows and a black stroke `width` wide above them, and every row
/// above the contents, so the white fill also covers type's own character colors: the shape a
/// style with no fill and no stroke is shown on, with the style's effects and transparency.
fn backing(g: &GraphicStyle, width: f64) -> GraphicStyle {
let mut g = g.clone();
g.appearance.contents_index = None;
g.appearance.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE))));
g.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), width)));
g
}
/// The red of the slash on the thumbnail of a style with no fill and no stroke.
const SLASH: [f32; 3] = [230.0, 0.0, 0.0];
/// Draw a red slash (`/`) across the middle of `img`, a third of its side long, over what is there.
fn slash(img: &mut egui::ColorImage) {
let [w, h] = img.size;
let side = w.min(h) as f32;
let (cx, cy, half) = (w as f32 / 2.0, h as f32 / 2.0, side / 6.0);
let (a, b) = (pos2(cx - half, cy + half), pos2(cx + half, cy - half));
let radius = (side * 0.035).max(0.9);
let ab = b - a;
for y in 0..h {
for x in 0..w {
let p = pos2(x as f32 + 0.5, y as f32 + 0.5);
let t = ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0);
let cover = (radius + 0.5 - (p - (a + ab * t)).length()).clamp(0.0, 1.0);
if cover > 0.0
&& let Some(px) = img.pixels.get_mut(y * w + x)
{
let mix = |old: u8, new: f32| (old as f32 + (new - old as f32) * cover).round() as u8;
*px = Color32::from_rgb(mix(px.r(), SLASH[0]), mix(px.g(), SLASH[1]), mix(px.b(), SLASH[2]));
}
}
}
}
/// What a style's thumbnail paints with besides the style: the patterns and brushes of a document,
/// or the patterns of a library.
#[derive(Clone, Copy)]
@@ -147,9 +192,20 @@ fn look_hashes(ctx: &egui::Context, app: &VectorcraftApp) -> Arc<Vec<u64>> {
}
/// Style `g` applied (as `graphicStyle.apply` applies it) to the preview shape, rendered `px`
/// pixels square on white, with `paints`.
/// pixels square on white, with `paints`. A style with no fill and no stroke ([`paints_nothing`])
/// is shown on the shape outlined in black and filled with white, under a red slash.
fn render(app: &VectorcraftApp, paints: Paints, g: &GraphicStyle, preview: Preview, px: u32) -> Option<egui::ColorImage> {
const SIDE: f64 = 100.0;
let empty = paints_nothing(g);
let backed;
let g = if empty {
// An outline 1.5 pixels wide on images up to 150 pixels across, and one hundredth of the
// image width on larger ones.
backed = backing(g, (1.5 * SIDE / px.max(1) as f64).max(1.0));
&backed
} else {
g
};
let mut doc = Document::new(SIDE, SIDE);
doc.patterns = paints.patterns.to_vec();
if uses_brush(g)
@@ -172,7 +228,11 @@ fn render(app: &VectorcraftApp, paints: Paints, g: &GraphicStyle, preview: Previ
let layer = doc.layers[0].id;
doc.insert(Some(layer), 0, app.session.styled(&shape, g)).ok()?;
let img = RENDERER.with(|r| r.borrow_mut().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, SIDE, SIDE), px as f64 / SIDE, true));
Some(crate::canvas::color_image(&img))
let mut img = crate::canvas::color_image(&img);
if empty {
slash(&mut img);
}
Some(img)
}
/// The thumbnail of style `g` (`look`: its [`look_hash`]) at `size` points.
@@ -226,8 +286,10 @@ pub(super) fn outline(ui: &Ui, r: Rect, on: bool, hovered: bool) {
ui.painter().rect_stroke(r, 0.0, Stroke::new(if on { 2.0 } else { 1.0 }, color), StrokeKind::Inside);
}
/// Style `g` on a copy of the first selected object, `px` pixels square on white. One texture,
/// re-rendered only when the document, the style's look or the size changes.
/// Style `g` on a copy of the first selected object, `px` pixels square on white; a style with no
/// fill and no stroke shows the object outlined in black and filled with white, under a red slash,
/// as [`render`] shows it. One texture, re-rendered only when the document, the style's look or the
/// size changes.
fn object_preview(app: &VectorcraftApp, ctx: &egui::Context, g: &GraphicStyle, look: u64, px: u32) -> Option<TextureHandle> {
let st = app.session.active()?;
let n = st.doc.node(*st.selection.objects.first()?)?;
@@ -238,14 +300,30 @@ fn object_preview(app: &VectorcraftApp, ctx: &egui::Context, g: &GraphicStyle, l
{
return Some(tex);
}
let styled = app.session.styled(n, g);
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(&st.doc, &styled, px, Some([255; 4])))?;
let color = crate::canvas::color_image(&img);
let tex = ctx.load_texture("gs-large-object", color, egui::TextureOptions::LINEAR);
let tex = ctx.load_texture("gs-large-object", render_object(app, &st.doc, n, g, px)?, egui::TextureOptions::LINEAR);
ctx.data_mut(|d| d.insert_temp(slot, (key, tex.clone())));
Some(tex)
}
/// Style `g` on a copy of `n` (an object of `doc`), rendered `px` pixels square on white: the image
/// of [`object_preview`].
fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyle, px: u32) -> Option<egui::ColorImage> {
let empty = paints_nothing(g);
let styled = if empty {
// An outline about 1.5 pixels wide on the object scaled to the preview.
let side = n.geometric_bounds().map_or(1.0, |b| b.width().max(b.height()));
app.session.styled(n, &backing(g, (1.5 * side / px.max(1) as f64).max(1e-3)))
} else {
app.session.styled(n, g)
};
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?;
let mut img = crate::canvas::color_image(&img);
if empty {
slash(&mut img);
}
Some(img)
}
/// The large preview of style `i` next to the pointer while the right button is held on it: on
/// the selected object when there is one, else on the preview shape.
fn large_preview(app: &VectorcraftApp, ctx: &egui::Context, s: &Shown, i: usize) {
@@ -954,6 +1032,104 @@ mod tests {
assert_eq!(px(2, 2), Color32::WHITE);
}
/// Is `c` the slash's red?
fn red(c: Color32) -> bool {
c.r() > 180 && c.g() < 70 && c.b() < 70
}
/// Is `c` near black?
fn dark(c: Color32) -> bool {
c.r() < 90 && c.g() < 90 && c.b() < 90
}
/// A style with no fill and no stroke shows its thumbnail on the preview square or on type,
/// outlined in black and filled with white, under a red slash; so does a style whose rows paint
/// None, and one with only effects, whose effects still show. The large preview on the selected
/// object shows the same.
#[test]
fn a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash() {
let app = app();
let d = app.session.active().unwrap().doc.clone();
let image = |app: &VectorcraftApp, g: &GraphicStyle, preview: Preview| render(app, Paints::of(&d), g, preview, 40).unwrap();
let px = |img: &egui::ColorImage, x: usize, y: usize| img.pixels[y * img.size[0] + x];
let empty = GraphicStyle::new("Empty", Appearance::default());
let nones = GraphicStyle::new("Nones", Appearance::basic(Paint::None, Paint::None, 1.0));
for g in [&empty, &nones] {
let img = image(&app, g, Preview::Square);
// The square spans 8.8 to 31.2 pixels: a black edge, white inside, red in the middle.
assert!(red(px(&img, 20, 20)), "{}: {:?}", g.name, px(&img, 20, 20));
assert!((7..=10).any(|x| dark(px(&img, x, 20))), "{}: the left edge is black", g.name);
assert_eq!(px(&img, 13, 13), Color32::WHITE, "{}", g.name);
assert_eq!(px(&img, 2, 2), Color32::WHITE, "{}", g.name);
assert!(!red(px(&img, 13, 13)) && !red(px(&img, 27, 27)));
}
// On type: the slash over the outlined characters.
let img = image(&app, &empty, Preview::Text);
assert!(red(px(&img, 20, 20)));
assert!(img.pixels.iter().any(|c| dark(*c)), "the characters are outlined in black");
// Effects still show: a drop shadow 10 points down and right of the square.
let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 10, "blur": 0}), visible: true };
let effects = GraphicStyle::new("Shadow", Appearance { effects: vec![shadow], ..Appearance::default() });
let img = image(&app, &effects, Preview::Square);
assert!(red(px(&img, 20, 20)));
assert_ne!(px(&img, 33, 33), Color32::WHITE, "the shadow shows below the square");
// The large preview on the selected rectangle.
let st = app.session.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let img = render_object(&app, &st.doc, n, &empty, 60).unwrap();
assert!(red(px(&img, 30, 30)));
assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30));
assert_eq!(px(&img, 10, 10), Color32::WHITE);
// A style that paints keeps its own look there, without the slash.
let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0));
let img = render_object(&app, &st.doc, n, &blue, 60).unwrap();
assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255));
}
/// The white fill of a style with no fill and no stroke paints above type's characters even
/// when the style puts its Characters row above some of its rows and Override Character Color
/// is off: the type preview looks the same as for the style without that row order.
#[test]
fn the_white_fill_of_a_style_with_no_paint_covers_the_characters_whatever_its_contents_row() {
let mut app = app();
app.session.prefs.override_char_color = false;
let d = app.session.active().unwrap().doc.clone();
let image = |g: &GraphicStyle| render(&app, Paints::of(&d), g, Preview::Text, 40).unwrap();
let plain = GraphicStyle::new("Nones", Appearance::basic(Paint::None, Paint::None, 1.0));
let mut above = plain.clone();
above.appearance.set_contents_at(1);
assert_eq!(above.appearance.contents_index, Some(1));
assert!(paints_nothing(&above));
assert!(image(&above).pixels == image(&plain).pixels, "the characters' own fill shows through the white fill");
}
/// A style with only a fill, or only a stroke, shows its own paint; a hidden fill or one with
/// zero opacity still counts as a fill, so its thumbnail shows no slash.
#[test]
fn a_fill_or_a_stroke_alone_or_a_hidden_fill_shows_no_slash() {
let app = app();
let d = app.session.active().unwrap().doc.clone();
let image = |g: &GraphicStyle| render(&app, Paints::of(&d), g, Preview::Square, 40).unwrap();
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let fill = GraphicStyle::new("Fill", Appearance::basic(blue.clone(), Paint::None, 1.0));
let stroke = GraphicStyle::new("Stroke", Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.6, 0.0)), 4.0));
let mut hidden = GraphicStyle::new("Hidden", Appearance::basic(blue.clone(), Paint::None, 1.0));
if let Some(f) = hidden.appearance.fill_mut() {
f.visible = false;
}
let mut clear = GraphicStyle::new("Clear", Appearance::basic(blue, Paint::None, 1.0));
if let Some(f) = clear.appearance.fill_mut() {
f.opacity = 0.0;
}
for g in [&fill, &stroke, &hidden, &clear] {
assert!(!paints_nothing(g), "{}", g.name);
assert!(!image(g).pixels.iter().any(|c| red(*c)), "{} shows no slash", g.name);
}
assert_eq!(image(&fill).pixels[20 * 40 + 20], Color32::from_rgb(0, 0, 255));
assert_eq!(image(&hidden).pixels[20 * 40 + 20], Color32::WHITE);
assert!(image(&stroke).pixels.iter().any(|c| c.g() > 100 && c.r() < 60 && c.b() < 60), "the stroke shows");
}
#[test]
fn merge_asks_for_a_name_and_drops_move_styles_or_make_new_ones() {
let mut app = app();
+1 -1
View File
@@ -33,7 +33,7 @@
//! - Double-clicking a name renames it; double-clicking elsewhere on a row opens its options.
//! - A target circle targets its layer, group or object (`layer.target`); dragging it onto another
//! row's circle moves the appearance there (Alt copies it, `appearance.transfer`) and dropping it
//! on the trash clears it.
//! on the trash reduces it to basic appearance (`appearance.reduceToBasic`) without deleting it.
//! - Search All and the Filter button at its right (`ui.layersFilter`, lit while a filter is on)
//! narrow the rows, and every row that holds others shows open while they do. A row stays when
//! its name holds the text typed, it is one of the object kinds ticked under By Object and it is
+4 -3
View File
@@ -55,13 +55,14 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc
let m = ui.input(|i| i.modifiers);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
let trash = widgets::icon_button(&mut child, "trash-2", tl!("Delete Selection"), false, 24.0);
// A target circle dropped on the trash clears that appearance (dragged rows: below). Peek at
// the payload's type before taking it: egui's take drops a payload of another type.
// A target circle dropped on the trash reduces that appearance to one fill and one stroke
// (dragged rows: below). Peek at the payload's type before taking it: egui's take drops a
// payload of another type.
if trash.dnd_hover_payload::<PanelDrag>().is_some()
&& let Some(d) = trash.dnd_release_payload::<PanelDrag>()
&& let PanelDrag::Appearance(id) = *d
{
actions.push(("appearance.clear".into(), json!({"ids": [id.0]})));
actions.push(("appearance.reduceToBasic".into(), json!({"ids": [id.0]})));
} else if trash.clicked() {
// With no row highlighted, the selected art and ruler guides go.
if view.rows.is_empty() && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) {
+42 -7
View File
@@ -409,7 +409,7 @@ fn clicking_a_target_circle_targets_the_layer() {
}
#[test]
fn dragging_a_target_circle_moves_or_copies_the_appearance_and_the_trash_clears_it() {
fn dragging_a_target_circle_moves_or_copies_the_appearance() {
let (mut app, layer, [a, b]) = two_rects();
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
let ctx = egui::Context::default();
@@ -421,14 +421,49 @@ fn dragging_a_target_circle_moves_or_copies_the_appearance_and_the_trash_clears_
// A plain drag onto the layer's circle moves it there.
drag(&mut app, &ctx, c[1], c[0], false);
assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0);
// Dropped on the trash, the layer's appearance is cleared (and nothing is deleted).
let st = app.session.active().unwrap();
let count = st.doc.node_count();
}
/// A target circle dropped on the trash reduces that item's own appearance to its topmost visible
/// fill and stroke in one undo step, and deletes nothing; dropped again, it changes nothing and
/// adds no undo step. A layer keeps only the rows it had, and its art is left as it is.
#[test]
fn dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance() {
let (mut app, layer, [a, _]) = two_rects();
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
// [Fill green, Stroke, Fill red, Stroke 5 pt], with an effect on the object.
run(&mut app, "appearance.addFill", json!({"ids": [a.0]}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 0, "color": "#00ff00"}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 2, "color": "#ff0000"}));
run(&mut app, "appearance.addStroke", json!({"ids": [a.0]}));
run(&mut app, "appearance.setItem", json!({"ids": [a.0], "index": 3, "weight": 5}));
run(&mut app, "effect.apply", json!({"ids": [a.0], "effect": "stylize.dropShadow", "item": null}));
let ctx = egui::Context::default();
let (c, _) = frame(&mut app, &ctx, vec![], false);
let trash = trash_pos(&mut app, &ctx);
let node = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().clone();
let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let (original, count, before) = (node(&app, a), app.session.active().unwrap().doc.node_count(), undo(&app));
// The bottom rectangle's circle (rows: the layer, the top rectangle, the bottom one).
drag(&mut app, &ctx, c[2], trash, false);
let n = node(&app, a);
assert!(n.appearance.is_basic(), "{:?}", n.appearance);
assert_eq!(n.appearance.items.len(), 2);
assert_eq!(n.appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000");
assert_eq!(n.appearance.stroke().unwrap().width, 5.0);
assert_eq!((app.session.active().unwrap().doc.node_count(), undo(&app)), (count, before + 1));
// Dropped again, nothing changes and no undo step is made.
drag(&mut app, &ctx, c[2], trash, false);
assert_eq!((node(&app, a), undo(&app)), (n, before + 1));
run(&mut app, "edit.undo", json!({}));
assert_eq!(node(&app, a), original, "one undo step restores the whole stack");
// The layer's own fill stays and its effect goes; the art on it keeps its appearance.
run(&mut app, "appearance.addFill", json!({"ids": [layer.0]}));
run(&mut app, "effect.apply", json!({"ids": [layer.0], "effect": "stylize.dropShadow", "item": null}));
drag(&mut app, &ctx, c[0], trash, false);
let st = app.session.active().unwrap();
assert_eq!(st.doc.node(layer).unwrap().opacity, 1.0);
assert_eq!(st.doc.node_count(), count);
let l = node(&app, layer);
assert_eq!((l.appearance.items.len(), l.appearance.effects.len()), (1, 0), "{:?}", l.appearance);
assert!(l.appearance.fill().is_some());
assert_eq!(node(&app, a), original);
}
/// The trash button: the bottom bar's rightmost button.
+21 -2
View File
@@ -4,6 +4,7 @@
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::wand::color_tolerance_max;
use super::{pstate, set_pstate};
use crate::VectorcraftApp;
@@ -47,12 +48,18 @@ fn row(app: &mut VectorcraftApp, ui: &mut Ui, o: &Value, label: &str, flag: &str
});
}
/// The largest color tolerance in the active document: 100 in a CMYK document, else 255.
fn color_max(app: &VectorcraftApp) -> f64 {
color_tolerance_max(app.session.active().map(|d| d.doc.color_mode).unwrap_or_default())
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let o = options(app);
row(app, ui, &o, tl!("Fill Color"), "fillColor", Some(("fillTolerance", Tol::Plain(""), 255.0)));
let cmax = color_max(app);
row(app, ui, &o, tl!("Fill Color"), "fillColor", Some(("fillTolerance", Tol::Plain(""), cmax)));
if !pstate::<bool>(ui.ctx(), "wand-hide-stroke") {
widgets::divider(ui);
row(app, ui, &o, tl!("Stroke Color"), "strokeColor", Some(("strokeTolerance", Tol::Plain(""), 255.0)));
row(app, ui, &o, tl!("Stroke Color"), "strokeColor", Some(("strokeTolerance", Tol::Plain(""), cmax)));
row(app, ui, &o, tl!("Stroke Weight"), "strokeWeight", Some(("weightTolerance", Tol::Weight, 1000.0)));
}
if !pstate::<bool>(ui.ctx(), "wand-hide-transparency") {
@@ -93,4 +100,16 @@ mod tests {
out.textures_delta.clear();
}
}
#[test]
fn color_tolerance_fields_go_to_100_in_a_cmyk_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
assert_eq!(color_max(&app), 255.0);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert_eq!(color_max(&app), 255.0);
app.session.execute("magicWand.set", &json!({"fillTolerance": 200})).unwrap();
app.session.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": "cmyk"})).unwrap();
assert_eq!(color_max(&app), 100.0);
assert_eq!(options(&mut app)["fillTolerance"], 100.0);
}
}
+39 -7
View File
@@ -118,13 +118,32 @@ transparent that has the largest share in the blend of them that comes closest t
**Flat Logo with a color between two others.** When a traced color lies between two others, as a gray
lies between black and white, an anti-aliased edge pixel between the outer two is also a blend of the
middle color and one of them. Flat Logo then reads the pixel as the blend of the colors that lie nearest
it in the flat areas within 6 pixels, when the pixel has a neighbor darker and a neighbor lighter than the
middle color, along the line between the other two. A black disc beside a gray square on white traces
with one gray shape, the square, and no gray slivers around the disc, when its edges are sharp or blurred
by up to about half a pixel. An edge blurred by a pixel or more can still leave gray slivers along the
disc, and so can an image with noise of a level or more in its pixels. A gray stroke two or three pixels
wide beside black has no darker pixel next to it and stays gray. A soft-edged gray stroke about two
middle color and one of them. Flat Logo then reads the pixel as a blend of the outer two when the pixel
lies on an edge between them and that blend lies nearer the pixel than the blend with the middle color.
The pixel lies on such an edge when, along the line between the outer two colors, it reaches a pixel
darker than the middle color in at most 5 steps, each to the neighbor that lies farthest toward the
darker color while the pixels keep getting darker, and reaches a pixel lighter than the middle color the
same way. A blend lies as near the pixel as the farther of its colors' nearest flat areas within 6
pixels. The blend of the outer two also lies as near as the larger of the two step counts to a pixel of
each outer color, when that number is smaller.
A black disc beside a gray square on white traces with one gray shape, the square, and no gray slivers
around the disc, when its edges are sharp or blurred by up to 2 pixels, with the colors found or named.
With the colors named and edges blurred by 3 pixels, a gray of 128 is still one shape, a gray of 200
leaves 4 slivers with no area, and a light gray (230) leaves 8 slivers of up to 21 pixels. An image with
noise of a level or more in its pixels can still leave gray slivers along the disc.
With sharp edges, a gray stroke two or three pixels wide beside black has no darker pixel next to it and
stays gray, and so does a gray band along black. On edges blurred by a pixel or more, gray near black
loses some of its pixels. A soft-edged gray band up to 4 pixels wide lying along black traces as black
and white at blurs of 1.5 and 2 pixels, and so does one up to 3 pixels wide at blurs of 1 and 3 pixels; a
wider band loses some of its pixels next to black, and one 8 pixels wide keeps at least half of its gray
at blurs of 1.5 and 2 pixels. A soft-edged gray stroke 2 pixels from black can lose some or all of its
gray, one 4 pixels from black loses a few pixels (a light gray stroke 2 pixels wide, blurred by 1.5
pixels, keeps 28 of 34), and the pixels of one 6 pixels or more from black do not reach black in 5 steps
and are not read as an edge of black and white. A soft-edged gray
stroke 2 or 3 pixels wide running straight out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of
the 16 pixels nearest black. A soft-edged gray stroke about two
pixels wide that touches black traces as black and white, and one about three pixels wide that touches
black can lose most or all of its gray when it is short (12 pixels long or less). A line of gray one
pixel wide between black and white stays gray when at least 13 of its pixels touch: such a line and a
@@ -134,6 +153,19 @@ between pixels or is blurred traces as black and white. A flat area whose color
some levels off, counts as holding the named colors it is a blend of, and so do the pixels of exactly
its color that touch it.
The same holds when the left-out color lies beyond both colors of the edge, as a pale gray ground lies
beyond a gray panel and a charcoal disc: an edge pixel between the panel and the disc is also a blend of
the ground and the disc. Flat Logo reads it as a blend of the panel and the disc when, along the line
through the three colors, the pixel has a neighbor on each side of it, no neighbor lies past the panel
toward the ground, and a chain of neighbors, each nearer the panel's color than the one before, leads
from the pixel, in at most 6 steps, to the panel's color or to a flat area of the panel. The same rule
applies to a left-out color darker than both colors of the edge, and to colors that are not grays. A
charcoal disc on a gray panel on a paler ground then traces with no slivers of the ground around it when
its edges are sharp or blurred by 0.7 pixel. An edge blurred by a pixel or more can still leave slivers
of the ground. The pixels of a pale line on the disc, whether one pixel wide, blurred over three pixels
or falling between two pixels, and the edge of a gap of the ground's color between the disc and the
panel keep the ground in their blends.
**Large images.** An image of more than 1500 pixels on a side is traced as any other, only more
slowly, and the trace says so: `imageTrace.make` returns the note in `warnings` and the status bar
shows it (the [results optimization](https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html)
+29 -3
View File
@@ -2956,6 +2956,16 @@ records no undo step.
among the objects beside it in its group or layer, passing over hidden and locked objects and sublayers. When there
is no such object, the selection stays as it is.
`select.magicWand` compares fill and stroke colors by the active document's color mode. In an RGB document
`fillTolerance` and `strokeTolerance` run from 0 to 255 and measure the Euclidean distance between the display RGB
values. In a CMYK document they run from 0 to 100 and measure the Euclidean distance between the C, M, Y and K
percentages: a CMYK color's own values, and RGB, Gray and Lab colors converted to CMYK. Ten points of one ink matches
at 10, and ten points of each of two inks does not. A tolerance above 100 set in an RGB document is kept and applies
as 100 while a CMYK document is active; `magicWand.options` and `magicWand.set` report that value. `magicWand.set`
returns an error and changes no setting, `reset` included, when a given tolerance is not a number or is out of its
range (the color tolerances by the active document, 0 to 255 with no document open; `weightTolerance` 0 to 1000 pt;
`opacityTolerance` 0 to 100 %). An omitted value keeps its setting.
`select.same.textFillAndStrokeColor` (Select › Same › Text Fill & Stroke Color) selects the type objects that have
characters whose fill and stroke both match the first character of the first selected type, and returns `{count}`.
`select.same.textFillColor` and `select.same.textStrokeColor` compare the fill or the stroke alone. In type with
@@ -5407,7 +5417,7 @@ layer (its opacity, its own fills and effects, an opacity mask on the whole laye
selected. `document.inspect` reports it as `target`, and any other selection change ends it.
`appearance.transfer {source, target, copy?}` is dragging a target circle onto another: the target gets the source's
fills, strokes, effects and transparency, and the source is cleared unless `copy` (Alt-drag). Dropping a circle on the
panel's trash is `appearance.clear {ids: [id]}`. Masked objects' names have a dashed underline; while an opacity mask
panel's trash is `appearance.reduceToBasic {ids: [id]}` (Reduce to Basic Appearance; nothing is deleted). Masked objects' names have a dashed underline; while an opacity mask
is edited the panel lists only an `<Opacity Mask>` entry and the document tab says `(<Opacity Mask>/Opacity Mask)`.
```json
@@ -7008,6 +7018,20 @@ of it headless), gathered once per document state; the shape being drawn is neve
With a 100 × 100 square at (100, 100), the first starts the rectangle on its corner (200, 200); the second puts the
Pen's second anchor at (150, 431), in line with the square's centre.
With `backquote` true on a `drag` event, the `rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star` and
`lineSegment` tools leave a copy of the shape being drawn each time the pointer has moved 8 screen points since the
last copy, or since the first event with the key down; a key change with no pointer travel leaves none. Each copy is
the shape as that event showed it, with its modifiers and Up/Down counts, and is its own object. The `up` keeps the
copies and the last shape as one undo step, and Escape takes them all back. One drag leaves at most 128 copies, and a
shape with no width, height or length leaves none. The spacing and the limit are VectorCraft's own values; the
continuous duplicate itself is in the Keys for drawing table of
[the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469). With Smart
Guides off, this drag leaves a 70 × 50 and a 90 × 50 copy and the 110 × 70 rectangle:
```json
{"name":"pointer_gesture","arguments":{"tool":"rectangle","events":[{"kind":"down","x":50,"y":50},{"kind":"drag","x":100,"y":100,"backquote":true},{"kind":"drag","x":120,"y":100,"backquote":true},{"kind":"drag","x":140,"y":100,"backquote":true},{"kind":"drag","x":160,"y":120},{"kind":"up","x":160,"y":120}]}}
```
## Type preferences
- `placeholderText` (on by default): type the Type tools place (`pointer_gesture` with `type`, `areaType`…) starts with
@@ -8418,7 +8442,8 @@ height (`"100h"`) or a resolution (`"72ppi"`); raster rows name their files `@2x
otherwise. `fullDocument` writes one file per row instead (a PDF of every artboard, other formats the bounds of all
art), `includeBleed` grows each artboard by the document's bleed, `includeArtboardFill: false` (Include Artboard
Fill unchecked) leaves the artboards' background colors out of the files, `pdfs: "single"` (Export PDFs As › Single file)
writes the artboards a PDF row exports as the pages of one PDF named after the document, `subfolders` puts each
writes the artboards a PDF row exports as the pages of one PDF named after the document (it is refused with
`assets`, `layers` or `selection: "each"`, whose files each hold one item's art), `subfolders` puts each
row's files in a sub-folder (its size or format, or its own `folder`; `folders: "format"` sorts by format instead), `preset: "mobile"` or `"density"` (Android-style ldpi…xxxhdpi
sub-folders) replaces the rows, and `settings: {png: {…}, jpg: {…}, svg: {…}, pdf: {preset}}` gives every row of a
format its options. On every platform, `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters from a
@@ -11213,7 +11238,8 @@ others, each group nearest first. The measure is VectorCraft's own. It compares
Regular by its OS/2 PANOSE digits (only between faces of the same PANOSE family kind), weight and width classes, x-height,
cap height and average character width, and its `post` italic angle (a named instance of a variable font takes its `wght`
and `slnt` settings), leaving out a number either face does not give, and counts a family of another kind (serif, sans
serif, script and the font menu's other kinds) as further away. It reads these when a font is cataloged or loaded and opens
serif, script and the font menu's other kinds) as further away. A family that shares none of these numbers with `family`
comes after every family in its group that shares one. It reads these when a font is cataloged or loaded and opens
no font file when asked. `limit` (a whole number from 1 to 100000) keeps
the first ones. A missing or blank `family` fails with `` `family` is required ``, one that is not a string with
`` `family` must be a string ``, a family that isn't available or that the font menus don't list with ``font family `<name>` is not available``, and any
+11 -1
View File
@@ -857,6 +857,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Export for Screens artboard names can be double-clicked to rename them in grid or list view (#7275). Enter, a click outside the field or switching to Assets commits the name; Escape cancels the edit. The dialog stays open, checked artboards stay selected and the rename is undoable. The typed name goes to the artboard that was double-clicked even when the artboards change order while it is typed; the field closes when its artboard is deleted or another document becomes active. Evidence: `dialogs::tests_screens::double_clicking_an_artboard_name_in_export_for_screens_renames_it`, `dialogs::tests_screens::switching_export_tabs_commits_an_artboard_name`, `dialogs::tests_screens::an_artboard_name_follows_its_artboard_while_it_is_typed` and `dialogs::tests_screens::an_artboard_name_stays_with_its_document`.
- Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`.
- Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`.
- Export for Screens refuses `pdfs: "single"` with `assets`, `layers` or `selection: "each"`, whose files each hold one item's art, instead of writing the first item alone as one PDF named after the document; `pdfs: "multiple"` writes a PDF of each item, and the selection as one file writes one PDF either way. The rule is VectorCraft's own. Tests: `fileio::tests_screens::single_file_pdfs_are_refused_for_assets_layers_and_each_object`.
- Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`).
- Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`).
- Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI.
@@ -1100,6 +1101,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`).
- In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected.
- While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does.
- A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`).
- Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`).
- Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369).
- Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`).
@@ -1172,6 +1174,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
`css.export` refuses a `scope` or `path` that is not a string (`5`, `true`, `["all"]`, `null`) before writing anything, instead of exporting the selection or returning the CSS as data; a left-out `scope` still exports the selection, and a left-out `path` still returns the CSS. `css.generate` and `css.export {scope: "all"}` refuse a malformed `ids` or `id`, which they do not use, as the selection's export does.
Agents read the key object: `select.key` returns it, and `document.inspect` and the `ui.pointer` and `pointer_gesture` replies report it as `key`. `select.key` with an id that isn't a selected top-level object returns an error and leaves the key unchanged.
The Select menu's Same commands, its Object commands that select art, Next Object Above and Below, saved selections and the Magic Wand (#2655) select only objects that Select All selects and objects inside them: nothing hidden or locked, nothing in a hidden or locked group, layer or sublayer, nothing on a template layer, and in isolation mode nothing outside the isolated group or layer. In isolation mode Select All, All on Active Artboard and Inverse select nothing while the isolated group or layer, or a group or layer it is in, is hidden, locked or a template layer.
In a CMYK document the Magic Wand's Fill Color and Stroke Color tolerances run from 0 to 100 and compare the colors' CMYK values; in an RGB document they run from 0 to 255 and compare RGB values, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) gives the two ranges. The distance is VectorCraft's own: the Euclidean distance between the C, M, Y and K percentages, with RGB, Gray and Lab colors converted to CMYK. A tolerance above 100 set in an RGB document applies as 100 in a CMYK document and comes back in an RGB one. `magicWand.set` refuses a tolerance out of its range and changes nothing (`cmyk_document_compares_fill_and_stroke_colors_in_cmyk`, `set_rejects_tolerances_out_of_range_and_changes_nothing`).
Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it.
Select ▸ Object ▸ Not Aligned to Pixel Grid (`select.object.notAlignedToPixelGrid`) selects the paths and compound paths whose pixel-aligned property is off, whatever their coordinates, and leaves out guides, type, images, groups and the paths inside a compound path ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185); `tests::pixelalign::not_aligned_to_pixel_grid_selects_paths_without_the_property`, `not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected`). It also leaves out symbol instances, area type, type on a path, gradient meshes and placed documents, and the paths on template layers, in hidden or locked sublayers and on locked artboards; it selects the paths in clip groups, blends, envelopes, repeats and Intertwine groups and paths with effects (`not_aligned_to_pixel_grid_leaves_out_images_symbol_instances_and_type`, `not_aligned_to_pixel_grid_leaves_out_template_layers_locked_sublayers_and_locked_artboards`, `not_aligned_to_pixel_grid_selects_clipping_paths_and_paths_with_effects`, `not_aligned_to_pixel_grid_selects_the_paths_of_blends_envelopes_repeats_and_intertwines`, `not_aligned_to_pixel_grid_leaves_out_meshes_placed_documents_and_guides_but_takes_live_shapes`, `not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property`).
Align and Distribute Spacing keep a compound path or selected group that contains the key object in place, as they keep the key object itself.
@@ -1199,6 +1202,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812).
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812).
- **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812).
Backtick (`` ` ``) held while a rectangle, rounded rectangle, ellipse, polygon, star or line is dragged out leaves copies of the shape being drawn along the drag, each its own object: the continuous duplicate that the Keys for drawing table of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469) lists. Each copy is the shape as the drag showed it then, with its modifiers and Up/Down counts; the release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing (a copy each time the pointer has moved 8 screen points with the key down, none for the key alone) and the limit of 128 copies a drag are VectorCraft's own values, and a shape with no width, height or length leaves no copy. The arc, spiral, grid and Flare tools do not leave copies (tests `backtick_drag_leaves_copies_of_the_rectangle_being_drawn` and, through the engine, `a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step`).
Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule.
While a grid is dragged out, F lowers `rowSkew` (rectangular) or `radialSkew` (polar) by 10 percentage points and V raises it by 10; X lowers `columnSkew` (rectangular) or `concentricSkew` (polar) by 10 and C raises it by 10. Plain and Shift presses work; with Alt, Ctrl or Cmd held they do not, as for the other letters a tool takes while dragging. Each press changes the skew once and updates the preview; values stay within ±500% and remain in the tool options after release. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list the four drag keys and a 10% change. The signs (positive values follow VectorCraft's existing skew convention, so F and X lower the stored value) and one change per press with key repeat ignored are our own rules.
While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules.
@@ -1442,6 +1446,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`.
- **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515).
- **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`.
- **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`.
- **Find Font: Replace With Font From:** a dropdown under Replace With Font chooses the list the replacement font comes from: Document lists the families the document uses, once each; Recent lists the recently applied families that are installed (fonts applied with Find Font's Change and Change All included), newest first, as many as Preferences › Type › Number of Recent Fonts allows; System, the default, lists the installed families available in the font menu. The dialog opens on System with Source Sans 3 chosen, or the font menu's first family when Source Sans 3 is not installed. Choosing a list keeps the chosen font when the list has it and it is installed; otherwise Document and Recent choose the list's first installed font, and System chooses Source Sans 3 or the font menu's first family. Change and Change All are unavailable when the list has no installed font (Recent before any font was applied) and when the chosen family is not installed or is not in the shown list. Behavior reference: [Find and replace fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) (public documentation). Tests: `crates/ui-egui/src/find_font.rs`.
- **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`.
- **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`.
@@ -1598,7 +1603,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original.
- **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`.
- **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`.
- **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`.
- **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 to 2 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, against 11 and 14 gray paths before; pixel noise of a level or more can still leave gray slivers); with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white at blurs of 1.5 and 2 pixels, a soft-edged gray stroke 2 pixels from black can lose some or all of its gray and one 4 pixels away a few pixels, and a soft-edged gray stroke running out of black loses 3 or 4 pixels where it meets black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`.
- **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`.
- **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756).
While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own.
@@ -1690,6 +1696,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only.
- **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90).
- **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB.
- **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change.
- **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. Windows, the BSDs and other browsers have no sampler yet; the button is gray there.
- **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`).
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
@@ -1736,6 +1743,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui).
- **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects.
Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing.
A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`).
The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`).
An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame.
Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render).
@@ -1762,6 +1770,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; eleven generated style libraries (including Game HUD, Status Effects, Neon & Glow, Painted and Sketched, whose seven styles each repaint a solid fill with one watercolor, dry brush, pastel, charcoal or ink effect, and Textures) save and load as `.vcstyles`.
The built-in Textures graphic style library (`graphicStyle.addFromLibrary {library: "textures"}`) has eight styles that paint their fills and strokes with the texture effects: Fine Grain (Grain), Canvas Weave and Burlap Sack (Texturizer), Cracked Glaze (Craquelure), Mosaic Floor (Mosaic Tiles), Quilted Squares (Patchwork), Leaded Glass (Stained Glass) and Damp Paper (Water Paper). The help page names new graphic styles for textures ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html)) without naming them, so the styles, their names and their settings are VectorCraft's own (`tests::stylelib::textures_styles_apply_their_texture_effects_and_keep_their_params_through_save_and_open`).
In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one.
In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`).
Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`).
- **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
- **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html).
@@ -2044,6 +2053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too.
- Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613).
- Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773).
- EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines).
- **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation).
- **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac).
- **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875).
+1 -1
View File
@@ -35,7 +35,7 @@ against Illustrator's public documentation; **estimated** unless noted.
| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) |
| Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. |
| OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). |
| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`). |
| Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; the font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice); Show Similar Fonts: the ≈ button on a family's row lists the families that look like it first ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)), by VectorCraft's own measure of PANOSE, weight, width, heights, average width and italic angle, same script first, a family sharing none of these numbers with it last in its group (VectorCraft's own rule), and the ≈ chip under the filters clears it (`text.similarFonts`; evidence: `font_menu::tests::show_similar_fonts_orders_the_list_by_likeness`, `tests::similar::families_are_ordered_by_likeness`, `tests::similar::a_family_without_numbers_comes_after_the_measured_ones`). |
| Missing glyphs set in an installed font made for their script (Thai, Lao, Khmer, Myanmar first; then any font that has them) | done | Thai: Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai, TLWG |
| Full font-name matching (OpenType name ID 4) | done | #1258: loaded/cataloged faces and Missing Fonts searches; localized names and variable default faces; Windows font-service QA pending |
| Variable fonts | done | named instances as styles; Character panel › Variable Font sets each axis (`fontAxes`); the font menu's Font Technology › Variable lists only variable font families, with the script, kind and ★ filters ([Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html)); a family with a variable file beside static ones counts as variable. Evidence: `font_menu::tests::the_variable_filter_lists_only_variable_families`, `tests_axes::a_family_with_variation_axes_is_variable`, `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable` |