Merge main into fix/global-edit-preview-cache

This commit is contained in:
dotCooCoo committed 2026-11-29 11:36:55 -08:00
commit 7e5d8d368c
54 files changed
+2026 -137

No files matched your search

Generated
+2 -1
View File
@@ -8538,7 +8538,6 @@ dependencies = [
"raw-window-handle",
"rustix 1.1.6",
"serde_json",
"socket2",
"tempfile",
"vectorcraft-engine",
"vectorcraft-render",
@@ -8699,6 +8698,8 @@ dependencies = [
"craft-codepage",
"craft-doc",
"craft-docpath",
"craft-font-catalog",
"craft-font-store",
"craft-image-codecs",
"craft-jxl",
"craft-proof",
+3
View File
@@ -15,6 +15,9 @@ craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8d
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
+1
View File
@@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
+3
View File
@@ -211,6 +211,9 @@ fn main() -> ExitCode {
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
// The Language packs installed in the shared font store; `proof.installPack` returns once
// installed.
prefs_dir::use_language_packs();
let mut args: Vec<String> = std::env::args().skip(1).collect();
// Before any subcommand attaches the plug-in folder.
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
+2 -1
View File
@@ -20,10 +20,11 @@ vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] }
egui = { workspace = true }
egui_extras = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# Image loaders for `src/web.rs`, which builds only for wasm32.
egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
-2
View File
@@ -129,5 +129,3 @@ winresource = "0.1"
[dev-dependencies]
tempfile = "3"
# Bound socket buffers in real loopback transport deadline regressions.
socket2 = { workspace = true }
+4
View File
@@ -571,6 +571,10 @@ fn main() -> std::process::ExitCode {
mac_fonts::install();
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
prefs_dir::install_fonts();
// Language packs: installs and index fetches run on their own threads, so the window keeps
// working while a pack downloads.
prefs_dir::use_language_packs();
vectorcraft_engine::packs::run_in_background(true);
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
+8
View File
@@ -24,6 +24,14 @@ pub fn install_fonts() {
}
}
/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font
/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the
/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not
/// VectorCraft's preferences.
pub fn use_language_packs() {
vectorcraft_engine::packs::use_font_store();
}
/// The folder `name` next to the settings, for what the user keeps: none in a run without
/// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing.
fn store_dir(name: &str) -> Option<PathBuf> {
+79 -8
View File
@@ -446,6 +446,66 @@ impl Drop for InMask {
}
}
thread_local! {
/// While an [`InteriorProbe`] lives, whether a leaf tested without
/// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with
/// it; `None` outside a probe.
static INTERIOR_SEEN: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether
/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits
/// nothing then looks inside the unfilled closed paths with a second walk only when one of them
/// holds the point.
struct InteriorProbe {
was: Option<bool>,
}
impl InteriorProbe {
/// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths.
/// Otherwise the guard leaves things as they are, and no leaf measures an interior for it.
fn open(wanted: bool) -> Self {
Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } }
}
/// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point?
fn seen(&self) -> bool {
INTERIOR_SEEN.get() == Some(true)
}
}
impl Drop for InteriorProbe {
fn drop(&mut self) {
// A probe opened inside another passes what it saw on to it.
let seen = INTERIOR_SEEN.get() == Some(true);
INTERIOR_SEEN.set(self.was.map(|was| was || seen));
}
}
/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when
/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without
/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take
/// one with it, and hits nothing.
fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option<HitKind> {
if takes_interior(n, opt) {
return contains().then_some(HitKind::Fill);
}
if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) {
#[cfg(test)]
INTERIORS_PROBED.with(|c| c.set(c.get() + 1));
if contains() {
INTERIOR_SEEN.set(Some(true));
}
}
None
}
#[cfg(test)]
thread_local! {
/// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread.
static INTERIORS_PROBED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
/// the region it clips to. It is also under an [`InMask`] guard.
@@ -667,10 +727,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
// an unfilled closed path ([`HitOptions::unfilled_interiors`]), when the first pass passes one
// holding `p` ([`InteriorProbe`]).
let painted = HitOptions { unfilled_interiors: false, ..opt };
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
let mut probe = Some(InteriorProbe::open(interiors));
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
if pass.unfilled_interiors && !probe.take().is_some_and(|probe| probe.seen()) {
break;
}
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
@@ -1017,12 +1082,15 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
/// only when the first, without it, hits nothing.
/// only when the first, without it, hits nothing and passes an unfilled closed path holding `p`
/// ([`InteriorProbe`]).
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline);
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() {
return painted;
}
drop(probe);
hit_test_walk(doc, p, opt, skip, editable_only)
}
@@ -1672,8 +1740,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let has_fill = n.appearance.has_visible_fill();
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed);
let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten();
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
@@ -1740,7 +1808,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
}
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p))
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -2121,11 +2189,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
find.find(&art.art, &mut path, None, outline).map(|_| path)
};
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only
// when the first walk passes one holding `p` ([`InteriorProbe`]).
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline);
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
if !opt.unfilled_interiors || opt.path_only || outline {
if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() {
return None;
}
drop(probe);
walk.restart();
pick(opt)
})
+105
View File
@@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
}
/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box
/// holds (50, 50), and it is drawn nowhere near that point.
fn open_corner(d: &mut Document, o: f64) -> Node {
let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)];
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false));
Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
}
/// How many leaves [`hit_leaf`] tested while `f` ran, with its result.
fn leaves_tested<R>(f: impl FnOnce() -> R) -> (R, usize) {
LEAVES_TESTED.with(|c| c.set(0));
let r = f();
(r, LEAVES_TESTED.with(std::cell::Cell::get))
}
/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the
/// document once: looking inside unfilled closed paths tests no more leaves than a click without
/// it. An unfilled closed path that holds the point is still hit inside.
#[test]
fn a_selection_click_that_hits_nothing_walks_the_document_once() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
for i in 0..10 {
let corner = open_corner(&mut d, f64::from(i));
d.insert(Some(l), 99, corner).unwrap();
}
let p = Point::new(50.0, 50.0);
let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING));
assert_eq!(hit, None);
assert_eq!(without, 10);
let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS));
assert_eq!(hit, None);
assert_eq!(with, without, "hit_test");
let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None));
assert!(tops.is_empty());
assert_eq!(with, without, "objects_at");
// An unfilled frame below them that holds the point: the second walk finds it.
let frame = d.alloc_id();
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame));
assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]);
}
/// A hit test that does not look inside unfilled closed paths measures none of their interiors.
#[test]
fn a_hit_test_without_unfilled_interiors_measures_no_interior() {
let mut d = Document::new(200.0, 200.0);
stroked(&mut d, &FRAME, true);
let p = Point::new(50.0, 50.0);
let probed = |f: &dyn Fn()| {
INTERIORS_PROBED.with(|c| c.set(0));
f();
INTERIORS_PROBED.with(std::cell::Cell::get)
};
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test");
assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at");
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only");
assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside");
}
/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no
/// unfilled closed path of the art holds the point, walks the art once.
#[test]
fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() {
let mut d = Document::new(200.0, 200.0);
let corners: Vec<Arc<Node>> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect();
let root = Node::group(d.alloc_id(), corners);
d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) });
let l = d.layers[0].id;
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let n = d.node(inst).unwrap();
let p = Point::new(50.0, 50.0);
let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING));
assert_eq!(part, None);
assert!(without >= 10, "{without} leaves tested");
let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS));
assert_eq!(part, None);
assert_eq!(with, without);
}
#[test]
fn long_plain_stroke_hits_its_middle_and_curved_end() {
let mut d = Document::new(200.0, 200.0);
@@ -3569,3 +3651,26 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
}
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
#[test]
fn hovers_past_many_paths_read_their_anchors_once() {
use vectorcraft_geom::anchors::measured_control_anchors;
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
for i in 0..100 {
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
d.insert(Some(l), 0, n).unwrap();
}
let empty = Point::new(900.0, 900.0);
let before = measured_control_anchors();
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = measured_control_anchors() - before;
assert!(first >= 400, "the first hover reads every square's anchors: {first}");
for _ in 0..3 {
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
}
assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor");
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
}
+4
View File
@@ -89,6 +89,10 @@ windows-native-keyring-store = "1.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { version = "1.12", optional = true }
# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in
# Cargo.lock (craft-font-manager), so this adds no new crate.
craft-font-store = { workspace = true }
craft-font-catalog = { workspace = true }
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
# Linux. All MIT OR Apache-2.0.
+5
View File
@@ -65,6 +65,8 @@ pub(crate) mod objects_on_path;
mod opacitymask;
mod overprint;
pub mod package;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
mod paint;
mod panelcmds;
pub mod params;
@@ -382,6 +384,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
// Language packs need a font store, which the web build has none of.
#[cfg(not(target_arch = "wasm32"))]
v.extend(packs::specs());
v.extend(svgfilter::specs());
v.extend(newart::specs());
v.extend(colortheme::specs());
+48 -2
View File
@@ -1,5 +1,6 @@
//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
@@ -17,7 +18,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
@@ -52,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
grid
),
cmd!(
"addon.arrange.offset",
"Offset Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}",
has_multi,
offset
),
cmd!(
"addon.arrange.swap",
"Swap Objects",
@@ -228,6 +238,42 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "count": n }))
}
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.offset";
let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?;
let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position";
let reverse = switch_or(p, "reverse", false, C)?;
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
// The objects in stacking order from the back, each with its leading and trailing edge along the direction.
let mut items: Vec<(NodeId, f64, f64)> = roots
.iter()
.filter_map(|id| {
let b = effects::preview::bounds_of(d, &[*id], true)?;
Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) })
})
.collect();
if by_position {
items.sort_by(|a, b| a.1.total_cmp(&b.1));
}
if reverse {
items.reverse();
}
// The first stays; each later one starts `gap` past where the one before it now ends.
let mut end: Option<f64> = None;
let xfs: Vec<(NodeId, Affine)> = items
.iter()
.map(|&(id, start, finish)| {
let shift = end.map_or(0.0, |e| e + gap - start);
end = Some(finish + shift);
(id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }))
})
.collect();
transform_each(s, "Offset Objects", false, &xfs)?;
Ok(json!({ "count": items.len() }))
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
@@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() {
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
}
#[test]
fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() {
let mut s = session();
let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0);
let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0);
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[c, a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap();
assert_eq!(r["count"], json!(3));
assert_eq!(steps(&s), n + 1, "one undo step");
// From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y.
assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0)));
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)));
// Reversed: c stays, then b, then a. The gap defaults to 10.
s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap();
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
}
#[test]
fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() {
let mut s = session();
let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0);
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0);
select(&mut s, &[a, b, c]);
// Top to bottom: b, c, a; each 5 into the one before it, keeping its x.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap();
assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// Bottom to top: a stays, then c, then b.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
// Left to right in a row: a, b, c.
s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// Visual boxes 24 wide, touching.
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
// A 200 wide object clipped to a 30 wide mask at x 100.
let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0);
let mask = rect(&mut s, 100.0, 40.0, 30.0, 30.0);
select(&mut s, &[clipped, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0];
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, group, c]);
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// The mask starts at a's right edge, and c at the mask's.
assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask));
assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped));
assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.offset"), "off with one object");
select(&mut s, &[a, b]);
assert!(enabled(&s, "addon.arrange.offset"));
// Already 10 apart in a row.
let n = steps(&s);
s.execute("addon.arrange.offset", &json!({})).unwrap();
assert_eq!(steps(&s), n, "no step when nothing moves");
// Two objects in one group are one object: nothing to chain.
s.execute("object.group", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
assert!(!enabled(&s, "addon.arrange.offset"), "off with one group");
refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]);
s.execute("edit.undo", &json!({})).unwrap();
let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
select(&mut s, &[a, b]);
refuses(
&mut s,
"addon.arrange.offset",
&[
json!({"direction": "diagonal"}),
json!({"direction": 1}),
json!({"gap": 1e7}),
json!({"gap": -1e7}),
json!({"gap": "10"}),
json!({"order": "size"}),
json!({"reverse": "yes"}),
],
);
}
#[test]
fn swap_trades_places_and_optionally_sizes() {
let mut s = session();
+117
View File
@@ -0,0 +1,117 @@
//! Language packs as commands (#4936): list, install and remove the packs that spell-check and
//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn
//! downloading on: an install needs the Craft apps' shared download setting, which only the person
//! using an app turns on.
use serde_json::{Value, json};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
use crate::packs::{self, Outcome};
/// The Language pack commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "proof.packs",
"Language Packs",
[],
None,
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
always,
list
),
cmd!(
query "proof.installPack",
"Install Language Pack",
[],
None,
"{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}",
always,
install
),
cmd!(
query "proof.removePack",
"Remove Language Pack",
[],
None,
"{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}",
always,
remove
),
]
}
fn locale_param(p: &Value, command: &str) -> Result<String> {
let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?;
packs::parse_locale(raw).map_err(|e| bad(command, e))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "proof.packs";
match p.get("refresh") {
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) => {
not_confined(C)?;
packs::refresh().map_err(EngineError::Other)?;
}
Some(_) => return Err(bad(C, "`refresh` must be true or false")),
}
// The jobs before the installed packs: an install makes craft-proof read its pack before it
// leaves the jobs, so one that ends between the two reads is in one list or the other.
let packs::Status { installing, refreshing, errors } = packs::status();
let installed = craft_proof::packs::installed();
let backend = packs::backend();
let rows: Vec<Value> = packs::available()
.iter()
.map(|p| {
json!({
"locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class,
"spelling": p.spelling, "hyphenation": p.hyphenation,
"installed": installed.iter().any(|i| i.locale == p.locale),
})
})
.collect();
// An install that ended since the last frame shows in every document's layout.
s.poll_language_packs();
Ok(json!({
"packs": rows,
"installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::<Vec<_>>(),
"installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::<Vec<_>>(),
"refreshing": refreshing,
"errors": errors,
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
"available": backend.is_some(),
}))
}
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
/// store the Craft apps share, which is outside them.
fn not_confined(command: &str) -> Result<()> {
if crate::file_access::current().is_some() {
return Err(EngineError::Other(format!(
"automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots"
)));
}
Ok(())
}
fn install(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.installPack")?;
not_confined("proof.installPack")?;
match packs::install(&locale).map_err(EngineError::Other)? {
Outcome::Started => Ok(json!({"locale": locale, "started": true})),
Outcome::Done => {
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": true}))
}
}
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.removePack")?;
not_confined("proof.removePack")?;
packs::remove(&locale).map_err(EngineError::Other)?;
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": false}))
}
+3
View File
@@ -1914,6 +1914,9 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
// Only native builds load modules, so only they save the disabled list.
#[cfg(target_arch = "wasm32")]
let _ = (s, turn);
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
+2
View File
@@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[
"text.rescanFonts",
"text.fontList",
"text.spelling.",
// Language packs: downloads into, and removals from, the font store the Craft apps share.
"proof.",
"colorTheme.",
"magicWand.",
"eyedropper.",
@@ -6,6 +6,7 @@
pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.offset",
"addon.arrange.randomizeOpacity",
"addon.arrange.replace",
"addon.arrange.size",
+4 -3
View File
@@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize
/// not, since a save takes in the words another window saved), and a dictionary file attached.
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
/// out of date (Auto Spell Check checks the type again).
/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of
/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with
/// craft-proof's own dictionaries, which change when a Language pack is installed or removed.
pub fn dictionary_generation() -> u64 {
DICTIONARY_GENERATION.load(Ordering::Relaxed)
DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation())
}
fn dictionary_changed() {
+5
View File
@@ -12,6 +12,8 @@ pub mod guard;
pub mod inspect;
pub mod journal;
pub mod link_watch;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
pub mod schemas;
pub mod steps;
pub mod store;
@@ -220,6 +222,9 @@ pub struct Session {
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
/// that starts them ([`Session::load_plugins_in_background`]).
plugin_loads_in_background: bool,
/// The Language packs' generation the documents were last laid out for
/// ([`Session::poll_language_packs`]).
packs_seen: u64,
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
+389
View File
@@ -0,0 +1,389 @@
//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence
//! texts of a language other than English, published by storytold/craft-i18n and installed into the
//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where
//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used
//! here too, since the apps share the store.
//!
//! The store downloads only while its download setting is on, which only the person using an app
//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as
//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person
//! allowed downloads.
//!
//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of
//! installs running and one error per locale. In the desktop app installs run on a thread of their
//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents
//! again when one ends; elsewhere they return once installed.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
pub use craft_font_store::Cancel;
/// One pack the pack index lists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pack {
/// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name.
pub locale: String,
/// The language's own name (`Nederlands`).
pub name: String,
/// The download's size in bytes.
pub size: u64,
/// SPDX licence expression of the pack's data.
pub licence: String,
/// The licence class: `Embeddable` or `Download-only`.
pub class: String,
/// Whether it has a spelling dictionary.
pub spelling: bool,
/// Whether it has hyphenation patterns.
pub hyphenation: bool,
}
/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests.
pub trait Backend: Send + Sync {
/// The installed-packs folder craft-proof reads.
fn packs_dir(&self) -> PathBuf;
/// Whether the person allowed downloads.
fn downloads_on(&self) -> bool;
/// The packs of the index fetched last, with no request; empty before the first fetch.
fn cached_index(&self) -> Vec<Pack>;
/// Fetches the pinned pack index (needs downloads on).
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String>;
/// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads
/// on), calling `progress(done, total)` in bytes.
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>;
/// Removes the installed pack for `locale`.
fn remove(&self, locale: &str) -> Result<(), String>;
/// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any.
fn index_override(&self) -> Option<String> {
None
}
}
/// An install running.
struct Job {
done: u64,
total: u64,
cancel: Cancel,
}
#[derive(Default)]
struct Jobs {
installing: BTreeMap<String, Job>,
/// A fetch of the index running.
refreshing: Option<Cancel>,
/// The last failure of each locale's install or removal, and of the index fetch (key `""`).
errors: BTreeMap<String, String>,
}
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() });
static BACKGROUND: AtomicBool = AtomicBool::new(false);
/// Goes up each time the installed packs change.
static GENERATION: AtomicU64 = AtomicU64::new(0);
fn jobs() -> MutexGuard<'static, Jobs> {
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs.
pub fn set_backend(backend: Option<Arc<dyn Backend>>) {
let dir = backend.as_ref().map(|b| b.packs_dir());
*BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend;
craft_proof::packs::set_packs_dir(dir);
changed();
}
/// The backend [`set_backend`] set.
pub fn backend() -> Option<Arc<dyn Backend>> {
BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads
/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there
/// are no packs.
pub fn use_font_store() {
let env = craft_font_catalog::FontEnv::from_process();
set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc<dyn Backend>));
}
/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps
/// working) instead of returning once they are done.
pub fn run_in_background(on: bool) {
BACKGROUND.store(on, Ordering::Relaxed);
}
/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]).
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// Read the packs folder again: spelling and hyphenation in its languages change.
fn changed() {
craft_proof::packs::reload();
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// Whether an install or an index fetch is running.
pub fn busy() -> bool {
let j = jobs();
!j.installing.is_empty() || j.refreshing.is_some()
}
/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language
/// tag of letters and digits, at most 35 bytes, in parts of at most 8.
pub fn parse_locale(raw: &str) -> Result<String, String> {
let l = raw.trim().to_ascii_lowercase().replace('_', "-");
let ok = !l.is_empty()
&& l.len() <= 35
&& l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::<String>())) }
}
fn no_backend() -> String {
"Language packs aren't available: there is no font store folder for this user".into()
}
fn downloads_off() -> String {
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
}
/// The packs the index fetched last lists.
pub fn available() -> Vec<Pack> {
backend().map(|b| b.cached_index()).unwrap_or_default()
}
/// What `proof.packs` reports about the jobs.
pub struct Status {
/// The installs running, as (locale, bytes done, bytes in all).
pub installing: Vec<(String, u64, u64)>,
/// Whether the index is being fetched.
pub refreshing: bool,
/// The last error of each locale (`""`: the index fetch).
pub errors: BTreeMap<String, String>,
}
/// The jobs running and the last errors.
pub fn status() -> Status {
let j = jobs();
Status {
installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(),
refreshing: j.refreshing.is_some(),
errors: j.errors.clone(),
}
}
/// What an install or a fetch did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
/// Done.
Done,
/// Running in the background ([`run_in_background`]).
Started,
}
/// Runs `job` on a thread of its own in the background, else here and gives its own result (never
/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its
/// thread can't start.
fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result<Outcome, String> {
if !BACKGROUND.load(Ordering::Relaxed) {
return job().map(|()| Outcome::Done);
}
match std::thread::Builder::new().name("language-pack".into()).spawn(move || {
// The result is kept in the shared errors for `proof.packs`.
let _ = job();
}) {
Ok(_) => Ok(Outcome::Started),
Err(e) => {
undo();
Err(format!("couldn't start the download: {e}"))
}
}
}
/// Fetches the pinned pack index again. Needs downloads on.
pub fn refresh() -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let cancel = {
let mut j = jobs();
if j.refreshing.is_some() {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.refreshing = Some(cancel.clone());
j.errors.remove("");
cancel
};
run(
move || {
let r = b.fetch_index(&cancel).map(|_| ());
let mut j = jobs();
j.refreshing = None;
if let Err(e) = &r {
j.errors.insert(String::new(), e.clone());
}
r
},
|| jobs().refreshing = None,
)
}
/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs
/// downloads on. Spelling and hyphenation in that language use it once it is installed.
pub fn install(locale: &str) -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let locale = locale.to_string();
let cancel = {
let mut j = jobs();
if j.installing.contains_key(&locale) {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() });
j.errors.remove(&locale);
cancel
};
let l = locale.clone();
run(
move || {
let r = install_now(&*b, &l, &cancel);
// craft-proof reads the new pack before the job ends, so a caller that sees no
// install running sees the pack installed (`proof.packs`, `busy`).
if r.is_ok() {
changed();
}
let mut j = jobs();
j.installing.remove(&l);
if let Err(e) = &r {
j.errors.insert(l, e.clone());
}
r
},
|| {
jobs().installing.remove(&locale);
},
)
}
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
return Err(format!("there is no Language pack for {locale}"));
}
b.install(locale, cancel, &mut |done, total| {
if let Some(job) = jobs().installing.get_mut(locale) {
(job.done, job.total) = (done, total);
}
})
}
/// Stops the install of `locale` (or the index fetch, for `""`) if one is running.
pub fn cancel(locale: &str) {
let j = jobs();
let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) };
if let Some(c) = c {
c.cancel();
}
}
/// Removes the installed pack for `locale`; not while it is installing.
pub fn remove(locale: &str) -> Result<(), String> {
let b = backend().ok_or_else(no_backend)?;
if jobs().installing.contains_key(locale) {
return Err(format!("the {locale} pack is still installing"));
}
let r = b.remove(locale);
changed();
let mut j = jobs();
match &r {
Ok(()) => j.errors.remove(locale),
Err(e) => j.errors.insert(locale.to_string(), e.clone()),
};
r
}
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
/// packs), pinned by the sha256 of its `index.json`. The font store reads
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin {
url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json",
sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b",
};
/// The font store as the packs [`Backend`].
struct FontStoreBackend {
store: craft_font_store::FontStore,
/// The index read or fetched last: an install takes its entry (URL, size, sha256) from it.
index: Mutex<Option<craft_font_store::PackIndex>>,
}
impl FontStoreBackend {
fn new(store: craft_font_store::FontStore) -> Self {
Self { store, index: Mutex::new(None) }
}
fn keep(&self, index: craft_font_store::PackIndex) -> Vec<Pack> {
let packs = index
.packs
.iter()
.map(|e| Pack {
locale: e.locale.clone(),
name: e.name.clone(),
size: e.size,
licence: e.licence.clone(),
class: e.class.clone(),
spelling: e.spelling,
hyphenation: e.hyphenation,
})
.collect();
*self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index);
packs
}
}
impl Backend for FontStoreBackend {
fn packs_dir(&self) -> PathBuf {
self.store.language_packs_dir()
}
fn downloads_on(&self) -> bool {
self.store.network() == craft_font_store::Network::On
}
fn cached_index(&self) -> Vec<Pack> {
self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default()
}
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String> {
let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?;
Ok(self.keep(index))
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone();
let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?;
let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone();
self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string())
}
fn remove(&self, locale: &str) -> Result<(), String> {
self.store.remove_language_pack(locale).map_err(|e| e.to_string())
}
fn index_override(&self) -> Option<String> {
craft_font_store::language_pack_index_overridden()
}
}
/// The font store backend in `dir`, for tests that need the real store without a request.
#[cfg(test)]
pub(crate) fn font_store_in(dir: PathBuf) -> Arc<dyn Backend> {
Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent)))
}
+12 -6
View File
@@ -2140,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let name = &text_arg(arg(a, 1), "name")?;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
@@ -2158,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
/// or a Boolean becomes the text `String(value)` gives.
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let note = &text_arg(arg(a, 1), "note")?;
if note.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the note is too long".into()));
}
let item = this_item(h, a)?;
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
if !same {
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
@@ -2196,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -2206,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let locked = boolean(arg(a, 1), "locked")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -2216,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let v = number(arg(a, 1), "opacity")?;
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
@@ -2225,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
// replaces the one the graph keeps for its series or kind.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let item = this_item(h, a)?;
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
@@ -2271,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
/// would still replace the blend mode a graph keeps for the item's series or kind.
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let mode = match arg(a, 1) {
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
_ => None,
};
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
let item = this_item(h, a)?;
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
@@ -2403,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
}
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let p = point(arg(a, 1), "position")?;
move_to(h, a, Some(p[0]), Some(p[1]))
}
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let x = coordinate(arg(a, 1), "left")?;
move_to(h, a, Some(x), None)
}
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let y = coordinate(arg(a, 1), "top")?;
move_to(h, a, None, Some(y))
}
@@ -2421,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
/// objects included.
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
let item = this_item(h, a)?;
let what = if width { "width" } else { "height" };
let size = number(arg(a, 1), what)?;
if size <= 0.0 || size > MAX_SIZE {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
+98 -21
View File
@@ -1225,7 +1225,26 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer {
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
path_at(h, *run, *uid, *high, *low)
let item = path_at(h, *run, *uid, *high, *low)?;
flush_other(h, item)?;
Ok(item)
}
/// Writes the waiting point changes of another path in the same Objects on Path group as `item`.
fn flush_other(h: &super::Host, item: Item) -> std::result::Result<(), HostError> {
let waiting = h.dom.pending.borrow().as_ref().map(|(w, _)| *w);
let other = waiting.is_some_and(|w| {
w.doc.uid == item.doc.uid
&& w.id != item.id
&& with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let read = d.ancestry(item.id).unwrap_or_default();
d.ancestry(w.id).is_some_and(|a| {
a.iter().any(|g| read.contains(g) && d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))
})
})
});
if other { flush(h) } else { Ok(()) }
}
/// `typename` of the points of a path that is still in its document.
@@ -1322,7 +1341,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths. While the object model writes one path's points
/// ([`super::State`]'s `one_path`), only that path is looked at in its document.
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
/// Objects on Path group are looked at in its document.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
@@ -1335,9 +1355,24 @@ pub(super) fn see_all_points(h: &super::Host) {
let mut keys = Vec::new();
// The documents that changed since the last look, kept as they are now.
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
// Editing a path in an Objects on Path group can move other paths in the group.
let mut moved = Vec::new();
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
Some(st) => {
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
let d = &st.doc;
let group = d.ancestry(item.id).and_then(|a| {
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
});
if let Some(g) = group {
g.walk(&mut |n: &crate::doc::Node| {
if n.id != item.id && paths.contains_key(&n.id.0) {
moved.push((*uid, n.id.0));
}
});
}
}
docs.insert(*uid, st.doc.clone());
}
None => {
@@ -1345,7 +1380,10 @@ pub(super) fn see_all_points(h: &super::Host) {
}
}
match one {
Some(item) if item.doc.uid == *uid => keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))),
Some(item) if item.doc.uid == *uid => {
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
keys.append(&mut moved);
}
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
}
}
@@ -1432,6 +1470,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
}
@@ -1664,38 +1703,69 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer {
let sel = &st.selection;
(sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone())
};
// Writing the points can prune the selection, and selecting loads the selected paths' paint
// into new art, so new art's paint, the defaults a script set included, is put back.
keeping_paint(h, || remove_point(h, item, i, selected))?;
cut_points(h, item);
Ok(Data::Undefined)
}
/// Removes point `i` of the path of `item` for [`pt_remove`], and renumbers `selected`, the
/// direct selection of the path's points before the removal.
fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::doc::Selection>) -> std::result::Result<(), HostError> {
let removed = edit_points(h, item, |subs| {
let (s, j) = locate(subs, i)?;
let sp = subs.get_mut(s)?;
// The segment that closes a closed subpath ends at its first anchor.
let closing = (sp.closed && j == 0).then(|| sp.anchors.len() - 1);
// The segment that closes a closed subpath runs from its last anchor to its first.
let last = sp.closed.then(|| sp.anchors.len() - 1);
sp.anchors.remove(j);
let gone = sp.anchors.is_empty();
if gone {
subs.remove(s);
}
Some((s, j, gone, closing))
Some((s, j, gone, last))
})?;
if let (Some((s, j, gone, closing)), Some(mut sel)) = (removed, selected) {
// The points are written first, and the selection is then set with selection commands,
// which the journal records with the edit.
flush(h)?;
renumber_selected(&mut sel, item.id, s, j, gone, closing);
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
})?;
if let (Some((s, j, gone, last)), Some(before)) = (removed, selected) {
let mut sel = before.clone();
renumber_selected(&mut sel, item.id, s, j, gone, last);
// A selection the removal leaves as it was waits with the points, so that removals in a
// row are written together, unless its anchors are now all of the path's, which selects
// the path whole, or the path is in an Objects on Path group, which places it again.
let wait = sel == before && {
let valid = read_points(h, item, |subs| {
sel.anchors.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| *k < sp.anchors.len())))
&& sel.segments.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| sp.has_segment(*k, true))))
})?;
let total = points_of(h, item)?;
let all = sel.anchors.get(&item.id).is_some_and(|a| a.len() >= total) && !sel.segments.contains_key(&item.id);
let on_path = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
d.ancestry(item.id).is_some_and(|a| a.iter().any(|g| d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)))
});
valid && !all && !on_path
};
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
})?;
}
}
cut_points(h, item);
Ok(Data::Undefined)
Ok(())
}
/// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was
/// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other
/// ends leave the selection, unless a segment still selected ends there, and the anchors, segments
/// and subpaths after it keep the points they selected. `closing` is the segment that closed the
/// subpath at the removed anchor, when it did.
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, closing: Option<usize>) {
/// and subpaths after it keep the points they selected. `last` is the index of the subpath's last
/// anchor before the removal when the subpath is closed: its closing segment runs from that anchor
/// to anchor 0.
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, last: Option<usize>) {
// The closing segment ends at the removed anchor when the removed anchor is the first one.
let closing = last.filter(|_| j == 0);
// An anchor (or a segment, by its first anchor) after the removed one moves down one place.
let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> {
match p.cmp(&s) {
@@ -1713,7 +1783,14 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u
let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect();
for (p, k) in cut {
// Segment k runs from anchor k to anchor k + 1; one of the two is the removed one.
let other = if k == j { k + 1 } else { k };
// The closing segment of a closed subpath ends at anchor 0.
let other = if k != j {
k
} else if last == Some(k) {
0
} else {
k + 1
};
// The closing segment's other end is its first anchor, the old last one.
let other = if closing == Some(k) { k } else { other };
ends.extend(shift((p, other), false));
+1
View File
@@ -163,6 +163,7 @@ pub fn refused_to_scripts(id: &str) -> bool {
"edit.undoGroup.",
"file.recovery.",
"stroke.widthProfile.",
"proof.",
];
const IDS: &[&str] = &[
"text.addFontFiles",
+2 -1
View File
@@ -111,6 +111,7 @@ impl Session {
plugin_dir: None,
plugin_loads: Default::default(),
plugin_loads_in_background: false,
packs_seen: 0,
scripts_dir: None,
startup_scripts_dir: None,
script_listing_clock: Default::default(),
@@ -359,7 +360,7 @@ impl Session {
/// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved
/// document stays saved, and its undo history keeps its documents as they are. The document is
/// left as it is when `stale` picks nothing.
fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
let Some(st) = self.docs.get_mut(index) else { return };
if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) {
return;
+38
View File
@@ -1093,6 +1093,44 @@ impl Session {
self.plugin_loads_in_background = on;
}
/// Lays every document out again when the installed Language packs changed since the last
/// call (an install in the background ended, or a pack was removed), since spelling and
/// hyphenation in their languages change → whether an install or index fetch is still running,
/// so the app looks again. The app calls it as its frames go by.
pub fn poll_language_packs(&mut self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
// Busy first: an install moves the generation on before it ends, so when none is
// running any more its change is read below.
let busy = crate::packs::busy();
let now = crate::packs::generation();
if now != self.packs_seen {
self.packs_seen = now;
for index in 0..self.docs.len() {
// A document in the back is measured in its own composite fonts, lent for the
// measuring, as `measure_back_document` does: the front document's are the
// ones registered, and one of the same name may differ.
let back_fonts = (self.active != Some(index)).then(|| self.docs.get(index).map(|st| st.doc.composite_fonts.clone())).flatten();
let lent = back_fonts.as_ref().map(|fonts| vectorcraft_text::FontDb::global().lend_document_composite_fonts(fonts));
// Type in a language of its own may break its lines elsewhere now: it is
// measured again (not an edit), so its selection box and hits follow.
self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some()));
drop(lent);
if let Some(st) = self.docs.get_mut(index) {
st.revision += 1;
}
}
}
busy
}
// The web build has no packs.
#[cfg(target_arch = "wasm32")]
{
let _ = self.packs_seen;
false
}
}
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
/// load's file-name order, up to the first module still loading, without waiting → whether
/// some are still loading. A load starts once the loads before it are done. When another
+2
View File
@@ -128,6 +128,8 @@ mod outlineobject;
pub(super) mod outlinestroke;
mod overprint;
mod package;
#[cfg(not(target_arch = "wasm32"))]
mod packs;
mod paintopacity;
mod paintproxy;
mod panelcmds;
+267
View File
@@ -0,0 +1,267 @@
//! Language packs (`proof.packs`, `proof.installPack`, `proof.removePack`, #4936): an installed pack
//! spell-checks its language in the documents, an install needs downloads on, and a pack installed
//! in the background reaches the documents once it ends.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use serde_json::{Value, json};
use crate::packs::{self, Backend, Cancel, Pack};
use crate::*;
/// Tests that set the process-wide packs backend take turns.
fn packs_lock() -> MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Puts the process back to no packs and no background installs when dropped, also when the test
/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then
/// it deletes the test's folder.
struct Reset(PathBuf);
impl Drop for Reset {
fn drop(&mut self) {
while packs::busy() {
for (locale, _, _) in packs::status().installing {
packs::cancel(&locale);
}
packs::cancel("");
std::thread::yield_now();
}
packs::run_in_background(false);
packs::set_backend(None);
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A new folder for one test.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-packs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// Writes a small Dutch pack into `packs/nl`, laid out as the font store unpacks one.
fn write_dutch_pack(packs: &Path) {
let dir = packs.join("nl");
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
std::fs::write(dir.join("pack.toml"), "locale = \"nl\"\nname = \"Nederlands (test)\"\nlicence = \"MIT\"\n").unwrap();
std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap();
std::fs::write(dir.join("spelling.aff"), "SET UTF-8\nTRY esianrtolducgmphbykfvwjzxq\n").unwrap();
std::fs::write(dir.join("spelling.dic"), "5\nhet\nhuis\nen\nde\nfiets\n").unwrap();
}
/// A session with a new document holding Dutch point type with one misspelt word, `fietz`.
fn dutch_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Het huis en de fietz"})).unwrap()["id"].clone();
s.execute("text.setFormat", &json!({"ids": [id], "language": "Dutch"})).unwrap();
s
}
/// The unknown words a check lists, as (word, lang).
fn unknown(s: &mut Session) -> Vec<(String, String)> {
let r = s.execute("text.spelling.check", &json!({})).unwrap();
r["words"].as_array().unwrap().iter().map(|w| (w["word"].as_str().unwrap().into(), w["lang"].as_str().unwrap().into())).collect()
}
fn installed_locales(s: &mut Session) -> Vec<String> {
let r = s.execute("proof.packs", &json!({})).unwrap();
r["installed"].as_array().unwrap().iter().map(|p| p["locale"].as_str().unwrap().to_string()).collect()
}
#[test]
fn a_pack_in_the_font_store_checks_its_language_until_it_is_removed() {
let _turn = packs_lock();
let root = folder("store");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
// A pack another Craft app installed into the shared store.
let store = packs::font_store_in(root.clone());
write_dutch_pack(&store.packs_dir());
packs::set_backend(Some(store));
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())], "checked in Dutch by the pack");
assert_eq!(installed_locales(&mut s), ["nl"]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!((listed["available"].clone(), listed["downloads"].clone()), (json!(true), json!(false)), "downloads stay off");
let before = s.doc().unwrap().revision;
assert_eq!(s.execute("proof.removePack", &json!({"locale": "NL"})).unwrap()["installed"], false);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), without, "checked as before the pack");
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.removePack", &json!({"locale": "nl"})).is_err(), "no longer installed");
}
/// A stand-in for the font store: it lists a Dutch pack and installs it by writing its files.
struct Fake {
dir: PathBuf,
downloads: bool,
/// While set, an install waits until it is cleared.
hold: AtomicBool,
}
impl Backend for Fake {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
self.downloads
}
fn cached_index(&self) -> Vec<Pack> {
let nl = Pack {
locale: "nl".into(),
name: "Nederlands".into(),
size: 2,
licence: "MIT".into(),
class: "Embeddable".into(),
spelling: true,
hyphenation: false,
};
vec![nl]
}
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
Ok(self.cached_index())
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
progress(1, 2);
while self.hold.load(Ordering::Relaxed) {
if cancel.is_cancelled() {
return Err("cancelled".into());
}
std::thread::yield_now();
}
// The index lists only Dutch, which `packs::install` checks first.
if locale != "nl" {
return Err(format!("asked to install {locale}"));
}
write_dutch_pack(&self.dir);
Ok(())
}
fn remove(&self, locale: &str) -> std::result::Result<(), String> {
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
}
}
fn error(s: &mut Session, id: &str, p: Value) -> String {
s.execute(id, &p).unwrap_err().to_string()
}
#[test]
fn an_install_needs_downloads_on_and_a_pack_the_index_lists() {
let _turn = packs_lock();
let root = folder("fake");
let _reset = Reset(root.clone());
let mut s = dutch_session();
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("aren't available"), "no store, no packs");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: false, hold: AtomicBool::new(false) })));
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("downloading is turned off"));
assert!(error(&mut s, "proof.packs", json!({"refresh": true})).contains("downloading is turned off"));
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
for bad in [json!({}), json!({"locale": ""}), json!({"locale": "../nl"}), json!({"locale": 5})] {
assert!(s.execute("proof.installPack", &bad).is_err(), "{bad} is refused");
}
assert!(!root.exists(), "a refused locale writes nothing");
assert!(error(&mut s, "proof.installPack", json!({"locale": "fy"})).contains("no Language pack for fy"));
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["fy"].is_string(), "the failure is reported");
let before = s.doc().unwrap().revision;
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl_NL"})).contains("no Language pack for nl-nl"), "nl_NL reads as nl-nl");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["packs"][0]["installed"], true);
}
#[test]
fn an_install_in_the_background_reaches_the_documents_when_it_ends() {
let _turn = packs_lock();
let root = folder("background");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
let fake = Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) });
packs::set_backend(Some(fake.clone()));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true, "asked again, it is the same install");
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["installing"][0]["locale"], "nl");
assert!(error(&mut s, "proof.removePack", json!({"locale": "nl"})).contains("still installing"));
assert_eq!(unknown(&mut s), without, "not used before it is installed");
let before = s.doc().unwrap().revision;
fake.hold.store(false, Ordering::Relaxed);
while s.poll_language_packs() {
std::thread::yield_now();
}
s.poll_language_packs();
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
}
#[test]
fn a_cancelled_background_install_installs_nothing() {
let _turn = packs_lock();
let root = folder("cancel");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) })));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
packs::cancel("nl");
while packs::busy() {
std::thread::yield_now();
}
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled"));
}
/// A caller confined to automation roots lists the packs but can't fetch, install or remove them:
/// the store they are written into is outside its roots.
#[test]
fn a_confined_caller_lists_packs_but_cannot_change_them() {
let _turn = packs_lock();
let root = folder("confined");
let _reset = Reset(root.clone());
let roots_dir = folder("confined-roots");
std::fs::create_dir_all(&roots_dir).unwrap();
let mut s = dutch_session();
write_dutch_pack(&root);
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap();
let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string());
for (cmd, p) in
[("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))]
{
let e = confined(cmd, p).unwrap_err();
assert!(e.contains("automation path rejected"), "{cmd}: {e}");
}
assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed");
assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there");
let _ = std::fs::remove_dir_all(&roots_dir);
}
/// A script's rollback cannot put back what an install writes into the shared font store, so a
/// script cannot run the pack commands.
#[test]
fn a_script_cannot_install_a_pack() {
let _turn = packs_lock();
let root = folder("script");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let e = error(&mut s, "script.run", json!({"source": "vc.run('proof.installPack', {locale: 'nl'});", "name": "t.js"}));
assert!(e.contains("a script cannot run `proof.installPack`"), "{e}");
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs");
}
+23
View File
@@ -1702,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() {
assert!(e.contains("Stale page item"), "{e}");
}
/// A setter on a removed item reports the stale item before it checks the value it was given.
#[test]
fn setters_on_a_stale_item_report_it_before_a_bad_value() {
let (mut s, _, _) = doc();
for set in [
"name = {}",
"note = {}",
"hidden = 'x'",
"locked = 'x'",
"opacity = 500",
"blendingMode = 'x'",
"selected = 'x'",
"position = 'x'",
"left = 'x'",
"top = 'x'",
"width = -1",
"height = -1",
] {
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};"));
assert!(e.contains("Stale page item"), "{set}: {e}");
}
}
/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
/// the revert does not name the loaded one.
#[test]
+215
View File
@@ -809,6 +809,221 @@ fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() {
assert!(!s.active().unwrap().selection.objects.contains(&a));
}
/// Removing the last anchor of a closed path with only its closing segment selected takes the
/// segment's other end, the first anchor, out of the selection too.
#[test]
fn removing_the_last_point_deselects_the_closing_segment_and_its_first_anchor() {
let (mut s, a, _) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();");
assert_eq!(selected_anchors(&s, a), None, "the first anchor is not selected");
assert!(!s.active().unwrap().selection.objects.contains(&a));
}
/// Removing a point that renumbers the selected anchors keeps the new-art stroke width a script
/// set, so the next path it draws gets it.
#[test]
fn removing_a_point_keeps_the_default_stroke_width_a_script_set() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument; d.defaultStrokeWidth = 7; d.pathItems[0].pathPoints[0].remove();\
vc.log(d.pathItems.rectangle(10, 10, 5, 5).strokeWidth);",
);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)]));
assert_eq!(out, [json!(7)]);
}
/// Removals that leave the direct selection as it was are written together, with one
/// `path.setAnchors`.
#[test]
fn removals_that_keep_the_selection_are_written_together() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap();
let start = s.journal.len();
log(&mut s, "var q = app.activeDocument.pathItems[0].pathPoints; q[3].remove(); q[2].remove();");
let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count();
assert_eq!(writes, 1);
assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors.len(), 2);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)]));
}
#[test]
fn removing_a_replacement_point_clears_selection_of_a_missing_subpath() {
for segments in [false, true] {
let (mut s, a, _) = doc();
let anchors: Vec<Value> = (0..3).map(|x| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false})).collect();
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": [{"anchors": anchors, "closed": false}, {"anchors": anchors, "closed": false}]}))
.unwrap();
if segments {
s.execute("select.segments", &json!({"id": a.0, "segments": [[1, 0]], "mode": "set"})).unwrap();
} else {
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[1, 0]]}], "mode": "set"})).unwrap();
}
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [20, 0], [30, 0]]);\
p.pathPoints[3].remove(); vc.log(p.selected); vc.log(p.selectedPathPoints.length);",
);
assert_eq!(out, [json!(false), json!(0)], "segments: {segments}");
let path = node(&s, a);
let subs = &path.path_data().unwrap().subpaths;
assert_eq!(subs.len(), 1);
assert_eq!(subs[0].anchors.len(), 3);
assert_eq!(selected_anchors(&s, a), None);
let sel = &s.active().unwrap().selection;
assert!(!sel.segments.contains_key(&a));
assert!(!sel.objects.contains(&a));
}
}
#[test]
fn reading_an_unrelated_path_keeps_point_edits_written_together() {
let (mut s, a, b) = doc();
let before = node(&s, b);
let start = s.journal.len();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, p = P[0].pathPoints, q = P[1].pathPoints;\
p[0].anchor = [20, 30]; vc.log(q.length); vc.log(q[0].anchor); p[1].anchor = [50, 30];",
);
let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count();
assert_eq!(writes, 1);
assert_eq!(out, [json!(4), json!([100, 200])]);
assert_eq!(node(&s, b), before);
let edited = node(&s, a);
let anchors = &edited.path_data().unwrap().subpaths[0].anchors;
assert_eq!(anchors[0].p, vectorcraft_geom::Point::new(20.0, 270.0));
assert_eq!(anchors[1].p, vectorcraft_geom::Point::new(50.0, 270.0));
}
/// Removing the one point that was not direct-selected leaves every point selected, which
/// selects the path whole.
#[test]
fn removing_the_only_unselected_point_selects_the_path_whole() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]}], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();");
assert_eq!(selected_anchors(&s, a), None);
assert!(s.active().unwrap().selection.objects.contains(&a));
}
/// Removing a point of a direct-selected member of an Objects on Path group writes it at once, so
/// its points read where the group places it.
#[test]
fn removing_a_point_of_a_selected_member_reads_where_the_group_places_it() {
let (mut s, b) = doc_on_path();
s.execute("select.anchorsMany", &json!({"items": [{"id": b.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, m = P.getByName('m');\
m.pathPoints[3].remove(); m.pathPoints[2].remove(); vc.log(m.pathPoints[0].anchor);\
P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor);",
);
assert_eq!(out[0], out[1], "the member read where it is after the run");
}
/// [`doc`] with path `drive`, the path of an Objects on Path group that holds `b`, named `m`.
fn doc_on_path() -> (Session, NodeId) {
let (mut s, _, b) = doc();
let c = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
log(&mut s, "var p = app.activeDocument.pathItems; p[0].name = 'drive'; p[2].name = 'm';");
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("object.objectsOnPath.attach", &json!({"path": c.0, "ids": [b.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
(s, b)
}
/// Reading the points of a path writes the waiting point changes of another path first, so a
/// member of an Objects on Path group reads where the group's edited path moved it.
#[test]
fn reading_a_member_point_after_editing_its_group_path_reads_where_it_moved() {
let (mut s, _) = doc_on_path();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\
var x = m.pathPoints[0].anchor[0];\
for (var i = 0; i < g.pathPoints.length; i++) { var q = g.pathPoints[i]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; }\
vc.log(m.pathPoints[0].anchor[0] - x);\
P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor[0] - x);",
);
assert_ne!(out[1], json!(0), "the member moved");
assert_eq!(out[0], out[1], "the member read where it is after the run");
}
/// A member point read before the group's path is edited is stale afterwards, as the engine moved
/// the member, even when an undo puts the member back.
#[test]
fn a_member_point_read_before_its_group_path_changes_is_stale() {
let (mut s, _) = doc_on_path();
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = g.pathPoints[0]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
}
#[test]
fn a_point_in_a_nested_member_is_stale_after_another_path_changes_and_undoes() {
let (mut s, a, b) = doc();
log(&mut s, "var P = app.activeDocument.pathItems; P[0].name = 'edit'; P[1].name = 'm';");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.active().unwrap().doc.parent_of(a).unwrap();
let drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
s.execute("object.objectsOnPath.attach", &json!({"path": drive.0, "ids": [group.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = art(&s);
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
assert_eq!(art(&s), before);
}
#[test]
fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_changes_and_undoes() {
let (mut s, a, b) = doc();
log(&mut s, "app.activeDocument.pathItems[0].name = 'drive';");
s.execute("object.objectsOnPath.attach", &json!({"path": a.0, "ids": [b.0]})).unwrap();
let inner = s.active().unwrap().doc.parent_of(a).unwrap();
let sibling = rect(&mut s, 100.0, 200.0, 50.0, 50.0);
s.execute("object.setProps", &json!({"ids": [sibling.0], "name": "m"})).unwrap();
s.execute("select.set", &json!({"ids": [inner.0, sibling.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.active().unwrap().doc.parent_of(inner).unwrap();
let outer_drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
s.execute("object.objectsOnPath.attach", &json!({"path": outer_drive.0, "ids": [group.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = art(&s);
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\
vc.log(m.pathPoints[0].anchor);\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]];\
vc.log(m.pathPoints[0].anchor); app.undo();",
);
assert_ne!(out[0], out[1], "the sibling outside the inner group moved");
assert_eq!(art(&s), before);
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
assert_eq!(art(&s), before);
}
/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke.
fn doc_with_paints() -> (Session, NodeId) {
let (mut s, a, _) = doc();
+2
View File
@@ -995,6 +995,8 @@ fn structured_junk() {
("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})),
("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})),
("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})),
("addon.arrange.offset", json!({"direction": "column", "gap": -1e6, "order": "position", "reverse": true})),
("addon.arrange.offset", json!({"direction": "diagonal", "gap": f64::MAX, "order": 3, "reverse": "x"})),
("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})),
("addon.arrange.replace", json!({"fit": "proportional", "keep": true})),
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
+108 -3
View File
@@ -8,12 +8,16 @@
//! in and rebuilds the table, which has one entry per chunk.
//!
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
//!
//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`])
//! once it has been measured, until the list changes.
use std::borrow::Cow;
use std::fmt;
use std::ops::{Index, IndexMut, RangeBounds};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use kurbo::Rect;
use serde::{Deserialize, Serialize};
use crate::path::Anchor;
@@ -40,12 +44,49 @@ pub struct Anchors {
ends: Vec<usize>,
/// The number of anchors.
len: usize,
/// The box round every anchor's point and handles, once measured; emptied by every change.
control: OnceLock<Rect>,
}
thread_local! {
/// [`measured_control_anchors`] of this thread.
static MEASURED_CONTROL_ANCHORS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many anchors [`Anchors::control_bounds`] has read on this thread.
pub fn measured_control_anchors() -> u64 {
MEASURED_CONTROL_ANCHORS.get()
}
impl Anchors {
/// An empty list.
pub const fn new() -> Self {
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() }
}
/// The box round every anchor's point and handles, or `None` when the list is empty. The list
/// reads its anchors for it once, and again only after it has changed.
pub fn control_bounds(&self) -> Option<Rect> {
if self.len == 0 {
return None;
}
Some(*self.control.get_or_init(|| {
MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64));
let mut r: Option<Rect> = None;
for c in &self.chunks {
for a in c.iter() {
for p in [a.p, a.h_in, a.h_out] {
r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p)));
}
}
}
r.unwrap_or_default()
}))
}
/// Forget the measured [`Self::control_bounds`]: every change calls it.
fn changed(&mut self) {
self.control.take();
}
/// The number of anchors.
@@ -85,6 +126,7 @@ impl Anchors {
if i >= self.len {
return None;
}
self.changed();
let (c, o) = self.locate(i);
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
}
@@ -101,11 +143,13 @@ impl Anchors {
/// The first anchor to change.
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.first_mut()?).first_mut()
}
/// The last anchor to change.
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.last_mut()?).last_mut()
}
@@ -118,6 +162,7 @@ impl Anchors {
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
/// iterator reaches it.
pub fn iter_mut(&mut self) -> IterMut<'_> {
self.changed();
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
self.chunks.iter_mut().flat_map(chunk)
}
@@ -177,6 +222,7 @@ impl Anchors {
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
fn reindex(&mut self) {
self.changed();
self.chunks.retain(|c| !c.is_empty());
self.len = self.chunks.iter().map(|c| c.len()).sum();
let n = self.chunks.len();
@@ -193,6 +239,7 @@ impl Anchors {
/// Add `a` at the end.
pub fn push(&mut self, a: Anchor) {
self.changed();
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
_ => {
@@ -210,6 +257,7 @@ impl Anchors {
/// Remove the last anchor.
pub fn pop(&mut self) -> Option<Anchor> {
self.changed();
let last = self.chunks.last_mut()?;
let a = Arc::make_mut(last).pop();
if last.is_empty() {
@@ -489,6 +537,7 @@ impl Index<usize> for Anchors {
impl IndexMut<usize> for Anchors {
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
fn index_mut(&mut self, i: usize) -> &mut Anchor {
self.changed();
let (c, o) = self.locate(i);
&mut Arc::make_mut(&mut self.chunks[c])[o]
}
@@ -501,7 +550,7 @@ impl From<Vec<Anchor>> for Anchors {
}
let len = v.len();
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
Self { chunks, ends: Vec::new(), len }
Self { chunks, ends: Vec::new(), len, control: OnceLock::new() }
}
}
@@ -725,6 +774,8 @@ mod tests {
}
}
assert_eq!(a.len(), v.len(), "step {step}");
// The box kept from the step before is measured again after the edit.
assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}");
if step % 50 == 0 {
assert_eq!(a, v, "step {step}");
for i in 0..v.len() {
@@ -737,6 +788,60 @@ mod tests {
assert_eq!(a.get(v.len()), None);
}
/// The box of every anchor of `v` with its handles, measured anchor by anchor.
fn box_of(v: &[Anchor]) -> Option<Rect> {
let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
}
#[test]
fn control_bounds_read_the_anchors_once_until_they_change() {
let n = 1000;
let mut a = Anchors::from(line(n));
let read = measured_control_anchors;
let before = read();
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(read() - before, n as u64, "the first call reads every anchor");
let copy = a.clone();
for _ in 0..5 {
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(copy.control_bounds(), box_of(&line(n)));
}
assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor");
// Every change measures again, and only the list that changed.
let far = Point::new(-50.0, 900.0);
type Edit = fn(&mut Anchors, Point);
let edits: [(&str, Edit); 11] = [
("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)),
("index_mut", |a, p| a[4].h_in = p),
("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)),
("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)),
("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)),
("push", |a, p| a.push(Anchor::corner(p))),
("insert", |a, p| a.insert(1, Anchor::corner(p))),
("pop", |a, _| {
let _ = a.pop();
}),
("remove", |a, _| {
let _ = a.try_remove(0);
}),
("truncate", |a, _| a.truncate(10)),
("reverse", |a, _| a.reverse()),
];
for (k, (what, edit)) in edits.iter().enumerate() {
let p = Point::new(far.x - k as f64, far.y + k as f64);
assert!(a.control_bounds().is_some());
edit(&mut a, p);
let r = read();
assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}");
assert_eq!(read() - r, a.len() as u64, "after {what}: measured again");
}
assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box");
a.clear();
assert_eq!(a.control_bounds(), None);
}
#[test]
fn iterators_skip_and_count_as_a_slice_does() {
let v = line(1000);
+3 -4
View File
@@ -745,11 +745,10 @@ impl PathData {
}
bbox
}
/// Bounds including control handles (used for quick culling).
/// Bounds including control handles (used for quick culling). Each subpath keeps its own box
/// ([`Anchors::control_bounds`]) until its anchors change.
pub fn control_bounds(&self) -> Option<Rect> {
let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b))
}
pub fn transform(&mut self, a: Affine) {
for sp in &mut self.subpaths {
+24 -3
View File
@@ -1,5 +1,5 @@
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects,
//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
@@ -22,19 +22,21 @@ use crate::menus::{Sep, c, cp};
/// Zoom to Selection: a view command, since the view is the interface's.
pub const ZOOM: &str = "addon.arrange.zoomSelection";
const GRID: &str = "addon.arrange.grid";
const OFFSET: &str = "addon.arrange.offset";
const REPLACE: &str = "addon.arrange.replace";
const SIZE: &str = "addon.arrange.size";
const OPACITY: &str = "addon.arrange.randomizeOpacity";
const SORT: &str = "addon.arrange.sort";
/// Each dialog's command and heading.
const DIALOGS: [(&str, &str); 5] = [
const DIALOGS: [(&str, &str); 6] = [
(GRID, "Arrange in Grid"),
(OFFSET, "Offset Objects"),
(REPLACE, "Replace with Top Object"),
(SIZE, "Set Size of Each"),
(OPACITY, "Randomize Opacity"),
(SORT, "Sort Objects"),
];
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes.
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take.
const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6;
const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6;
/// The seeds the Randomize Opacity dialog offers.
@@ -56,6 +58,7 @@ const ATTRIBUTES: [(&str, &str); 7] = [
pub fn menu() -> Vec<Node> {
vec![
c("Arrange in Grid…", GRID),
c("Offset Objects…", OFFSET),
cp("Swap Objects", "addon.arrange.swap", json!({})),
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
c("Replace with Top Object…", REPLACE),
@@ -69,6 +72,7 @@ pub fn menu() -> Vec<Node> {
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
@@ -116,6 +120,17 @@ fn grid_rows(lengths: LengthUnits) -> Vec<Param> {
]
}
fn offset_rows(lengths: LengthUnits) -> Vec<Param> {
let directions = [("row", "Row (Left to Right)"), ("column", "Column (Top to Bottom)")];
let orders = [("stacking", "Stacking Order"), ("position", "Position")];
vec![
choice("direction", "Direction:", &directions, "row"),
length("gap", "Gap:", 10.0, GAPS, lengths),
choice("order", "Order:", &orders, "stacking"),
check("reverse", "Reverse Order", false),
]
}
fn replace_rows() -> Vec<Param> {
let fits = [("keep", "Actual Size"), ("bounds", "Bounds"), ("proportional", "Bounds (Fit Proportionally)")];
vec![choice("fit", "Size:", &fits, "keep"), check("keep", "Keep Original", false), scale_strokes()]
@@ -156,6 +171,10 @@ fn grid_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&grid_rows(POINTS), fields))
}
fn offset_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&offset_rows(POINTS), fields))
}
fn replace_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&replace_rows(), fields))
}
@@ -196,6 +215,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
"gapX": 10, "gapY": 10, "centerOnArtboard": false,
}),
),
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
// A new seed each time the document has changed, so running it again varies the result.
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
@@ -223,6 +243,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
let fields = form::fields_of(&rows, opening.as_object()?);
let opened = match command {
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
@@ -62,6 +62,60 @@ fn real_grid_edits_reach_the_preview_and_confirmed_geometry() {
assert!(!app.any_dialog_open());
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
#[test]
fn real_offset_edits_reach_the_preview_and_ok_applies_them_as_one_step() {
let (app, a, b) = app();
let n = steps(&app);
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Offset Objects…");
type_number(&mut panel, "Gap", "3");
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.number("gap")), Some(3.0));
{
// From the back: a stays and b starts 3 past its right edge, keeping its y.
let app = panel.app();
assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (0.0, 0.0));
assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (23.0, 100.0));
}
panel.focus("Reverse Order");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
let preview = {
// Reversed: b stays and a starts 3 past b's right edge, keeping its y.
let app = panel.app();
assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (100.0, 100.0));
assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (143.0, 0.0));
(bounds(&app, a), bounds(&app, b))
};
panel.click("OK");
panel.frame();
let app = panel.app();
assert_eq!((bounds(&app, a), bounds(&app, b)), preview);
assert_eq!(steps(&app), n + 1, "one undo step");
assert!(!app.any_dialog_open());
}
#[test]
fn real_offset_cancel_puts_the_objects_back() {
let (app, a, b) = app();
let n = steps(&app);
let before = (bounds(&app, a), bounds(&app, b));
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Offset Objects…");
type_number(&mut panel, "Gap", "50");
assert_eq!(bounds(&panel.app(), b).x0, 70.0, "the preview moves b");
panel.click("Cancel");
panel.frame();
let app = panel.app();
assert_eq!((bounds(&app, a), bounds(&app, b)), before);
assert_eq!(steps(&app), n);
assert!(!app.any_dialog_open());
}
#[test]
fn real_size_keyboard_edits_keep_unticked_sides_unchanged() {
let (app, a, b) = app();
+7 -2
View File
@@ -553,6 +553,11 @@ impl VectorcraftApp {
// what waits for them. They install after the control requests are drained, so the frame
// after the last one opens the files held for them (the desktop app does that before this
// pass) before a control request waiting for them runs.
// A Language pack installed or removed lays the documents out again; while one downloads
// the host keeps coming back to look.
if self.session.poll_language_packs() {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
if self.session.plugins_loading() {
if self.session.poll_plugin_loads() {
ctx.request_repaint_after(std::time::Duration::from_millis(50));
@@ -809,8 +814,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
root.values.set(TabCloseLook::Glyph);
// A collapsed panel column's icon groups stand apart by a hairline, as production drew them.
root.values.set(IconGroupSeparator::Rule);
// New Document's preset cards show blank paper on a flat card, as production drew them.
root.values.set(PresetCardLook::Page);
// New Document's preset cards show blank paper on a card that rests on a tile, as production drew them.
root.values.set(PresetCardLook::PageTile);
// A bare Tab on the canvas, or with nothing focused, toggles the panels (`window.dock`) instead of moving focus.
root.tab_toggles_chrome = true;
// Escape in a text field gives up its focus, reverting any typing, so the next keys are the window's.
@@ -1126,15 +1126,7 @@ macro_rules! style_dialog {
}
fn show(&mut self, ui: &mut egui::Ui, stack: &craft::ui::dialog::DialogStack) -> Option<craft::ui::dialog::DialogResult<Self::Result>> {
// A measuring run can end without running the dialog's body and then sets the first tab as the
// shown one. The dialog keeps the tab that was shown before that run.
let measuring = craft::ui::runtime::measure::active(ui.ctx());
let tab = self.inner.tab();
let shown = craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack);
if measuring && self.inner.tab() != tab {
let _ = craft::ui::dialog::StackDialog::set_json_field(&mut self.inner, ui.ctx(), "tab", serde_json::json!(tab));
}
shown
craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack)
}
fn key(&self) -> Option<&str> {
@@ -1079,6 +1079,38 @@ fn new_character_style_refuses_size_and_leading_errors_at_ok() {
}
}
/// Character Style Options and New Character Style opened on a tab other than General still show that tab after
/// their first frames, which measure the dialog before its body runs.
#[test]
fn a_style_dialog_opened_on_a_later_tab_keeps_it_through_its_first_frames() {
use egui::{Pos2, RawInput, Rect, vec2};
let mut app = app();
app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
open(&mut app, "Body");
set::<Existing>(&app, "tab", json!("advanced"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Existing>(&app)["tab"], json!("advanced"), "Character Style Options left Advanced Character Formats");
cancel::<Existing>(&mut app);
app.run("ui.newCharStyle", json!({})).unwrap();
set::<Fresh>(&app, "tab", json!("color"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Fresh>(&app)["tab"], json!("color"), "New Character Style left Character Color");
}
#[test]
fn invalid_number_keeps_last_valid_preview() {
let mut app = app();
@@ -907,6 +907,34 @@ mod tests {
assert!(st.history.undo.is_empty());
}
/// Document Setup opened on a tab other than General still shows that tab after its first frames, which
/// measure the dialog before its body runs.
#[test]
fn a_later_tab_picked_before_the_first_frame_stays_shown() {
for tab in ["Transparency", "Type", "Color"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "tab", json!(tab));
for _ in 0..5 {
frame(&mut app);
}
let shown = app.dialogs().unwrap().with(|h| {
use craft::ui::dialog::StackDialog as _;
h.get_by_id::<HostedPropertiesDialog>(id()).and_then(|d| d.json_fields())
});
assert_eq!(shown.map(|f| f["tab"].clone()), Some(json!(tab)), "Document Setup left {tab}");
}
}
#[test]
fn every_tab_draws_and_ok_is_one_undo_step() {
let (mut app, ctx) = setup_open();
@@ -1112,6 +1112,38 @@ mod tests {
assert!(inside.is_empty(), "the segments draw icons, not words: {inside:?}");
}
/// Each preset card rests on a tile, a light veil of the scrim over the dialog's surface, with its paper on it, so a
/// card that is not selected still stands apart from the dialog.
#[test]
fn resting_preset_cards_stand_on_a_tile() {
use craft::ui::runtime::env::Env;
use craft::ui::style::rgba_color;
let mut scrim = egui::Color32::TRANSPARENT;
let mut theme =
crate::testing::ui_context().run_ui(Default::default(), |ui| scrim = rgba_color(Env::of(ui).tokens.tokens().color.surface.scrim));
// The test reads the theme; no renderer applies the frame's textures.
theme.textures_delta.clear();
let mut app = app();
open(&mut app);
let out = laid_out(&mut app);
let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default();
let card = nodes
.iter()
.find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false))
.and_then(|(_, n)| n.bounds())
.map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
.expect("a preset card that is not selected");
let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes);
let rects: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }).collect();
let veil = |fill: egui::Color32| fill.a() > 0 && fill.a() < scrim.a() && fill.to_opaque() == scrim.to_opaque();
assert!(
rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)),
"a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}",
rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::<Vec<_>>()
);
assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile");
}
/// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and
/// the built-in cards turn to the picked orientation (#2860).
#[test]
+1 -24
View File
@@ -521,22 +521,6 @@ fn flyout_tab(layout: &Layout<String>, panel: &str) -> Option<String> {
.map(|front| front.to_string())
}
/// The actions that expand each floating window the pass made from part of a column collapsed to
/// icons, so a group or tab dragged out of an icon column floats as an expanded panel with its tabs
/// in the window. A whole icon column floated stays collapsed.
fn floated_from_icons(before: &Layout<String>, after: &Layout<String>) -> Vec<Action<String>> {
after
.floating
.iter()
.filter(|window| window.column.iconic && !before.floating.iter().any(|old| old.id == window.id))
.filter_map(|window| {
let first = window.panels().next()?;
let (_, column) = column_of(before, first)?;
(column.iconic && column.panels().count() > window.panels().count()).then(|| Action::set_iconic(first.clone(), false))
})
.collect()
}
/// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]):
/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout
/// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose
@@ -1393,20 +1377,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
app.dock_rt.rails = rails;
// A workspace a command switched to or changed in this pass (`Workspace::replace`) stays; the
// pass's edits were to the one it replaced.
let mut expand = Vec::new();
if app.ui.dock_workspace.revision() == revision {
let before = std::mem::replace(&mut app.ui.dock_workspace, workspace);
expand = floated_from_icons(before.layout(), layout_of(&app.ui));
app.ui.dock_workspace = workspace;
}
// A command of this pass that opened or closed a flyout wins over the area's own change.
if app.ui.open_panel == flyout_before {
app.ui.open_panel = flyout;
}
if !expand.is_empty()
&& let Err(error) = apply(app, None, expand)
{
app.status(error);
}
if output.error.is_some() {
Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[]));
app.status(tl!("Invalid panel layout; restored the default dock").to_string());
+3 -8
View File
@@ -35,14 +35,9 @@ pub struct DocInfoView {
/// the second or third click of a double or triple click.
pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool {
let mut clicked = false;
// A row whose label and value fit on one line keeps the value at its end. A wrapping row places its children as
// `Start` does, so the row wraps only when the two do not fit, as in a narrow panel or a longer translation.
let width = |text: &str| {
let font = egui::TextStyle::Body.resolve(ui.style());
ui.painter().layout_no_wrap(text.to_string(), font, egui::Color32::WHITE).size().x
};
let fits = width(label) + width(value) + 2.0 * ui.spacing().item_spacing.x <= ui.available_width();
Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(!fits).show(ui, |ui, _| {
// A row whose label and value fit on one line keeps the value at its end; otherwise the value wraps under the
// label, as in a narrow panel or a longer translation.
Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| {
Text::new(label.to_string()).shade(Shade::Muted).show(ui);
// The value can be selected and copied, and a click copies all of it (#8432). A drag selects
// and a Shift-click extends the selection, so neither copies. A value wider than the panel
@@ -10,7 +10,7 @@ use craft::color_ui::ui::{ColorPopover, PickedColor};
use craft::theme::Srgba;
use craft::ui::buttons::ToggleButton;
use craft::ui::choice::{Checkbox, Segmented};
use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use craft::ui::layout_components::Row;
use craft::ui::pickers::Select;
@@ -271,14 +271,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _
Row::new().show(ui, |ui, _| {
let mut hit = None;
for (key, on, other, label) in [("fills", fills, strokes, tl!("Fills")), ("strokes", strokes, fills, tl!("Strokes"))] {
// Inside the Create field a check box's own label is not drawn, so each box takes a field of
// its own with the label after it.
let enabled = !on || other;
let mut value = on;
Field::new(label).layout(FieldLayout::After).enabled(enabled).show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut value)).enabled(enabled).show(ui);
});
if value != on {
if check(ui, label, on, !on || other) {
hit = Some(key);
}
}
+3 -2
View File
@@ -377,7 +377,7 @@ pub(crate) fn link_field(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static
}
/// The Stroke panel: the weight, the stroke editor (cap, corner, align, dashes), arrowheads, scale, align and the
/// width profile. The panel's own rows share one label column, so their controls start at one x.
/// width profile. The panel's rows and the editor's rows share one label column, so their controls start at one x.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
use craft::ui::runtime::env::{WordRows, WordsOverride, with_env};
@@ -411,7 +411,8 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) {
let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone()))
.sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN)
.closed(mixed.can_align)
.mixed(&mixed_of(&mixed));
.mixed(&mixed_of(&mixed))
.host_labels(true);
let output = editor.show(ui);
if let (Some(new), Some(field)) = (output.events.landed(), output.field) {
apply_style(app, &style, new.clone(), field);
@@ -51,6 +51,22 @@ fn a_long_document_info_value_wraps_inside_a_narrow_panel() {
}
}
#[test]
fn a_document_info_value_that_does_not_fit_beside_its_label_moves_under_it() {
let name = "A document name long enough to run past a narrow panel";
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
run(&mut app, "file.new", json!({"width": 200, "height": 200, "name": name}));
let mut panel = Panel::new(app, doc_info::show);
panel.room(egui::vec2(160.0, ROOM.y));
panel.frame();
panel.frame();
let label = one(&panel, "Name");
let value = run_starting(&panel, "A document");
assert!(value.top() >= label.bottom() - 0.5, "the value {value:?} stands beside its label {label:?}, not under it");
// A row that wraps starts each line at the start edge.
assert!((value.left() - label.left()).abs() < 1.0, "the value {value:?} does not start under its label {label:?}");
}
#[test]
fn info_paints_stand_a_section_apart_from_the_numbers() {
let mut app = app_with_rect();
+8 -1
View File
@@ -28,9 +28,16 @@ fn turning_dashes_on_fits_them_to_corners_and_turning_back_on_restores_the_last_
#[test]
fn the_panel_rows_start_their_controls_at_one_x() {
let mut panel = Panel::new(app_with_rect(), stroke::show);
// Dashes show the Dash offset row.
run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2]}));
panel.frame();
panel.frame();
let starts: Vec<(&str, f32)> = ["Weight", "Start arrowhead", "Profile"].into_iter().map(|name| (name, panel.rect(name).min.x)).collect();
let names = ["Weight", "Miter limit", "Dash offset", "Start arrowhead", "Profile"];
let mut starts: Vec<(&str, f32)> = names.into_iter().map(|name| (name, panel.rect(name).min.x)).collect();
// The label text of the editor's button rows has the same names as their button groups.
for name in ["Alignment", "Caps", "Corners"] {
starts.push((name, panel.rect_role(name, craft::ui::contract::Role::RADIO_GROUP).min.x));
}
let first = starts[0].1;
assert!(starts.iter().all(|(_, x)| (x - first).abs() < 0.5), "controls start at {starts:?}");
}
+2 -2
View File
@@ -768,11 +768,11 @@ fn quad_bounds(quad: &[Point; 4]) -> vectorcraft_geom::Rect {
/// The Fill/Stroke proxy, Color/Gradient/None, the drawing modes and screen mode under the rail's
/// tools: in two columns the three drawing modes show, in one only the current one, which cycles
/// them. A row the rail is too narrow for goes on in the next line. The All Tools drawer's Show
/// section hides any of them. A rule above them parts them from the tools, which scroll above it in a short rail.
/// section hides any of them. The rail's footer region draws the rule that parts them from the tools, which scroll
/// above it in a short rail.
fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) {
let two = footer.columns > 1;
let show = app.ui.toolbar_show;
Divider::horizontal().show(ui);
if show.fill_stroke {
crate::panels::proxy(app, ui);
}
+12 -9
View File
@@ -306,9 +306,9 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() {
assert_eq!(app.session.draw_mode, vectorcraft_engine::DrawMode::Behind);
}
/// In one column the Color, Gradient and None chips share one line, and a rule across the rail parts the controls under
/// the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and
/// Stroke.
/// In one column the Color, Gradient and None chips share one line, and one rule across the rail parts the controls
/// under the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and
/// Stroke, and no second rule doubles it.
#[test]
fn the_controls_under_the_tools_share_a_line_under_a_rule() {
let mut app = app_with(200, 200);
@@ -325,12 +325,15 @@ fn the_controls_under_the_tools_share_a_line_under_a_rule() {
// A rule is a thin horizontal line or bar across most of the rail's width, between the tools and the controls.
let between = |y: f32| y > last.bottom() && y < proxy.top();
let across = |left: f32, right: f32| right - left >= last.width() * 0.75 && left < last.right() && right > last.left();
let ruled = flat.iter().any(|shape| match shape {
egui::Shape::LineSegment { points: [a, b], .. } => (a.y - b.y).abs() < 0.5 && between(a.y) && across(a.x.min(b.x), a.x.max(b.x)),
egui::Shape::Rect(r) => r.rect.height() <= 2.0 && between(r.rect.center().y) && across(r.rect.left(), r.rect.right()),
_ => false,
});
assert!(ruled, "a rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}");
let rules = flat
.iter()
.filter(|shape| match shape {
egui::Shape::LineSegment { points: [a, b], .. } => (a.y - b.y).abs() < 0.5 && between(a.y) && across(a.x.min(b.x), a.x.max(b.x)),
egui::Shape::Rect(r) => r.rect.height() <= 2.0 && between(r.rect.center().y) && across(r.rect.left(), r.rect.right()),
_ => false,
})
.count();
assert_eq!(rules, 1, "one rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}");
}
/// A screen reader reads the drawing-mode buttons' state as the rail shows it, in every mode: in two columns the
+2 -1
View File
@@ -539,7 +539,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF
export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their
own pixels until a document takes them in; estimate unchanged.
- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation. Estimate unchanged.
- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation; Language packs for languages other than English, read from the Craft apps' shared font store, with `proof.packs`, `proof.installPack` and `proof.removePack` (a Preferences page to install them and the missing-pack bar remain). Estimate unchanged.
- **Missing:** CJK vertical
composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern
features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935),
@@ -1036,6 +1036,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | minor | G4 type: Language packs (#4936): spelling and hyphenation read the packs installed in the Craft apps' shared font store, and `proof.packs`, `proof.installPack` and `proof.removePack` list, install and remove them (installs need downloading on, which only the person turns on); a Preferences page to install them and the missing-pack bar remain; scores and estimates unchanged. |
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
| 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
| 2026-11-21 | minor | G13: View › Snapping groups five existing toggles and Pixel Snapping Options…; top-level commands and shortcuts remain; headless click/checkmark coverage added; scores and estimates unchanged. |
+48 -6
View File
@@ -3116,8 +3116,9 @@ through `$`:
stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through
`object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the
points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
`path.setAnchors` before the script uses any other member or command, or the points of another path, and when the
script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points
`path.setAnchors` before the script uses any other member or command, edits the points of another path, or reads
the points of another path in the same Objects on Path group, and when the script ends;
a path aligned to the pixel grid, or in an object that is, is written at each change, so its points
read as the grid snaps them.
`pathPoints`
(https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and
@@ -3142,7 +3143,10 @@ through `$`:
a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other
than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`,
`object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an
object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point,
object that holds it, such as `translate()`. An exception applies when editing another path in an Objects on
Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`.
Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of
another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point,
and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole.
Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT`
to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a
@@ -3561,7 +3565,7 @@ returns `{stopped}`. `notifications/cancelled` stops a run only while the `tools
for it, as in a headless server; use `script.stop` for a run the app started. A script cannot run commands that
change anything outside the documents: `script.*` except `script.check`, `plugin.*`, `prefs.*`, `actionSet.*`,
`shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`,
`stroke.widthProfile.*`, saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`,
`stroke.widthProfile.*`, `proof.*` (Language packs), saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`,
`text.rescanFonts`, `links.findFiles`, `file.place.queue`, `color.loadProfile`, `color.removeProfile`, `file.print`,
`view.proofSetup`, `view.proofSetup.save`, `view.proofSetup.load`, `view.proofColors`, `view.overprintPreview` and
`view.separationsPreview`. It also cannot run
@@ -13536,7 +13540,7 @@ returns the new value.
`text.spelling.check {ids?}` lists the words of the document's type that its dictionaries don't know: every
visible, unlocked type object in paint order, or those in `ids` (and in the groups `ids` names). Each run is checked
in its Character panel Language (English when it has none) by craft-proof, one paragraph at a time; a language without
a spelling dictionary marks nothing. English words come from the first dictionary craft-proof finds: a Hunspell
a spelling dictionary marks nothing (see [Language packs](#language-packs)). English words come from the first dictionary craft-proof finds: a Hunspell
dictionary in the user's dictionaries folder, the SCOWL dictionary for that English built in from craft-i18n, a
system Hunspell dictionary, and last the public-domain Moby word list built into craft-proof. Words in capitals, words with digits and web addresses are taken as correct. The result is
`{words: [{id, start, end, word, lang}], more}`: `start` and `end` are byte offsets in the type object's text, the
@@ -13587,6 +13591,40 @@ for it (each a `text.editRange {id, start, end, insert}` item labelled with its
All (`text.spelling.ignoreAll {word}`) and Add to Dictionary (`text.spelling.addWord {word}`); the context menu's
entries list them with their params. A right-click on type also has Spelling › Auto Spell Check (`edit.autoSpellCheck`).
### Language packs
Languages other than English are spell-checked, and hyphenated, from **Language packs**: one per language, with its
Hunspell dictionary, hyphenation patterns and licence texts, published by storytold/craft-i18n (release
`language-packs-2`, whose `index.json` VectorCraft pins by its sha256). They are installed into the font store folder
the Craft apps share, so a pack installed in another Craft app is used here too. A language's dictionary is looked up
in an installed pack, then in the system's Hunspell dictionaries. The desktop app and `vectorcraft-cli` read the
installed packs; the web app has none, and no `proof.*` commands.
- `proof.packs {refresh?}` lists the packs of the index fetched last (`packs`, each with `locale`, `name`, `size` in
bytes, `licence`, `class`, `spelling`, `hyphenation` and `installed`), the packs in use (`installed`), the installs
running (`installing`, with bytes `done` of `total`), whether the index is being fetched (`refreshing`), the last
failure of each locale (`errors`; `""` is the index fetch), whether downloading is on (`downloads`), a test index
used instead of the pinned one (`indexOverride`, from `CRAFT_LANGUAGE_PACK_INDEX`) and whether there is a store to
install into (`available`). `refresh: true` fetches the index again.
- `proof.installPack {locale}` downloads a pack, checks its sha256 and installs it (fetching the index first when it
doesn't list the locale). Every open document is laid out and checked again with it. `locale` is the pack's tag,
like `nl` or `pt-br` (`pt_BR` reads as `pt-br`).
- `proof.removePack {locale}` removes an installed pack, not while it installs.
Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click
(the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error
that says so. A caller with automation roots (`--automation-read-root`, `--automation-write-root`) can list packs
but not fetch, install or remove them, since the store is outside its roots. A script cannot run the `proof.*`
commands at all, since a run's rollback cannot put the store back. In the desktop app installs and fetches
run in the background: `proof.installPack` returns
`{locale, started: true}` and `proof.packs` shows the install in `installing`, then in `installed` or `errors`. In
`vectorcraft-cli` they return once done.
```json
{"name":"run_command","arguments":{"command":"proof.packs","params":{"refresh":true}}}
{"name":"run_command","arguments":{"command":"proof.installPack","params":{"locale":"nl"}}}
```
## Find and Replace
`edit.findNext {find, matchCase?, wholeWord?, backwards?, hiddenLayers?, lockedLayers?, from?}` finds the next match
@@ -17534,11 +17572,12 @@ images and patterns keep their colours. → `{changed, swatches: [the document s
Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are
`addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the
top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured
as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid, which uses visual bounds.
as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds.
| Command | Parameters (default) | Does |
|---|---|---|
| `addon.arrange.grid` | `layout`: `grid`, `row`, `column` (`grid`); `columns`: 1…10000 (⌈√count⌉, never more than the count); `gapX` pt (10), `gapY` pt (`gapX`), each −1000000…1000000; `centerOnArtboard` (false) | Lays the objects out in their stacking order from the back, left to right and top to bottom. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, and each object is centred in its cell. The grid starts at the selection's top-left, or is centred on the artboard under the selection's centre (the first artboard when none is there). → `{count}` |
| `addon.arrange.offset` | `direction`: `row` (left to right), `column` (top to bottom) (`row`); `gap` pt, −1000000…1000000 (10; negative overlaps the objects); `order`: `stacking` (stacking order from the back), `position` (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (`stacking`); `reverse` (false) | Chains the objects one after another in that order: the first stays where it is, and each later one moves only along the direction so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Measured by visual bounds, a clipping group by its mask. Needs two objects or more. → `{count}` |
| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. |
| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` |
| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). |
@@ -17551,9 +17590,12 @@ active view so the selection's visual bounds fill the window with a margin, as `
and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs
(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose
fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies.
Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order
and Reverse Order.
```json
{"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}}
{"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}}
{"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}}
{"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}}
```
+5 -1
View File
@@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
@@ -3158,6 +3158,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
## Arrange Tools add-on: Offset Objects (2026-11-29)
A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on.
## Type Tools add-on: Text Tweaker (2026-11-03)
A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on.
+1
View File
@@ -567,6 +567,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored |
| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored |
| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `<name>_YYYY-MM-DD_HH-MM.<ext>` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored |
| Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar |
| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app |
+11 -6
View File
@@ -316,13 +316,18 @@ fn test_packages(select: &[String], shown: &str, part: Option<shards::Part>) ->
/// The doctests, which nextest doesn't run.
fn cmd_doctests() -> Result<(), String> {
doctest_packages(&["--workspace".to_owned()], "--workspace")
doctest_packages(&shards::members(&metadata()?)?)
}
/// [`cmd_doctests`] for the packages `select` picks, shown as `shown`.
fn doctest_packages(select: &[String], shown: &str) -> Result<(), String> {
/// [`cmd_doctests`] for the crates of `crates` that have doc tests.
fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> {
let crates = shards::with_doctests(crates);
if crates.is_empty() {
return Ok(());
}
let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
let mut c = cargo();
c.arg("test").args(select).arg("--doc");
c.arg("test").args(shards::select(&crates)).arg("--doc");
run(c, &format!("cargo test {shown} --doc"))
}
@@ -372,9 +377,9 @@ fn cmd_ci_shard() -> Result<(), String> {
steps.push(("test", Box::new(move || test_packages(&s, &w, part))));
// The doctests and the i18n report run once, on a split's first part.
let first = part.is_none_or(|p| p.is_first());
let (s, w) = (select.clone(), shown.clone());
if first {
steps.push(("doctests", Box::new(move || doctest_packages(&s, &w))));
let c = crates.clone();
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
}
if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") {
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
+50 -2
View File
@@ -88,6 +88,10 @@ pub struct Member {
/// against this repo's geom and pathops by git, so the graph holds a second copy of each.
pub id: String,
pub version: String,
/// Whether `cargo test --doc` can select this package without a warning: it has no library
/// target, or one of `lib`, `rlib` or `proc-macro` kind. Cargo warns for a selected package
/// whose library is only a `cdylib`, `dylib` or `staticlib`.
pub doctests: bool,
}
/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part.
@@ -159,7 +163,7 @@ pub fn members(meta: &Value) -> Result<Vec<Member>, String> {
.filter(|p| p["id"].as_str().is_some_and(|id| ids.contains(id)))
.map(|p| {
let field = |key: &str| p[key].as_str().map(str::to_owned).ok_or_else(|| format!("cargo metadata: a workspace package has no `{key}`"));
Ok(Member { name: field("name")?, id: field("id")?, version: field("version")? })
Ok(Member { name: field("name")?, id: field("id")?, version: field("version")?, doctests: has_doctests(p) })
})
.collect::<Result<_, String>>()?;
if members.is_empty() {
@@ -168,6 +172,24 @@ pub fn members(meta: &Value) -> Result<Vec<Member>, String> {
Ok(members)
}
/// [`Member::doctests`] for the `cargo metadata` package `p`.
fn has_doctests(p: &Value) -> bool {
let kinds = |t: &Value| t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>();
let libraries: Vec<Vec<String>> = p["targets"]
.as_array()
.into_iter()
.flatten()
.map(kinds)
.filter(|k| k.iter().any(|k| matches!(k.as_str(), "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro")))
.collect();
libraries.is_empty() || libraries.iter().flatten().any(|k| matches!(k.as_str(), "lib" | "rlib" | "proc-macro"))
}
/// The crates of `crates` that `cargo test --doc` can select (see [`Member::doctests`]).
pub fn with_doctests(crates: &[Member]) -> Vec<Member> {
crates.iter().filter(|m| m.doctests).cloned().collect()
}
/// Each group of `groups` with its crates: a named crate must be a workspace member and named
/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's
/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice.
@@ -347,7 +369,24 @@ mod tests {
use super::*;
fn m(name: &str) -> Member {
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into() }
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
}
#[test]
fn the_doc_tests_leave_out_only_packages_whose_library_cargo_cannot_doc_test() {
let package = |kinds: &[&str]| serde_json::json!({ "targets": [{ "kind": kinds }, { "kind": ["bin"] }] });
assert!(has_doctests(&package(&["lib"])));
assert!(has_doctests(&package(&["rlib"])));
assert!(has_doctests(&package(&["proc-macro"])));
assert!(has_doctests(&package(&["cdylib", "rlib"])));
assert!(has_doctests(&package(&["bin"])));
assert!(has_doctests(&serde_json::json!({ "targets": [] })));
assert!(!has_doctests(&package(&["cdylib"])));
assert!(!has_doctests(&package(&["dylib"])));
assert!(!has_doctests(&package(&["staticlib"])));
let mut cdylib = m("cdylib");
cdylib.doctests = false;
assert_eq!(with_doctests(&[m("a"), cdylib, m("b")]).iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["a", "b"]);
}
fn crates(shard: &Shard) -> Vec<&str> {
@@ -514,6 +553,15 @@ mod tests {
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
}
#[test]
fn the_workspace_doc_tests_skip_the_cdylib_thumbnail_handler() {
let ws = members(&crate::metadata().unwrap()).unwrap();
let doctests = |name: &str| ws.iter().find(|m| m.name == name).map(|m| m.doctests);
assert_eq!(doctests("vectorcraft-thumbnail-handler"), Some(false));
assert_eq!(doctests("vectorcraft-geom"), Some(true));
assert_eq!(doctests("vectorcraft-cli"), Some(true));
}
#[test]
fn a_feature_only_another_shard_turns_on_is_a_difference() {
let ws = [m("lib"), m("geom")];