Merge main into fix/issue-8583

This commit is contained in:
dotCooCoo committed 2026-11-27 23:37:43 -08:00
commit 326a5f83f2
56 files changed
+2689 -221

No files matched your search

+7 -17
View File
@@ -1,5 +1,4 @@
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
/// Invalid roots must exit before desktop initialization on every platform, including a CI
/// machine with no display. A regression must fail rather than hang with a window open.
@@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) {
rejects_with_env(args, &[], message);
}
/// Runs the desktop binary without a display, so on Linux a regression exits with a display
/// error, which the exact stderr check rejects, instead of opening a window.
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
let mut child = Command::new(crate::bin())
let child = Command::new(crate::bin())
.args(args)
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
.env_remove("WAYLAND_SOCKET")
.env_remove("VECTORCRAFT_CONTROL_PORT")
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
.env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT")
@@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
.stderr(Stdio::piped())
.spawn()
.unwrap();
// Long enough for the binary to start on a loaded machine (the workspace's other tests run
// meanwhile), short enough to catch a desktop that started instead of exiting.
let deadline = Instant::now() + Duration::from_secs(30);
let timed_out = loop {
if child.try_wait().unwrap().is_some() {
break false;
}
if Instant::now() >= deadline {
child.kill().unwrap();
break true;
}
std::thread::sleep(Duration::from_millis(10));
};
let out = child.wait_with_output().unwrap();
assert!(!timed_out, "{args:?}: desktop started or did not exit promptly");
let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting"));
assert!(!out.status.success(), "{args:?}");
assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout);
// Exact stderr excludes unrelated startup warnings or display errors that could otherwise
+2 -26
View File
@@ -1,15 +1,12 @@
//! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a
//! terminal, SSH or an agent's shell it used to open the window (or hang without a display).
use std::io::Read;
use std::process::{Command, Output, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
/// regression exits with that error instead of opening a window.
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
let mut child = Command::new(crate::bin())
let child = Command::new(crate::bin())
.args(args)
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
@@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
.stderr(Stdio::piped())
.spawn()
.unwrap();
// Both pipes end when the binary exits, however long a loaded machine takes to start it. The
// deadline only stops a binary that is still running.
let deadline = Instant::now() + Duration::from_secs(120);
let stdout = read_to_end(child.stdout.take().unwrap());
let stderr = read_to_end(child.stderr.take().unwrap());
let recv = |rx: &mpsc::Receiver<Vec<u8>>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now()));
let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else {
child.kill().unwrap();
panic!("{args:?}: the app started instead of printing its usage");
};
Output { status: child.wait().unwrap(), stdout, stderr }
}
/// Reads `pipe` to its end on another thread.
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
let _ = tx.send(buf);
});
rx
crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage"))
}
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
+72
View File
@@ -2,6 +2,11 @@
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::Read;
use std::process::{Child, Output};
use std::sync::mpsc;
use std::time::{Duration, Instant};
mod automation_args;
mod help;
@@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf {
.map(std::path::PathBuf::from)
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
}
/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. Both
/// pipes end when the binary exits, however long a loaded machine takes to start it. The deadline
/// only stops a binary that is still running: the test then fails with `started`.
fn exit_output(child: Child, started: &str) -> Output {
exit_output_by(child, started, Instant::now() + Duration::from_secs(120))
}
/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even
/// when its output arrives after it; the output then has 10 seconds more to arrive.
fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output {
let stdout = read_to_end(child.stdout.take().unwrap());
let stderr = read_to_end(child.stderr.take().unwrap());
let (mut out, mut err) = (None, None);
if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() {
child.kill().unwrap();
child.wait().unwrap();
panic!("{started}");
}
receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10));
let (Some(stdout), Some(stderr)) = (out, err) else {
panic!("{started}: the binary exited, but its output pipes stayed open");
};
Output { status: child.wait().unwrap(), stdout, stderr }
}
/// A pipe's reader and the slot that holds its output once it arrives.
type Pipe<'a> = (&'a mpsc::Receiver<Vec<u8>>, &'a mut Option<Vec<u8>>);
/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether
/// every slot is filled.
fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool {
let mut filled = true;
for (rx, slot) in pipes {
if slot.is_none() {
*slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok();
}
filled &= slot.is_some();
}
filled
}
/// Reads `pipe` to its end on another thread.
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
let _ = tx.send(buf);
});
rx
}
/// A binary that exits before the deadline passes even when a process it started keeps its
/// output pipes open past the deadline.
#[cfg(unix)]
#[test]
fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() {
use std::process::{Command, Stdio};
let mut child =
Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
// `sh` has exited; the `sleep` it started still holds both pipes for about a second.
child.wait().unwrap();
let out = exit_output_by(child, "an exited binary was reported as running", Instant::now());
assert!(out.status.success());
assert!(out.stdout.is_empty() && out.stderr.is_empty());
}
+13 -2
View File
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths,
envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
};
pub use expand::{
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
@@ -975,6 +975,17 @@ mod tests {
assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round()));
// Margins an `f32` can't hold are none.
assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None);
// A straight line along an axis has margins across it, as shares of its length, and maps
// from its box with them; a point has none.
let line =
Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art());
let line = [Arc::new(line)];
let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0);
let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap();
assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}");
let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on });
assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}");
assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None);
assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none());
let saved = serde_json::to_value(on).unwrap();
+26 -14
View File
@@ -95,7 +95,9 @@ pub struct EnvelopeOptions {
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
pub distort_pattern_fills: bool,
/// With Distort Appearance, how far the box the content maps from reaches past its geometric
/// bounds at the top, bottom, left and right, as shares of their height and width. An envelope
/// bounds at the top, bottom, left and right, as shares of their height and width; when the
/// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side
/// ([`envelope_margin_lengths`]). An envelope
/// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes
/// have none. Leaving Edit Contents measures them again when the strokes reach differently.
#[serde(skip_serializing_if = "crate::skip::is_default")]
@@ -140,7 +142,8 @@ impl EnvelopeOptions {
if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) {
return r;
}
let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]);
let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r };
let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]);
if grown.is_finite() { grown } else { r }
}
}
@@ -457,19 +460,28 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
}
}
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
/// content with no width or no height, or for margins an `f32` can't hold.
/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with
/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the
/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight
/// line along an axis has margins across it. `None` when neither side has a length.
pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> {
let long = |l: f64| l.is_finite() && l >= 1e-6;
let (h, w) = match (long(plain.height()), long(plain.width())) {
(true, true) => (plain.height(), plain.width()),
(false, true) => (plain.width(), plain.width()),
(true, false) => (plain.height(), plain.height()),
(false, false) => return None,
};
Some([h, h, w, w])
}
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares
/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for
/// margins an `f32` can't hold.
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
if plain.width() < 1e-6 || plain.height() < 1e-6 {
return None;
}
let margin = [
(plain.y0 - stroked.y0) / plain.height(),
(stroked.y1 - plain.y1) / plain.height(),
(plain.x0 - stroked.x0) / plain.width(),
(stroked.x1 - plain.x1) / plain.width(),
]
.map(|m| m as f32);
let [v, _, h, _] = envelope_margin_lengths(plain)?;
let margin =
[(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32);
margin.iter().all(|m| m.is_finite()).then_some(margin)
}
+2
View File
@@ -964,6 +964,8 @@ pub use variablecmds::utf16_order_without_mark;
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
/// The kind of variable that drives an object's content (`variable.setBinding`).
pub(crate) use variablecmds::content_kind;
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
+49 -1
View File
@@ -1601,7 +1601,8 @@ impl Clipboard {
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
/// filter of its name; one that draws another definition than that filter takes the document's
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an
/// effect of the document that draws the same definition under a name no filter has gives that name. When that name would
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
@@ -1627,6 +1628,8 @@ impl Clipboard {
}
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
let mut effects_read = false;
// The filter effects of the document, by name and definition.
let mut held_effects = BTreeSet::new();
let mut links = BTreeMap::new();
for (name, xml) in found {
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
@@ -1640,14 +1643,28 @@ impl Clipboard {
effects_read = true;
for root in d.art_roots() {
node_filter_names(root, &mut taken);
node_filters(root, &mut held_effects);
}
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
node_filter_names(a, &mut taken);
node_filters(a, &mut held_effects);
}
for g in &d.graphic_styles {
appearance_filter_names(&g.appearance, &mut taken);
appearance_filters(&g.appearance, &mut held_effects);
}
}
// An effect of the document that already draws this filter under a name no filter
// of the document has (one pasted or loaded before) gives its name, so pasting or
// loading the same filter again adds no other name.
let earlier = held_effects.iter().find(|(n, x)| {
!d.svg_filters.iter().any(|f| &f.name == n)
&& vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x)
});
if let Some((n, x)) = earlier {
links.insert((name, xml), (n.clone(), x.clone()));
continue;
}
// Free names made from the starts of the name, longest first, then free letters and
// digits, then other single printable ASCII characters: the first under which the
// filter still draws.
@@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
@@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
Ok(placed)
}
/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the
/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as
/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to
/// them (a resource `d` has under the same name and with the same contents is used; another is
/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s;
/// an SVG filter whose name `d` gives another filter is renamed).
pub(crate) fn import_looks(
src: &Document,
d: &mut Document,
look: &Appearance,
attrs: &Map<String, Value>,
) -> Result<(Appearance, Map<String, Value>)> {
let library = OnceCell::new();
let defs = Defs::of(src, &library);
let mut used = Used::default();
used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]);
// The look goes on an empty path, so that its SVG filters are renamed where `d` gives their
// names other filters, as a pasted object's are.
let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone());
let clip = Clipboard::with_used(src, &used, &library, vec![carrier]);
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
let (mut look, mut attrs) = (look.clone(), attrs.clone());
out.relink.appearance(&mut look);
out.relink.attrs(&mut attrs);
Ok((look, attrs))
}
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
let mut used = Used::default();
+9 -5
View File
@@ -593,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, c
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
/// effect colors and the series paints and label styles that graphs keep included), symbols,
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color),
/// character and paragraph styles (their fill and stroke) and swatches through the color settings
/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and
/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of
/// graphic styles, brushes and text styles convert without being counted. Gray
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
/// ([`mode_converter`]). Lab colors
@@ -608,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
if !convert {
return 0;
}
convert_colors(d, &mode_converter(mode, intent, grays))
let conv = mode_converter(mode, intent, grays);
let changed = convert_colors(d, &conv);
convert_style_colors(d, &conv);
changed
}
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
+37 -18
View File
@@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<Cu
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
if fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
@@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()
if before == after {
return Ok(());
}
let changed = register(s, &before, &after);
let r = s.edit(label, |d, _| set_fonts(d, &after, &changed));
sync(s);
r
}
/// Before an edit makes `after` the active document's composite fonts (it has `before`), register
/// them in the font database and forget the ones taken out → the lowercased names of the fonts that
/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not.
pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec<String> {
let changed: Vec<String> =
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
// listed here that the document doesn't define.
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
let db = FontDb::global();
for f in &before {
for f in before {
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
db.remove_composite_font(&f.name);
}
}
for f in &after {
for f in after {
db.set_composite_font(f);
}
let r = s.edit(label, |d, _| {
*d.composite_fonts = after.clone();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
});
sync(s);
r
changed
}
/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again.
pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> {
*d.composite_fonts = after.to_vec();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
}
/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts
/// adds a font.
pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec<CompositeFont> {
let mut after = fonts.to_vec();
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
after
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
@@ -377,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
if apply {
let mut after = s.doc()?.doc.composite_fonts.to_vec();
for f in &fonts {
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
after = with_font(&after, f);
}
check_set(&after, C)?;
replace(s, "Import Composite Fonts", after)?;
+52
View File
@@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its
/// graph with the document's design of that name, as a pasted one does.
#[test]
fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute("graph.column", &json!({"design": "Coin"})).unwrap();
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone();
src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap();
let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap();
let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone();
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap();
src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap();
let source = (*src.doc().unwrap().doc).clone();
let look = source.node(NodeId(r)).unwrap().appearance.clone();
assert!(source.pattern("Charts").is_some());
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns = |d: &vectorcraft_doc::Document| -> Vec<usize> {
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect()
};
for styles in [false, true] {
// A document whose "Coin" is a rectangle and an ellipse.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if styles {
crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap();
} else {
crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap();
}
assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design");
}
}
#[test]
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
let mut s = Session::new();
+1 -1
View File
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Envelope Info",
[],
None,
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, a side shorter than 1e-6 pt taking the other side's, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
has_doc,
env_info
),
+108 -4
View File
@@ -15,10 +15,10 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit};
use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit};
use vectorcraft_geom::{Point, Rect};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or};
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Profile",
[],
None,
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
always,
edit_profile
),
@@ -72,10 +72,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profile",
[],
None,
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
always,
reset_profile
),
cmd!(
"file.newProfiles.applyDefaults",
"Use Profile Defaults",
[],
None,
"{name: a built-in category of file.newPresets (not Recent or Saved)} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when applying the profile leaves the document unchanged). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}",
has_doc,
apply_defaults
),
]
}
@@ -1113,3 +1122,98 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
};
Ok(json!({ "name": name, "reset": reset }))
}
/// `file.newProfiles.applyDefaults`: the active document takes the Default Graphic Style and
/// [Normal Character Style] of profile `name`, and new art is reset to them.
fn apply_defaults(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.newProfiles.applyDefaults";
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
let mode = s.doc()?.doc.color_mode;
let (mut src, warnings) = match s.read_profile(name) {
Ok(Some(p)) => (p.doc, p.warnings),
// The shipped profile: the defaults of a new document in this color mode.
Ok(None) => (Document::new_with_mode(1.0, 1.0, mode), vec![]),
Err(e) => return Err(bad(C, format!("the {name} profile can't be read: {e}"))),
};
if src.color_mode != mode {
super::colormgmt::set_color_mode(&mut src, mode, true, None, super::colormgmt::Grays::Profile);
}
// A profile without a Default Graphic Style gives the shipped one, as a new document from it
// starts with the shipped fill and stroke.
let look = match src.graphic_style(DEFAULT_GRAPHIC_STYLE) {
Some(g) => g.clone(),
None => Document::new_with_mode(1.0, 1.0, mode).graphic_style(DEFAULT_GRAPHIC_STYLE).cloned().unwrap_or_else(shipped_default_style),
};
let normal = super::textstyles::style_attrs(&src, false, super::textstyles::NORMAL_CHAR).unwrap_or_default();
let chars = s.prefs.override_char_color;
// A composite font the style names comes with it, in place of the document's of its name, as
// Import Composite Fonts brings it.
let family = normal.get("font_family").and_then(Value::as_str);
let fonts_before = s.doc()?.doc.composite_fonts.to_vec();
let fonts = family
.and_then(|f| CompositeFont::named(&src.composite_fonts, f))
.map(|f| super::compositefonts::with_font(&fonts_before, f))
.filter(|after| *after != fonts_before);
if let Some(after) = &fonts {
super::compositefonts::check_set(after, C)?;
}
let fonts_changed = match &fonts {
Some(after) => super::compositefonts::register(s, &fonts_before, after),
None => vec![],
};
let apply = |d: &mut Document| -> Result<()> {
if let Some(after) = &fonts {
super::compositefonts::set_fonts(d, after, &fonts_changed)?;
}
let before = d.clone();
let (appearance, attrs) = super::clipboard::resources::import_looks(&src, d, &look.appearance, &normal)?;
let attrs = if attrs.is_empty() {
attrs
} else {
super::textstyles::stored_style_attrs(d, false, &attrs)
.ok_or_else(|| bad(C, format!("the {name} profile's [Normal Character Style] has attributes charStyle.new does not take")))?
};
let new = GraphicStyle { appearance, ..look.clone() };
match d.graphic_style_index(DEFAULT_GRAPHIC_STYLE) {
Some(i) if d.graphic_styles[i].same_look(&new) => {}
Some(i) => super::style::redefine_in(d, &before, i, new, None, chars),
None => {
let id = d.next_graphic_style_id();
d.graphic_styles.insert(0, GraphicStyle { name: DEFAULT_GRAPHIC_STYLE.to_string(), id, ..new });
}
}
super::textstyles::redefine_normal_char(d, &attrs)
};
// An undo step only when the document changes; Undo puts the new-art paints back too.
let paint_before = super::colormgmt::new_art_colors_before(s)?;
let mut run = || -> Result<bool> {
let mut trial = (*s.doc()?.doc).clone();
apply(&mut trial)?;
let changed = trial != *s.doc()?.doc;
if changed {
s.edit("Use Profile Defaults", |d, _| apply(d))?;
}
Ok(changed)
};
let changed = run();
if fonts.is_some() {
super::compositefonts::sync(s);
}
let changed = changed?;
super::newart::reset(s);
// The selection's appearance does not replace the defaults just set.
s.note_defaults_only();
if changed || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
super::colormgmt::record_new_art_colors(s, paint_before)?;
}
let mut out = json!({ "name": name, "changed": changed });
if !warnings.is_empty() {
out["warnings"] = json!(warnings);
}
Ok(out)
}
/// The shipped Default Graphic Style: white fill, 1 pt black stroke.
fn shipped_default_style() -> GraphicStyle {
GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, vectorcraft_doc::Appearance::default_art())
}
+1 -1
View File
@@ -1253,7 +1253,7 @@ impl Session {
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
/// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting
/// with both the fill and the stroke).
fn note_defaults_only(&mut self) {
pub(crate) fn note_defaults_only(&mut self) {
let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true));
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
}
@@ -736,6 +736,7 @@ pub(super) const ALLOWED: &[&str] = &[
"variable.makeTextDynamic",
"variable.makeVisibilityDynamic",
"variable.rename",
"variable.setBinding",
"variable.sort",
"variable.unbind",
];
+39 -29
View File
@@ -545,40 +545,50 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
let chars = s.prefs.override_char_color;
let before = s.doc()?.doc.clone();
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
let id = d.graphic_style_id(i);
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look });
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
// source or as a linked object: the graph draws it again from the design.
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
set_link(d, &edited, None);
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
// its look and its link.
let mut follow_marks = super::graph::series_group_marks(d, &follow);
let edited: HashSet<NodeId> = edited.into_iter().collect();
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
let g = d.graphic_styles[i].clone();
let mut shared = None;
for nid in &follow_marks {
apply_style(d, *nid, &g, &mut shared, chars);
}
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
super::graph::capture_label_rows(d, &follow_marks);
if let Some(src) = src {
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
}
redefine_in(d, &before, i, look, src, chars);
Ok(())
})?;
Ok(json!({ "name": name }))
}
/// Replace graphic style `i` of `d` with the fills, strokes, effects and transparency of `look`,
/// keeping its name and id, as Redefine Graphic Style does: the objects still linked to it follow
/// the new definition, edited ones are unlinked and keep their look, and object `src` (the one the
/// look comes from, if any) becomes linked. `before` is `d` before the edit; `chars` is Override
/// Character Color.
pub(crate) fn redefine_in(d: &mut Document, before: &Document, i: usize, look: GraphicStyle, src: Option<NodeId>, chars: bool) {
let id = d.graphic_style_id(i);
let name = d.graphic_styles[i].name.clone();
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name, id, ..look });
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
// source or as a linked object: the graph draws it again from the design.
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
set_link(d, &edited, None);
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
// its look and its link.
let mut follow_marks = super::graph::series_group_marks(d, &follow);
let edited: HashSet<NodeId> = edited.into_iter().collect();
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
let g = d.graphic_styles[i].clone();
let mut shared = None;
for nid in &follow_marks {
apply_style(d, *nid, &g, &mut shared, chars);
}
super::appearance::capture_series_writes(before, d, &follow_marks, (true, true), (true, true), false, true);
super::graph::capture_label_rows(d, &follow_marks);
if let Some(src) = src {
let link = (!super::graph::is_design_art(d, src)).then_some(id);
set_link(d, &[src], link);
}
}
fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::whole_targets(s, p, "graphicStyle.breakLink")?;
s.edit("Break Link to Graphic Style", |d, _| {
+42 -19
View File
@@ -336,16 +336,17 @@ fn with_attrs<T: Serialize + DeserializeOwned>(base: &T, attrs: &Map<String, Val
}
/// `cur` after its style changed from `old` to `new`: attributes still equal to the old style's
/// value (or not set by it) take the new value, and removed attributes return to `base`;
/// overrides stay. `attrs` lists every attribute of `cur` ([`char_attrs`], [`para_attrs`]), so
/// one at its default matches a style that sets the default. Unchanged if the style doesn't
/// round-trip through JSON.
/// value (for one the old style does not set, the value of `old_base`, what the text had under
/// it) take the new value, and removed attributes return to `base`; overrides stay. `attrs`
/// lists every attribute of `cur` ([`char_attrs`], [`para_attrs`]), so one at its default
/// matches a style that sets the default. Unchanged if the style doesn't round-trip through JSON.
fn restyle<T: Serialize + DeserializeOwned + Clone>(
cur: &T,
attrs: fn(&T) -> Map<String, Value>,
old: &Map<String, Value>,
new: &Map<String, Value>,
base: &Map<String, Value>,
old_base: &Map<String, Value>,
) -> T {
// Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept.
let Some(mut m) = to_map(cur) else { return cur.clone() };
@@ -353,7 +354,7 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
let pair = |m: &Map<String, Value>| KINSOKU.map(|k| m.get(k).cloned());
let own = pair(&m);
for (k, v) in new {
if old.get(k).is_none_or(|o| m.get(k) == Some(o)) {
if m.get(k) == old.get(k).or_else(|| old_base.get(k)) {
m.insert(k.clone(), v.clone());
}
}
@@ -369,7 +370,7 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
// style's keeps its own.
let has = |m: &Map<String, Value>| KINSOKU.iter().any(|k| m.contains_key(*k));
if has(old) || has(new) {
let follows = !has(old) || pair(old) == own;
let follows = pair(if has(old) { old } else { old_base }) == own;
let to = if !follows {
own
} else if has(new) {
@@ -494,10 +495,16 @@ fn uses_of(uses: &std::collections::HashMap<Option<String>, usize>, kind: Kind,
fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new: &Map<String, Value>) -> Result<()> {
let target = (name != kind.normal()).then_some(name.to_string());
let normal = kind.attrs(d, kind.normal()).unwrap_or_default();
let base = match kind {
Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?),
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?),
// What the text had under the old definition where it sets nothing: Normal's (its old
// definition when Normal is the style redefined) over the defaults.
let old_normal = if target.is_none() { old } else { &normal };
let over_defaults = |attrs: &Map<String, Value>| -> Result<Map<String, Value>> {
Ok(match kind {
Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), attrs, &kind.cmd("edit"))?),
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), attrs, &kind.cmd("edit"))?),
})
};
let (base, old_base) = (over_defaults(&normal)?, over_defaults(old_normal)?);
each_text_mut(d, &mut |t| {
let mut changed = false;
// The first character whose leading the new definition changed.
@@ -505,8 +512,10 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
// Substitute the old definition only for leading generated by Block.
let block = t.dynamic_text && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. });
let block_metrics = super::typecmd::block_fit_metrics(t).map(|(points, gap, _)| (gap / points, super::typecmd::BLOCK_SIZES.0 / points));
// A leading the old definition does not set is the one the text had under it.
let old_leading = old
.get("leading")
.or_else(|| old_base.get("leading"))
.filter(|_| block && old.get("leading") != new.get("leading"))
.and_then(|v| serde_json::from_value::<Option<f64>>(v.clone()).ok());
match kind {
@@ -520,7 +529,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
r.style.leading = l;
}
let was = r.style.leading;
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new);
r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base, &old_base), new);
changed = true;
if r.style.leading != was && leading_at.is_none() {
leading_at = Some(off);
@@ -532,7 +541,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
Kind::Para => {
for pa in t.para_styles_mut() {
if pa.style_name == target {
*pa = restyle(pa, para_attrs, old, new, &base);
*pa = restyle(pa, para_attrs, old, new, &base, &old_base);
changed = true;
}
}
@@ -963,17 +972,31 @@ fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map<String, V
return ok();
}
let name = name.to_string();
s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| {
match kind.defs_mut(d).iter_mut().find(|s| s.name == name) {
Some(def) => def.attrs = new_attrs.clone(),
None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }),
}
update_users(d, kind, &name, &old, &new_attrs)?;
Ok(())
})?;
s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| set_definition(d, kind, &name, &old, &new_attrs))?;
ok()
}
/// Give style `name` of `d` the attributes `new_attrs` (it had `old`), and the text in it that
/// follows the old definition the new one (users keep their overrides).
fn set_definition(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Value>, new_attrs: &Map<String, Value>) -> Result<()> {
match kind.defs_mut(d).iter_mut().find(|s| s.name == name) {
Some(def) => def.attrs = new_attrs.clone(),
None => kind.defs_mut(d).push(TextStyleDef { name: name.to_string(), attrs: new_attrs.clone() }),
}
update_users(d, kind, name, old, new_attrs)
}
/// Redefine `[Normal Character Style]` of `d` with `attrs` (attributes as `charStyle.new` stores
/// them), as Redefine Character Style does: the type in it takes the new attributes and keeps its
/// overrides. Nothing changes when `attrs` is the current definition.
pub(crate) fn redefine_normal_char(d: &mut Document, attrs: &Map<String, Value>) -> Result<()> {
let old = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default();
if *attrs == old {
return Ok(());
}
set_definition(d, Kind::Char, NORMAL_CHAR, &old, attrs)
}
fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
let name = name_param(p, kind, "redefine")?.to_string();
let attrs = selection_attrs(s, p, kind, "redefine")?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?;
+17
View File
@@ -525,6 +525,23 @@ fn editing_character_style_clears_removed_size_without_losing_local_override() {
assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0));
}
/// A size a style starts to set reaches the text that had the size the style left it (Normal's,
/// or the default when Normal itself is redefined), and not text with a size of its own.
#[test]
fn a_size_a_character_style_starts_to_set_keeps_local_overrides() {
for name in ["Body", NORMAL_CHAR] {
let (mut s, id) = session_with_text("One two");
if name != NORMAL_CHAR {
s.execute("charStyle.new", &json!({"name": name, "attrs": {}})).unwrap();
s.execute("charStyle.apply", &json!({"name": name, "id": id})).unwrap();
}
s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 36.0})).unwrap();
s.execute("charStyle.setAttrs", &json!({"name": name, "attrs": {"size": 24.0}})).unwrap();
let r = runs(&s, id);
assert_eq!((r[0].style.size, r[1].style.size), (24.0, 36.0), "{name}");
}
}
#[test]
fn replacing_character_style_attrs_clears_removed_size() {
let (mut s, id) = session_with_text("Text");
+85 -4
View File
@@ -455,6 +455,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"unbound": n}))
}
/// The kind of variable that drives the content of `n`: text for type, image for an image object
/// and graph for a graph root. `None` for other objects, which have only a visibility slot.
pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option<VariableKind> {
match &n.kind {
NodeKind::Text(_) => Some(VariableKind::Text),
NodeKind::Image(_) => Some(VariableKind::Image),
_ if n.extras().graph.is_some() => Some(VariableKind::Graph),
_ => None,
}
}
/// The variables of `kind` bound to `id`, in the order they are defined.
fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec<String> {
let Some(bound) = vars.bindings.get(&id) else { return Vec::new() };
vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect()
}
/// The slot `variable.setBinding` names: an object's visibility, or its content.
fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> {
let node = doc.node(id).ok_or(EngineError::NoNode(id))?;
match str_param(p, "slot") {
Some("visibility") => Ok(("visibility", VariableKind::Visibility)),
Some("content") => {
content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0)))
}
_ => Err(bad(cmd, "`slot` must be `visibility` or `content`")),
}
}
/// Bind one object's visibility or content to one variable, or to none, in one undo step: the
/// object's other variables of that slot's kind are unbound. The content of type takes a text
/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded
/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing
/// changes when one fails. A call that leaves the bindings as they were adds no undo step.
fn set_binding(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.setBinding";
let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?;
let variable = match p.get("variable") {
None | Some(Value::Null) => None,
Some(v) => Some(named(v.as_str(), "variable", C)?),
};
let doc = &s.doc()?.doc;
let (slot, kind) = slot_kind(doc, id, p, C)?;
if let Some(name) = &variable {
let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?;
if have != kind {
return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label())));
}
check_bindable(doc, &[id], kind, C)?;
if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) {
return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0)));
}
}
let unbound: Vec<String> = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect();
let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" };
edit_variables(s, label, |vars| {
for n in &unbound {
vars.unbind(id, n);
}
if let Some(n) = &variable {
vars.bind(id, n);
}
Ok(())
})?;
Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound}))
}
/// The `variable` a command names, which must be defined; `None` when it names none.
fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result<Option<String>> {
let name = optional_name(p, "variable", cmd)?;
@@ -694,13 +761,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result<Value> {
/// other than a visibility variable, locked or inside a locked layer or group, or, for any
/// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the
/// objects report a value for is added to the row. Without an active row there is nothing to
/// update, so say so rather than picking one. With every bound object locked, no value is
/// written; an update that writes no value adds no undo step.
/// update, so say so rather than picking one. `name` updates that row instead, and leaves the
/// active row as it is. With every bound object locked, no value is written; an update that
/// writes no value adds no undo step.
fn dataset_update(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "dataset.update";
let all = bool_or(p, "all", false);
let given = match p.get("name") {
None => None,
Some(v) => Some(named(v.as_str(), "name", C)?),
};
let st = s.doc()?;
let Some(name) = st.doc.variables.active_dataset.clone() else {
let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else {
return Err(bad(C, "no active data set"));
};
if !anything_bound(&st.doc) {
@@ -985,6 +1057,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
unbind
),
cmd!(
"variable.setBinding",
"Bind Variable",
[],
None,
"{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}",
has_doc,
set_binding
),
cmd!(
"variable.lock",
"Lock Variables",
@@ -1037,7 +1118,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Data Set",
["Window", "Variables"],
None,
"{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}",
"{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}",
has_doc,
dataset_update
),
+2 -1
View File
@@ -362,7 +362,8 @@ impl ScriptGate {
ScriptGate { also: Some(also), ..self.clone() }
}
fn check(&self, path: &str, access: Access) -> Result<(), String> {
/// May `path` be read (or written) through this gate?
pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> {
if let Some(also) = &self.also {
also.check(path, access)?;
}
+47 -14
View File
@@ -68,6 +68,20 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current
use crate::{DocState, Document, NodeId, NodeKind, Session};
mod tags;
mod variables;
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
/// What [`after_command`] compares with, taken before each command a script runs
/// ([`variables::before_command`]).
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
variables::before_command(h, id)
}
/// After each command a script runs ([`variables::after_command`]).
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataSet>)>) {
variables::after_command(h, before);
}
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
@@ -118,7 +132,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
/// open, and the settings of each `DocumentPreset` the run made.
/// open, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset`
/// objects it gave out.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
@@ -126,6 +141,7 @@ pub(super) struct State {
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
presets: RefCell<Vec<Vec<(String, Data)>>>,
vars: variables::Handles,
}
impl State {
@@ -368,12 +384,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result<Doc, HostError
}
}
fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
let [high, low] = id_parts(id);
[float(h.run), float(st.uid), high, low, float(st.reverts)]
}
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
let &[run, uid, high, low, reverts] = handle else { return None };
let doc = find_doc(h, run, uid)?;
if h.session.borrow().documents().get(doc.index)?.reverts != whole(reverts)? {
return None;
}
Some((doc, id_of(high, low)?))
}
/// The page item `d` names, which must still be in its document.
fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if handle.len() != 5 {
return Err(HostError::Type("this is not a page item".into()));
}
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let s = h.session.borrow();
let st = &s.documents()[doc.index];
if st.doc.node(id).is_none_or(|n| typename(n).is_none()) {
@@ -410,8 +441,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
match st.doc.node(id) {
Some(n) => match typename(n) {
Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
Some(t) => host_ref(t, &node_handle(h, st, id)),
None => host_ref("Layer", &node_handle(h, st, id)),
},
None => Data::Null,
}
@@ -1958,17 +1989,16 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
let Some(&[run, uid, high, low]) = handle.as_deref() else {
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
if handle_of(target, "Document").is_some() {
return Err(HostError::Error("a document as the relative object is not available yet".into()));
}
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
};
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if doc.uid != item.doc.uid {
return Err(HostError::Error(CROSS_DOCUMENT.into()));
}
let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
with_doc(h, doc, |_, st| {
let d = &st.doc;
let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
@@ -2134,9 +2164,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
fn layer_name(h: &Host, a: &[Data]) -> Answer {
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX));
let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
}
@@ -2216,6 +2246,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
variables::define_enums(realm)?;
let l = link;
let mut application = named(vec![
("typename", typename_of("Application")),
@@ -2277,6 +2308,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
.into_iter()
.map(|m| later(l, "Document", m)),
);
document.extend(variables::document_members(l));
document.push(("tags".into(), get(l, tags::doc_tags)));
classes.push(class("Document", None, document, None));
classes.push(class(
@@ -2329,7 +2361,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
"sliced",
"uRL",
"uuid",
"visibilityVariable",
"wrapInside",
"wrapOffset",
"wrapped",
@@ -2342,8 +2373,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
.into_iter()
.map(|m| later(l, "PageItem", m)),
);
page_item.extend(variables::page_item_members(l));
classes.push(class("PageItem", None, page_item, None));
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None)));
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
classes.extend(variables::classes(l));
classes.push(class(
"Layer",
None,
+814
View File
@@ -0,0 +1,814 @@
//! Variables and data sets in the script object model: `Document.variables`, `dataSets`,
//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`,
//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Variables/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Variable/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/> describe them. Every change runs
//! one of the `variable.*` and `dataset.*` commands.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change
//! made through the object keeps the object working; once the name leaves the document any other
//! way (a delete, a rename by another command, an undo, a kind change by another command, or an
//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or
//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most
//! [`MAX_HANDLES`] of each.
//! - Collections list variables and data sets in the order the document holds them, counted from
//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`.
//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first
//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data
//! set named `Data Set 1` and so on, which becomes the active one.
//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`,
//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file
//! declared without one VectorCraft knows, and cannot be given.
//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order.
//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows
//! its values in the art, as `display()` does.
//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the
//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the
//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all.
//! An embedded image (`RasterItem`) cannot take an image variable.
//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the
//! script may read, or write, as its `File` objects may: the files of the open documents do not
//! count.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use serde_json::json;
use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref};
use super::{
Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get,
handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc,
};
use crate::doc::{DataSet, Node, Variable, VariableKind};
use crate::file_access::Access;
/// The error for a `Variable` whose variable left the document, or that came from an earlier run.
pub const STALE_VARIABLE: &str = "Stale variable";
/// The error for a `Dataset` whose data set left the document, or that came from an earlier run.
pub const STALE_DATASET: &str = "Stale data set";
/// The most `Variable` objects, and the most `Dataset` objects, one run gives out.
pub const MAX_HANDLES: usize = 10_000;
/// The kinds, each with the name of its `VariableKind` member.
const KINDS: [(VariableKind, &str); 5] = [
(VariableKind::Text, "TEXTUAL"),
(VariableKind::Visibility, "VISIBILITY"),
(VariableKind::Image, "IMAGE"),
(VariableKind::Graph, "GRAPH"),
(VariableKind::Unknown, "Unknown"),
];
/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a
/// variable (`None` for a data set) and whether it still names it.
struct Entry {
uid: u64,
name: String,
kind: Option<VariableKind>,
alive: bool,
}
/// The objects of one class a run gave out: each one's handle is its index here.
#[derive(Default)]
struct Table {
entries: Vec<Entry>,
/// The entry that names each document's name, while it does.
live: HashMap<(u64, String), usize>,
}
impl Table {
/// The entry for `name` of the document `uid`, made when there is none.
fn slot(&mut self, uid: u64, name: &str, kind: Option<VariableKind>, what: &str) -> std::result::Result<usize, HostError> {
if let Some(&at) = self.live.get(&(uid, name.to_string()))
&& self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind)
{
return Ok(at);
}
if self.entries.len() >= MAX_HANDLES {
return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run")));
}
self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true });
let at = self.entries.len() - 1;
self.live.insert((uid, name.to_string()), at);
Ok(at)
}
/// The entry `at` no longer names anything.
fn kill(&mut self, at: usize) {
if let Some(e) = self.entries.get_mut(at) {
e.alive = false;
let k = (e.uid, std::mem::take(&mut e.name));
if self.live.get(&k) == Some(&at) {
self.live.remove(&k);
}
}
}
/// The entry `at` names `name`, of `kind`, from now on: a rename made through it.
fn rename(&mut self, at: usize, name: &str, kind: Option<VariableKind>) {
let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return };
self.kill(at);
if let Some(e) = self.entries.get_mut(at) {
*e = Entry { uid, name: name.to_string(), kind, alive: true };
}
self.live.insert((uid, name.to_string()), at);
}
/// Kills each live entry `keep` refuses.
fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) {
let gone: Vec<usize> = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect();
for at in gone {
self.kill(at);
}
}
}
/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last
/// checked against it.
#[derive(Default)]
pub(super) struct Handles {
vars: RefCell<Table>,
sets: RefCell<Table>,
seen: RefCell<Vec<(u64, u64)>>,
}
/// The data sets of the active document before a command that may replace them (an import), while
/// the run holds a `Dataset`; `None` for any other command.
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<DataSet>)> {
if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() {
return None;
}
let s = h.session.try_borrow().ok()?;
s.active().map(|st| (st.uid, st.doc.variables.datasets.clone()))
}
/// After each command a script runs: the objects whose variable or data set it removed stop
/// working, so one made again under the same name does not bring them back. An import that leaves
/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset`
/// of that document, also when the new data sets reuse the names; an import that failed, was put
/// back or left the data sets as they were stops none.
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<DataSet>)>) {
let hs = &h.dom.vars;
if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() {
return;
}
let Ok(s) = h.session.try_borrow() else { return };
let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid));
let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect();
let changed: HashSet<u64> = {
let seen = hs.seen.borrow();
now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect()
};
*hs.seen.borrow_mut() = now;
if changed.is_empty() && replaced.is_none() {
return;
}
let mut kinds: HashMap<u64, HashMap<&str, VariableKind>> = HashMap::new();
let mut sets: HashMap<u64, HashSet<&str>> = HashMap::new();
for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) {
let vars = &st.doc.variables;
kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect());
sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect());
}
hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind);
hs.sets
.borrow_mut()
.sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str()))));
}
fn kind_text(k: VariableKind) -> Data {
let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n);
text(format!("VariableKind.{name}"))
}
fn kind_of(d: &Data) -> std::result::Result<VariableKind, HostError> {
let found = match d {
Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k),
_ => None,
};
match found {
Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())),
Some(k) => Ok(k),
None => Err(HostError::Type("kind must be a VariableKind value".into())),
}
}
/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes.
fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> {
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
if s.len() > MAX_TEXT_BYTES {
return Err(HostError::Range(format!("the {what} is too long")));
}
Ok(s)
}
/// The `name` field of a command's result.
fn result_name(d: &Data) -> Option<String> {
let Data::Object(o) = d else { return None };
o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None })
}
fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer {
let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?;
Ok(host_ref("Variable", &[float(h.run), float(at as u64)]))
}
fn set_ref(h: &Host, uid: u64, name: &str) -> Answer {
let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?;
Ok(host_ref("Dataset", &[float(h.run), float(at as u64)]))
}
/// A variable or data set an object names: its document, its handle's index and its name.
struct Named {
doc: Doc,
at: usize,
name: String,
kind: Option<VariableKind>,
}
/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its
/// document.
fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result<Named, HostError> {
let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) };
let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) };
let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) };
let stale = || HostError::Error(stale.into());
if whole(run) != Some(h.run) {
return Err(stale());
}
let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?;
let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets };
let (uid, name, kind) = {
let t = table.borrow();
let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?;
(e.uid, e.name.clone(), e.kind)
};
let doc = find_doc(h, float(h.run), float(uid));
let there = doc.is_some_and(|doc| {
with_doc(h, doc, |_, st| {
let vars = &st.doc.variables;
if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() }
})
});
match doc {
Some(doc) if there => Ok(Named { doc, at, name, kind }),
_ => {
table.borrow_mut().kill(at);
Err(stale())
}
}
}
fn this_var(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
named_of(h, arg(a, 0), true)
}
fn this_set(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
named_of(h, arg(a, 0), false)
}
/// The index argument of a collection's indexer: a whole number, or `None`.
fn index_arg(d: &Data) -> Option<usize> {
match d {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()),
_ => None,
}
}
// ---- Document ----
fn this_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Document")
}
fn doc_variables(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("Variables", &[float(h.run), float(doc.uid)]))
}
fn doc_datasets(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)]))
}
fn doc_locked(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked)))
}
/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so.
fn doc_set_locked(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) };
if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked {
on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?;
}
Ok(Data::Undefined)
}
fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) {
Some(name) => set_ref(h, doc.uid, &name),
None => Ok(Data::Null),
}
}
/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active
/// one and the art already shows it.
fn display(h: &Host, set: &Named) -> Answer {
let shown = with_doc(h, set.doc, |_, st| {
let vars = &st.doc.variables;
vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values()))
});
if !shown {
on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?;
}
Ok(Data::Undefined)
}
fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
if handle_of(arg(a, 1), "Dataset").is_none() {
return Err(HostError::Type("activeDataset must be a Dataset".into()));
}
let set = named_of(h, arg(a, 1), false)?;
if set.doc.uid != doc.uid {
return Err(HostError::Error("the data set is in another document".into()));
}
display(h, &set)
}
/// The path of the `File` argument of `what`, which must be a file the script may reach for
/// `access` through its own `File` objects.
fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result<String, HostError> {
let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) };
if path.chars().count() > super::super::files::MAX_PATH_CHARS {
return Err(HostError::Range(format!("{what}: the path is too long")));
}
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
gate.check(path, access).map_err(HostError::Error)?;
Ok(path.to_string())
}
/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's
/// variables and data sets with the library's.
fn doc_import(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = file_arg(h, a, "importVariables", Access::Read)?;
on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?;
Ok(Data::Undefined)
}
/// `exportVariables(file)`: `variable.saveLibrary` into the file.
fn doc_export(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = file_arg(h, a, "exportVariables", Access::Write)?;
on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?;
Ok(Data::Undefined)
}
// ---- Variables ----
fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Variables")
}
fn vars_typename(h: &Host, a: &[Data]) -> Answer {
vars_doc(h, a)?;
Ok(text("Variables"))
}
fn vars_length(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64)))
}
fn vars_parent(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn vars_at(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) {
Some(v) => var_ref(h, doc.uid, &v),
None => Ok(Data::Undefined),
}
}
fn vars_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let name = name_arg(arg(a, 1), "name")?;
let found = with_doc(h, doc, |_, st| {
h.charge_call(st.doc.variables.variables.len() as u64)?;
Ok::<_, HostError>(st.doc.variables.variable(name).cloned())
})?;
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v))
}
fn vars_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => vars_by_name(h, a),
Data::Number(_) => match vars_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the
/// first free name). → the new variable.
fn vars_add(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let name = with_doc(h, doc, |_, st| {
let vars = &st.doc.variables;
(1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default()
});
on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?;
var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text })
}
/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is
/// none.
fn vars_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect());
if !names.is_empty() {
on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?;
}
Ok(Data::Undefined)
}
// ---- Variable ----
fn var_typename(h: &Host, a: &[Data]) -> Answer {
this_var(h, a)?;
Ok(text("Variable"))
}
fn var_parent(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
Ok(doc_ref(h, v.doc.uid))
}
fn var_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(this_var(h, a)?.name))
}
/// `name = text`: `variable.rename`, which trims it, with no command when the name stays.
fn var_set_name(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
let to = name_arg(arg(a, 1), "name")?;
if to.trim() == v.name {
return Ok(Data::Undefined);
}
let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?;
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind);
Ok(Data::Undefined)
}
fn var_kind(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown)))
}
/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot
/// hold it and drops the variable's values, with no command when the kind stays.
fn var_set_kind(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
let kind = kind_of(arg(a, 1))?;
if Some(kind) == v.kind {
return Ok(Data::Undefined);
}
on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?;
h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind));
Ok(Data::Undefined)
}
fn var_page_items(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
with_doc(h, v.doc, |_, st| {
let ids: Vec<crate::NodeId> =
st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if ids.len() > MAX_LISTED {
return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects")));
}
h.charge_call(16 * ids.len() as u64)?;
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
})
}
/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values.
fn var_remove(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?;
h.dom.vars.vars.borrow_mut().kill(v.at);
Ok(Data::Undefined)
}
// ---- Datasets ----
fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Datasets")
}
fn sets_typename(h: &Host, a: &[Data]) -> Answer {
sets_doc(h, a)?;
Ok(text("Datasets"))
}
fn sets_length(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64)))
}
fn sets_parent(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn sets_at(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) {
Some(name) => set_ref(h, doc.uid, &name),
None => Ok(Data::Undefined),
}
}
fn sets_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let name = name_arg(arg(a, 1), "name")?;
let found = with_doc(h, doc, |_, st| {
h.charge_call(st.doc.variables.datasets.len() as u64)?;
Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone()))
})?;
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n))
}
fn sets_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => sets_by_name(h, a),
Data::Number(_) => match sets_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new
/// data set and makes it the active one. → the new data set.
fn sets_add(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?;
let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?;
set_ref(h, doc.uid, &name)
}
/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is
/// none.
fn sets_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect());
if !names.is_empty() {
on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?;
}
Ok(Data::Undefined)
}
// ---- Dataset ----
fn set_typename(h: &Host, a: &[Data]) -> Answer {
this_set(h, a)?;
Ok(text("Dataset"))
}
fn set_parent(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
Ok(doc_ref(h, d.doc.uid))
}
fn set_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(this_set(h, a)?.name))
}
/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays.
fn set_set_name(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
let to = name_arg(arg(a, 1), "name")?;
if to.trim() == d.name {
return Ok(Data::Undefined);
}
let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?;
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
h.dom.vars.sets.borrow_mut().rename(d.at, &name, None);
Ok(Data::Undefined)
}
fn set_display(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
display(h, &d)
}
/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no
/// command when it already holds what the bound objects hold.
fn set_update(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
let same = with_doc(h, d.doc, |_, st| {
let doc = &st.doc;
let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some());
bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values()))
});
if !same {
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?;
}
Ok(Data::Undefined)
}
/// `dataset.remove()`: `dataset.delete` of this data set.
fn set_remove(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?;
h.dom.vars.sets.borrow_mut().kill(d.at);
Ok(Data::Undefined)
}
// ---- Page items ----
/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its
/// content.
fn slot_kind(n: &Node, content: bool) -> std::result::Result<VariableKind, HostError> {
if !content {
return Ok(VariableKind::Visibility);
}
crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into()))
}
/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's
/// kind bound to the object, in the order the variables are defined, or `null`.
fn binding(h: &Host, a: &[Data], content: bool) -> Answer {
let item = item_of(h, arg(a, 0))?;
let found = with_doc(h, item.doc, |_, st| {
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
let kind = slot_kind(n, content)?;
let vars = &st.doc.variables;
let bound = vars.bindings.get(&item.id);
Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned())
})?;
match found {
Some(v) => var_ref(h, item.doc.uid, &v),
None => Ok(Data::Null),
}
}
/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of
/// the object's document, or with none for `null`. No command runs when the object already has just
/// that binding of the slot's kind.
fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer {
let item = item_of(h, arg(a, 0))?;
let variable = match arg(a, 1) {
Data::Null => None,
d if handle_of(d, "Variable").is_some() => {
let v = named_of(h, d, true)?;
if v.doc.uid != item.doc.uid {
return Err(HostError::Error("the variable is in another document".into()));
}
Some(v.name)
}
_ => return Err(HostError::Type("give a Variable or null".into())),
};
let same = with_doc(h, item.doc, |_, st| {
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
let kind = slot_kind(n, content)?;
let vars = &st.doc.variables;
let bound = vars.bindings.get(&item.id);
let held: Vec<&str> =
vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect();
Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::<Vec<_>>())
})?;
if !same {
let slot = if content { "content" } else { "visibility" };
edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?;
}
Ok(Data::Undefined)
}
fn item_visibility(h: &Host, a: &[Data]) -> Answer {
binding(h, a, false)
}
fn item_set_visibility(h: &Host, a: &[Data]) -> Answer {
set_binding(h, a, false)
}
fn item_content(h: &Host, a: &[Data]) -> Answer {
binding(h, a, true)
}
fn item_set_content(h: &Host, a: &[Data]) -> Answer {
set_binding(h, a, true)
}
// ---- Registration ----
/// The members this module adds to `Document`.
pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> {
named(vec![
("variables", get(l, doc_variables)),
("dataSets", get(l, doc_datasets)),
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)),
("variablesLocked", property(l, doc_locked, doc_set_locked)),
("importVariables", method(l, doc_import)),
("exportVariables", method(l, doc_export)),
])
}
/// The members this module adds to `PageItem`.
pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> {
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))])
}
/// The members this module adds to the page item class `class`.
pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> {
match class {
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]),
_ => Vec::new(),
}
}
/// The classes this module adds.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
vec![
class(
"Variables",
None,
named(vec![
("typename", get(l, vars_typename)),
("length", get(l, vars_length)),
("parent", get(l, vars_parent)),
("index", method(l, vars_index)),
("getByName", method(l, vars_by_name)),
("add", method(l, vars_add)),
("removeAll", method(l, vars_remove_all)),
]),
Some(function(l, vars_at)),
),
class(
"Variable",
None,
named(vec![
("typename", get(l, var_typename)),
("parent", get(l, var_parent)),
("name", property(l, var_name, var_set_name)),
("kind", property(l, var_kind, var_set_kind)),
("pageItems", get(l, var_page_items)),
("remove", method(l, var_remove)),
]),
None,
),
class(
"Datasets",
None,
named(vec![
("typename", get(l, sets_typename)),
("length", get(l, sets_length)),
("parent", get(l, sets_parent)),
("index", method(l, sets_index)),
("getByName", method(l, sets_by_name)),
("add", method(l, sets_add)),
("removeAll", method(l, sets_remove_all)),
]),
Some(function(l, sets_at)),
),
class(
"Dataset",
None,
named(vec![
("typename", get(l, set_typename)),
("parent", get(l, set_parent)),
("name", property(l, set_name, set_set_name)),
("display", method(l, set_display)),
("update", method(l, set_update)),
("remove", method(l, set_remove)),
]),
None,
),
]
}
/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings.
pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> {
let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect();
realm.define_host_object("VariableKind", items)
}
+2
View File
@@ -1354,6 +1354,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
let params = params.clone();
let session = host.session.clone();
let started = clock();
let before = dom::before_command(host, &id);
let r = {
let mut s = session.borrow_mut();
step(&mut s, host, &id, &params)
@@ -1387,6 +1388,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
dom::after_command(host, before);
crossed.map(|data| (data, value))
}
+1
View File
@@ -185,6 +185,7 @@ mod script_include;
mod script_io;
mod script_run;
mod script_tags;
mod script_variables;
mod script_xmp;
mod scripts;
mod segment_nudge;
+161
View File
@@ -892,6 +892,167 @@ fn a_profiles_normal_character_style_is_the_default_font() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("apply-defaults");
const GLOW: &str = r#"<filter id="Glow7653"><feOffset dx="3" dy="3"/></filter>"#;
// The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with
// the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("swatch.new", &json!({"name": "Laser Red", "color": "#ff0000", "global": true})).unwrap();
s.execute("svgFilter.define", &json!({"xml": GLOW})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("paint.setStroke", &json!({"swatch": "Laser Red"})).unwrap();
s.execute("stroke.set", &json!({"weight": 0.25})).unwrap();
s.execute("svgFilter.apply", &json!({"name": "Glow7653"})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
let serif =
s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Serif", "font": "Source Serif 4", "size": 9, "color": "#ff0000"})).unwrap();
s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": serif["id"]})).unwrap();
s.execute("document.save", &json!({})).unwrap();
// An RGB document made without a profile, with another filter named Glow7653, type in the
// default font and a rectangle linked to its Default Graphic Style.
s.execute("file.new", &json!({"colorMode": "rgb"})).unwrap();
s.execute("svgFilter.define", &json!({"xml": r#"<filter id="Glow7653"><feOffset dx="9" dy="9"/></filter>"#})).unwrap();
let before = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Before"})).unwrap();
let linked = s.execute("shape.rectangle", &json!({"x": 20, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let default_font = first_run(&s, &before["id"]);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "print"})).unwrap();
assert_eq!((r["name"].clone(), r["changed"].clone()), (json!("Print"), json!(true)), "{r}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
// The swatch comes along, in the document's color mode, and the style paints with it.
let d = &s.doc().unwrap().doc;
let red = d.swatches.iter().find(|w| w.name == "Laser Red").cloned().expect("the style's swatch");
assert!(matches!(red.paint, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint);
let stroke = s.paint.stroke.clone();
assert!(matches!(&stroke, Paint::Solid { swatch: Some(w), .. } if w == "Laser Red"), "{stroke:?}");
// The profile's filter keeps its definition under a free name; the document's keeps its own.
let style = d.graphic_style("Default Graphic Style").cloned().unwrap();
let filter = style.appearance.effects.iter().find(|e| e.id == "svg.filter").cloned().expect("the style's filter");
assert_ne!(filter.params["name"], "Glow7653", "{filter:?}");
assert!(filter.params["xml"].as_str().is_some_and(|x| x.contains("dx=\"3\"")), "{filter:?}");
assert!(d.svg_filters.iter().any(|f| f.name == "Glow7653" && f.xml.contains("dx=\"9\"")));
// New art takes the profile's look; so does the rectangle linked to the style.
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
assert_eq!(look(&s, id), (Paint::None, stroke.clone(), Some(0.25)));
assert_eq!(look(&s, linked), (Paint::None, stroke.clone(), Some(0.25)));
// New type starts in the profile's font, and type in [Normal Character Style] follows it.
let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "After"})).unwrap();
for id in [&made["id"], &before["id"]] {
let st = first_run(&s, id);
assert_eq!((st.font_family.as_str(), st.size), ("Source Serif 4", 9.0));
// The profile's CMYK red is converted to the document's color mode.
assert!(
matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { r, g, b }, .. } if r > 0.8 && g < 0.3 && b < 0.3),
"a converted red: {:?}",
st.fill
);
}
// Again: nothing changes and no undo step is recorded.
let step = s.doc().unwrap().history.step();
let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap();
assert_eq!(r["changed"], false, "{r}");
assert_eq!(s.doc().unwrap().history.step(), step);
// A category without a profile file gives the shipped defaults back.
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let print_paint = s.paint.clone();
let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Web"})).unwrap();
assert_eq!(r["changed"], true, "{r}");
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
let st = first_run(&s, &before["id"]);
assert_eq!((st.font_family, st.size), (default_font.font_family.clone(), default_font.size));
// Undo goes back to the Print profile's defaults in the document and for new art; Redo
// brings the shipped ones again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(first_run(&s, &before["id"]).font_family, "Source Serif 4");
assert_eq!(s.paint, print_paint);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
s.execute("edit.undo", &json!({})).unwrap();
// An unknown profile is an error and changes nothing.
let step = s.doc().unwrap().history.step();
assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err());
assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err());
assert_eq!(s.doc().unwrap().history.step(), step);
let _ = std::fs::remove_dir_all(&dir);
}
/// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's
/// defaults that Use Profile Defaults has just set.
#[test]
fn profile_defaults_stay_with_an_unrelated_object_selected() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("apply-defaults-selected");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("stroke.set", &json!({"weight": 0.25})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
s.execute("file.new", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "newArtBasic", "value": false})).unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap();
assert_eq!(r["changed"], true, "{r}");
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25)));
let _ = std::fs::remove_dir_all(&dir);
}
/// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open
/// document that composite font too, in place of the document's of the same name.
#[test]
fn profile_defaults_bring_the_composite_font_of_the_default_font() {
let font = |roman: f64| {
json!({"name": "CF Profile 7653", "parts": {
"kanji": {"font": "Source Sans 3"},
"roman": {"font": "JetBrains Mono", "size": roman},
}})
};
let (mut s, dir) = with_profiles("apply-defaults-composite");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap();
let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap();
s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": t["id"]})).unwrap();
s.execute("document.save", &json!({})).unwrap();
s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font(100.0)]})).unwrap();
let profile = |s: &Session| s.doc().unwrap().doc.composite_fonts.iter().find(|f| f.name == "CF Profile 7653").map(|f| f.parts.roman.size);
assert_eq!(profile(&s), Some(100.0));
let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap();
assert_eq!(r["changed"], true, "{r}");
assert_eq!(profile(&s), Some(50.0), "the profile's definition");
let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Ab"})).unwrap();
assert_eq!(first_run(&s, &made["id"]).font_family, "CF Profile 7653");
let missing = s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count();
assert_eq!(missing, 0);
// Again: nothing changes.
let step = s.doc().unwrap().history.step();
assert_eq!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap()["changed"], false);
assert_eq!(s.doc().unwrap().history.step(), step);
// Undone, the document's own definition is back.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(profile(&s), Some(100.0));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() {
let (mut s, dir) = with_profiles("errors");
+22
View File
@@ -1265,6 +1265,28 @@ fn wrappers_go_stale_after_delete_and_undo() {
assert!(e.contains("Stale page item"), "{e}");
}
#[test]
fn wrappers_go_stale_after_revert() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert");
let path = folder.join("saved's art.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let held = "var d = app.activeDocument, i = d.pageItems[0], l = i.parent; i.name = 'changed'; vc.run('file.revert');";
let out = log(&mut s, &format!("{held} vc.log(d.pageItems.length); vc.log(d.pageItems[0] === i); vc.log(d.pageItems[0].parent === l);"));
assert_eq!(out, vec![json!(2), json!(false), json!(false)]);
for operation in [
"i.name",
"i.name = 'wrong'",
"l.name",
"i.move(d.pageItems[1], ElementPlacement.PLACEBEFORE)",
"d.pageItems[1].duplicate(i, ElementPlacement.PLACEBEFORE)",
"d.pageItems[1].move(l, ElementPlacement.PLACEATEND)",
] {
let source = format!("{held} try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);");
assert_eq!(log(&mut s, &source), vec![json!("Stale page item"), json!(2)], "{operation}");
}
}
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
+452
View File
@@ -0,0 +1,452 @@
//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the
//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::tests_links::{Folder, RED, place, png, write};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
/// A document with a rectangle and, above it, a type object, so `pageItems[0]` is the type and `pageItems[1]` the rectangle.
fn doc() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap());
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap());
(s, t, r)
}
fn variables(s: &Session) -> Vec<(String, &'static str)> {
s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect()
}
#[test]
fn variables_collection_adds_finds_renames_and_removes() {
let (mut s, _, _) = doc();
let before = undo_steps(&s);
let out = log(
&mut s,
r#"var v = app.activeDocument.variables;
vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename);
var a = v.add(), b = v.add();
vc.log([a.name, b.name, a.kind, v.length].join());
b.name = 'title'; b.kind = VariableKind.VISIBILITY;
vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join());
vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined);
a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#,
);
assert_eq!(
out,
vec![
json!(0),
json!("Variables"),
json!("Document"),
json!("Variable1,Variable2,VariableKind.TEXTUAL,2"),
json!("title,VariableKind.VISIBILITY,title,Variable1,title"),
json!(true),
json!(1),
json!("Document,Variable")
]
);
assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]);
assert_eq!(undo_steps(&s), before + 1, "one undo step for the run");
assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found"));
assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found"));
assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index"));
}
#[test]
fn variable_names_and_kinds_are_checked_before_anything_changes() {
let (mut s, _, _) = doc();
s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap();
s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap();
let before = undo_steps(&s);
assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists"));
assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName"));
assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string"));
assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind"));
assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown"));
let long = "x".repeat(5000);
assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long"));
// Setting what the variable already has runs no command.
log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;");
assert_eq!(undo_steps(&s), before);
assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]);
}
#[test]
fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() {
let (mut s, _, _) = doc();
let e = failure(
&mut s,
"var v = app.activeDocument.variables.add();\
vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\
v.name;",
);
assert!(e.contains("Stale variable"), "{e}");
// A failed run keeps nothing, so the variable is defined outside the script.
s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap();
let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;");
assert!(e.contains("Stale variable"), "{e}");
let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;");
assert!(e.contains("Stale variable"), "{e}");
// A rename through the object keeps it.
assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]);
// A named engine keeps its globals, but an object from an earlier run is stale.
run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap();
let e = failure(&mut s, "#targetengine keepvars\nheld.name;");
assert!(e.contains("Stale variable"), "{e}");
}
#[test]
fn collections_from_an_earlier_run_throw_on_every_member() {
let (mut s, _, _) = doc();
run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap();
for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] {
let e = failure(&mut s, &format!("#targetengine keepcols\n{member};"));
assert!(e.contains("Stale document"), "{member}: {e}");
}
}
#[test]
fn content_and_visibility_variables_bind_one_variable_per_slot() {
let (mut s, t, r) = doc();
for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] {
s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap();
}
let before = undo_steps(&s);
let out = log(
&mut s,
r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1];
vc.log(t.contentVariable === null && t.visibilityVariable === null);
t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other');
r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide');
vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name);
vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename);
vc.log(r.contentVariable === undefined);"#,
);
assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]);
let vars = &s.active().unwrap().doc.variables;
assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::<Vec<_>>()), Some(vec!["other".to_string()]));
assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::<Vec<_>>()), Some(vec!["hide".to_string()]));
assert_eq!(undo_steps(&s), before + 1);
// A variable of another kind is refused, and nothing changes; null unbinds that slot only.
let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');");
assert!(e.contains("visibility variable"), "{e}");
let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');");
assert!(e.contains("text variable"), "{e}");
assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null"));
log(
&mut s,
"var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;",
);
let vars = &s.active().unwrap().doc.variables;
assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::<Vec<_>>()), Some(vec!["show".to_string()]));
// Assigning the binding the object already has runs no command.
let steps = undo_steps(&s);
log(
&mut s,
"var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;",
);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn an_embedded_image_cannot_take_an_image_variable() {
let dir = Folder::new("script-vars-embedded");
let path = dir.file("red.png");
write(&path, &png(10, 10, RED));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = place(&mut s, &path);
s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap();
let out =
log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);");
assert_eq!(out, vec![json!("photo")]);
s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap();
let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];");
assert!(e.contains("embedded image"), "{e}");
assert!(s.active().unwrap().doc.variables.bindings.is_empty());
// Its visibility still takes a visibility variable.
s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);",
);
assert_eq!(out, vec![json!("shown")]);
}
#[test]
fn data_sets_capture_display_update_and_remove() {
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
let before = undo_steps(&s);
let out = log(
&mut s,
r#"var d = app.activeDocument, sets = d.dataSets;
vc.log(sets.length + ',' + (d.activeDataset === null));
var one = sets.add();
vc.run('text.setText', {id: TEXT_ID, text: 'World'});
var two = sets.add();
vc.log([one.name, two.name, sets.length, d.activeDataset.name].join());
one.display(); vc.log(d.activeDataset.name);
vc.run('text.setText', {id: TEXT_ID, text: 'Again'});
two.update(); vc.log(d.activeDataset.name);
two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name);
d.activeDataset = two; vc.log(d.activeDataset.name);
one.remove(); vc.log(sets.length);"#
.replace("TEXT_ID", &t.0.to_string())
.as_str(),
);
assert_eq!(
out,
vec![
json!("0,true"),
json!("Data Set 1,Data Set 2,2,Data Set 2"),
json!("Data Set 1"),
json!("Data Set 1"),
json!("Second,Second"),
json!("Second"),
json!(1)
]
);
let vars = &s.active().unwrap().doc.variables;
assert_eq!(vars.datasets.len(), 1);
assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into())));
assert_eq!(vars.active_dataset.as_deref(), Some("Second"));
assert_eq!(undo_steps(&s), before + 1, "one undo step for the run");
let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;");
assert!(e.contains("Stale data set"), "{e}");
log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();");
assert!(s.active().unwrap().doc.variables.datasets.is_empty());
assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset"));
}
#[test]
fn update_of_a_data_set_that_holds_the_art_runs_no_command() {
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
s.execute("dataset.capture", &json!({})).unwrap();
let before = undo_steps(&s);
let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap();
assert_eq!(undo_steps(&s), before);
assert_eq!(r["slowestCommands"], json!([]), "{r}");
}
#[test]
fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() {
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
s.execute("dataset.capture", &json!({})).unwrap();
let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;");
assert!(e.contains("Stale data set"), "{e}");
}
#[test]
fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() {
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap();
let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);");
assert_eq!(out.len(), 1, "{out:?}");
let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;");
assert!(e.contains("Stale data set"), "{e}");
}
#[test]
fn variables_locked_refuses_new_variables_but_not_bindings() {
let (mut s, _, _) = doc();
s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\
d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);",
);
assert_eq!(out, vec![json!(false), json!(true)]);
assert!(s.active().unwrap().doc.variables.locked);
let e = failure(&mut s, "app.activeDocument.variables.add();");
assert!(e.contains("locked"), "{e}");
assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false"));
assert_eq!(variables(&s).len(), 1);
}
/// A variable library of two variables and two data sets, written for these tests from the elements
/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of
/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements
/// with `dataSetName`.
const LIBRARY: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<variableSets>
<variableSet varSetName="binding1" locked="none">
<variables>
<variable varName="title" trait="textcontent"/>
<variable varName="badge" trait="visibility"/>
</variables>
<sampleDataSets>
<sampleDataSet dataSetName="One"><title><p>Hello</p></title><badge>true</badge></sampleDataSet>
<sampleDataSet dataSetName="Two"><title><p>World</p></title><badge>false</badge></sampleDataSet>
</sampleDataSets>
</variableSet>
</variableSets>
"#;
/// A fresh folder with a `main` folder for the script, by its real path.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::canonicalize(&base).unwrap()
}
/// Runs `main/main.jsx` in `base` with `text`, on `s`.
fn run_file(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
let main = base.join("main/main.jsx");
std::fs::write(&main, text).unwrap();
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
}
#[test]
fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() {
let base = folder("import");
std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap();
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
let before = undo_steps(&s);
let r = run_file(
&mut s,
&base,
"var d = app.activeDocument; d.importVariables(new File('lib.xml'));\
vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\
d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);",
)
.unwrap();
assert_eq!(r["log"], json!(["2,2,Two", "title"]));
assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]);
assert_eq!(s.active().unwrap().doc.story_text(t), "World");
assert_eq!(undo_steps(&s), before + 1);
}
#[test]
fn import_variables_takes_only_a_file_the_script_may_read() {
let base = folder("import-refused");
std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap();
std::fs::write(base.join("outside.xml"), LIBRARY).unwrap();
let (mut s, _, _) = doc();
s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap();
let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string();
assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File"));
assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File"));
let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/");
let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));"));
assert!(e.contains("access denied"), "{e}");
// The open document's own file is refused, though the script's commands may open it.
let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned();
s.execute("file.saveAs", &json!({"path": saved})).unwrap();
let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/")));
assert!(e.contains("access denied"), "{e}");
// A plain object cannot pass for a File.
let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);");
assert!(e.contains("not plain data"), "{e}");
assert_eq!(variables(&s), vec![("keep".to_string(), "text")]);
}
#[test]
fn import_variables_refuses_hostile_libraries_before_any_edit() {
let base = folder("import-hostile");
let external = r#"<?xml version="1.0"?><!DOCTYPE v [<!ENTITY x SYSTEM "file:///etc/hosts">]><variableSets><variableSet><variables><variable varName="a" trait="textcontent"/></variables></variableSet></variableSets>"#;
std::fs::write(base.join("main/external.xml"), external).unwrap();
let deep = format!("<variableSets>{}{}</variableSets>", "<a>".repeat(300), "</a>".repeat(300));
std::fs::write(base.join("main/deep.xml"), deep).unwrap();
let mut big = LIBRARY.as_bytes().to_vec();
big.resize((8 << 20) + 1, b' ');
std::fs::write(base.join("main/big.xml"), big).unwrap();
let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\"");
std::fs::write(base.join("main/twice.xml"), twice).unwrap();
let (mut s, _, _) = doc();
s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap();
let before = undo_steps(&s);
for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] {
let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string();
assert!(e.contains(says), "{file}: {e}");
}
assert_eq!(variables(&s), vec![("keep".to_string(), "text")]);
assert_eq!(undo_steps(&s), before);
// Locked variables refuse a library that would delete or define one.
s.execute("variable.lock", &json!({"locked": true})).unwrap();
std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap();
let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string();
assert!(e.contains("locked"), "{e}");
assert_eq!(variables(&s), vec![("keep".to_string(), "text")]);
}
#[test]
fn export_variables_writes_a_library_that_import_reads_back() {
let (mut s, t, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap();
s.execute("dataset.capture", &json!({"name": "Row"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\
d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\
d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);",
);
let xml = out[0].as_str().unwrap();
for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "<p>Hello</p>"] {
assert!(xml.contains(part), "{part} in {xml}");
}
assert_eq!(out[1], json!("title,Row"));
}
#[test]
fn export_variables_writes_only_where_the_script_may_write() {
let base = folder("export-refused");
let (mut s, _, _) = doc();
s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap();
// The open document's own file is refused, though the script's commands may save it.
let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned();
s.execute("file.saveAs", &json!({"path": saved})).unwrap();
let before = std::fs::read(&saved).unwrap();
let path = saved.replace('\\', "/");
let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string();
assert!(e.contains("access denied"), "{e}");
assert_eq!(std::fs::read(&saved).unwrap(), before);
// The script's own folder is only read.
let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string();
assert!(e.contains("access denied"), "{e}");
assert!(!base.join("main/out.xml").exists());
assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File"));
// A library that cannot be written leaves no file.
s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap();
let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));");
assert!(e.contains("can't be saved"), "{e}");
let out =
log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);");
assert_eq!(out, vec![json!(false)]);
}
+18
View File
@@ -292,6 +292,24 @@ fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() {
assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]);
}
/// Pasted again, art whose filter was renamed takes the name the first paste gave it, so the
/// same filter does not come in under a new name each time.
#[test]
fn pasting_a_renamed_filter_again_reuses_its_name() {
let mut s = session();
run(&mut s, "svgFilter.define", json!({"xml": SHIFT}));
let svg = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs>{SHIFT_MORE}</defs><rect width="30" height="30" filter="url(#Shift)"/></svg>"#
);
run(&mut s, "clipboard.importSvg", json!({"svg": svg}));
run(&mut s, "edit.pasteInPlace", json!({}));
run(&mut s, "edit.pasteInPlace", json!({}));
let pasted = filter_effects(&s);
assert_eq!(pasted.len(), 2);
assert_eq!(pasted[0], pasted[1], "{pasted:?}");
assert_ne!(pasted[0].0, "Shift", "{pasted:?}");
}
/// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own
/// definition under a free name no longer than its own (a free letter for a one-letter name), and
/// its id is that name.
+16
View File
@@ -262,6 +262,22 @@ fn document_color_mode_converts_effect_colors() {
assert_eq!((object(&s), style(&s)), before);
}
/// Document Color Mode converts the fill of a character style, so type set in the style after the
/// switch paints in the new mode.
#[test]
fn document_color_mode_converts_character_style_colors() {
let mut s = session();
let id = run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "Ink", "color": "#ff0000"}))["id"].clone();
run(&mut s, "charStyle.new", json!({"name": "Red", "id": id}));
let fill = |s: &Session| {
let def = doc(s).char_styles.iter().find(|c| c.name == "Red").expect("the style");
serde_json::from_value::<Paint>(def.attrs["fill"].clone()).expect("a fill")
};
assert!(matches!(fill(&s).color(), Some(Color::Rgb { .. })), "{:?}", fill(&s));
run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}));
assert!(matches!(fill(&s).color(), Some(Color::Cmyk { .. })), "{:?}", fill(&s));
}
/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a
/// graph drawn again after the switch paints its series, labels and lines in the new mode.
#[test]
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
];
@@ -138,6 +139,23 @@ const INSIDE: &[(&str, &str)] = &[
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
// `visibilityVariable` is in its row above.
("", "Dataset Datasets Variable VariableKind Variables"),
("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"),
("Variables.", "prototype"),
("Variables.prototype.", "add constructor getByName index length parent removeAll typename"),
("Variable.", "prototype"),
("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"),
("Datasets.", "prototype"),
("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"),
("Dataset.", "prototype"),
("Dataset.prototype.", "constructor display name name= parent remove typename update"),
("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="),
("GraphItem.prototype.", "contentVariable contentVariable="),
("PlacedItem.prototype.", "contentVariable contentVariable="),
("RasterItem.prototype.", "contentVariable contentVariable="),
("TextFrame.prototype.", "contentVariable contentVariable="),
];
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
+30
View File
@@ -12633,6 +12633,36 @@ fn an_envelope_mapping_from_its_contents_strokes_is_read_back() {
assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin);
}
/// A stroked straight line, with no height without its stroke, saves the size of its box with its
/// stroke, and opens mapping from that box.
#[test]
fn a_stroked_straight_line_mapping_from_its_stroke_is_read_back() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin};
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut envelope = envelope_node(
&mut doc,
EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] },
50.0,
false,
EnvelopeOptions::NEW,
);
let line = shapes::line(kurbo::Point::new(40.0, 50.0), kurbo::Point::new(160.0, 50.0));
let line = Node::path(doc.alloc_id(), line, Appearance::basic(Paint::None, solid(Color::BLACK), 10.0));
let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() };
*content = vec![Arc::new(line)];
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap();
assert!(plain.height() < 1e-9 && stroked.height() > 9.0, "{plain:?} {stroked:?}");
options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap();
let margin = options.bounds_margin;
assert!(margin[0] > 0.0 && margin[1] > 0.0, "{margin:?}");
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
let (back, warnings, notes) = envelope_back(&doc);
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin);
}
/// A test's stand-in for a node that must be an envelope.
fn unreachable_envelope() -> ! {
panic!("not an envelope")
+3 -3
View File
@@ -32,7 +32,7 @@ use std::sync::Arc;
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
use vectorcraft_doc::live::{
EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes,
envelope_content_boxes_with, envelope_stroke_margin,
envelope_content_boxes_with, envelope_margin_lengths, envelope_stroke_margin,
};
use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef};
use vectorcraft_geom::PathData;
@@ -133,7 +133,7 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> {
/// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies
/// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the
/// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for
/// contents with no width or no height.
/// contents with neither a width nor a height.
fn saved_margin(o: &Obj, content: &[Arc<Node>], scale: f64) -> Option<[f32; 4]> {
let saved = |key: &str| match o.nums(key).as_slice() {
[v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()),
@@ -305,7 +305,7 @@ fn painted_margin(painted: Rect, plain: Rect) -> Option<[f32; 4]> {
/// Do bounds margins `a` and `b` give contents with geometric box `plain` the same box, each side
/// within [`PAINTED_SLACK`]?
fn same_box(a: [f32; 4], b: [f32; 4], plain: Rect) -> bool {
let sizes = [plain.height(), plain.height(), plain.width(), plain.width()];
let Some(sizes) = envelope_margin_lengths(plain) else { return a == b };
a.iter().zip(b).zip(sizes).all(|((a, b), size)| (f64::from(*a) - f64::from(b)).abs() * size <= PAINTED_SLACK)
}
+47 -8
View File
@@ -9042,7 +9042,7 @@ fn an_envelope_without_distort_appearance_maps_from_the_geometric_box() {
/// An envelope maps from the geometric box when its file saves that box's size, saves no size,
/// saves a size that isn't a number or saves a size far from both boxes; contents without a stroke
/// have one box, and contents with no height have no margins.
/// have one box.
#[test]
fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap};
@@ -9083,13 +9083,52 @@ fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() {
let thin = format!("{RED}0 1 1 0 1 0 0 XA\n0.2 w\n{}b\n", rect_path(40.0, 20.0, 160.0, 80.0));
let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &thin, 2, &plain)));
assert_eq!(live_envelope(&art(&r.doc)[0]).4.bounds_margin, [0.0; 4]);
// A stroked straight line: 120 × 0 without its stroke, and 120 × 10 as saved.
let keys = format!("{ENVELOPE_KEYS}10 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n");
let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n40 20 m\n160 20 L\nS\n");
let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &line, 2, &plain)));
for n in art(&r.doc) {
if let NodeKind::Envelope { options, .. } = &n.kind {
assert_eq!(options.bounds_margin, [0.0; 4]);
}
/// A stroked straight line, 120 × 0 without its stroke, whose file saves its size with the stroke
/// (120 × 10) maps from that box: the margins across the line are shares of its length. Lines
/// along either axis, in a mesh envelope and in a top object envelope.
#[test]
fn a_stroked_straight_line_saved_with_its_stroke_maps_from_the_stroked_box() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap};
for vertical in [false, true] {
let (w, h) = if vertical { (10.0, 120.0) } else { (120.0, 10.0) };
let outer = Rect::from_center_size((100.0, 50.0), (w, h));
let at = move |(i, j): (usize, usize)| (outer.x0 + i as f64 * w, outer.y0 + j as f64 * h);
let third = move |p: (usize, usize), q: (usize, usize)| {
let ((x, y), (u, v)) = (at(p), at(q));
(x + (u - x) / 3.0, y + (v - y) / 3.0)
};
let mesh = mesh_text(1, 1, &at, &third, None);
let flat = EnvelopeKind::Mesh {
rows: 1,
cols: 1,
points: vec![
Point::new(outer.x0, outer.y0),
Point::new(outer.x1, outer.y0),
Point::new(outer.x0, outer.y1),
Point::new(outer.x1, outer.y1),
],
handles: vec![],
};
let drawn = drawn_box(&flat, outer, outer);
let keys = format!("{ENVELOPE_KEYS}{h} /Real (AIDeformArtHeightKey) ,\n{w} /Real (AIDeformArtWidthKey) ,\n");
let line = if vertical { "100 -10 m\n100 110 L\n" } else { "40 50 m\n160 50 L\n" };
let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n{line}S\n");
for kind in [2, 3] {
let r = read_ok(&layer(&envelope_of(&mesh, &keys, &line, kind, &drawn)));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{vertical} {kind}: {a:#?}");
assert!(r.warnings.is_empty(), "{vertical} {kind}: {:?}", r.warnings);
let (.., options) = live_envelope(&a[0]);
let across = 5.0_f32 / 120.0;
let want = if vertical { [0.0, 0.0, across, across] } else { [across, across, 0.0, 0.0] };
assert!(options.bounds_margin.iter().zip(want).all(|(m, w)| (m - w).abs() < 1e-6), "{vertical} {kind}: {:?}", options.bounds_margin);
let src = EnvelopeMap::of(&a[0]).unwrap().src();
assert!(
(src.x0 - outer.x0).abs() + (src.y0 - outer.y0).abs() + (src.x1 - outer.x1).abs() + (src.y1 - outer.y1).abs() < 1e-3,
"{vertical} {kind}: {src:?}"
);
}
}
}
+13
View File
@@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
})
}
/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose
/// path is in its own slot. `None` for anything else, a `Folder` included.
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
let Some(c) = &i.files else { return Ok(None) };
if i.object(id)?.proto != Some(c.file_proto) {
return Ok(None);
}
Ok(match slot(i, id, PATH)? {
Value::String(s) => Some(s.to_rust_string()),
_ => None,
})
}
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
if let Value::String(s) = &value {
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
+9 -3
View File
@@ -200,8 +200,8 @@ struct Reading {
ancestors: Vec<ObjId>,
path: Vec<Step>,
function: Rc<str>,
/// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object
/// that has [`crate::HOST_REF_KEY`] is refused.
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
/// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused.
hosted: bool,
}
@@ -272,6 +272,12 @@ impl Interp {
if r.ancestors.len() >= r.limits.depth {
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
}
if r.hosted
&& let Some(path) = crate::file_classes::file_path(self, id)?
{
self.charge_reading(r, path.len().saturating_add(16))?;
return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))]));
}
let shape = match &self.object(id)?.class {
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
@@ -338,7 +344,7 @@ impl Interp {
self.use_fuel()?;
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
let name = String::from_utf16_lossy(&k);
if r.hosted && name == crate::HOST_REF_KEY {
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) {
return Err(self.data_error(r, ErrorType::Type, "is not plain data"));
}
r.path.push(Step::Name(k));
+13
View File
@@ -131,6 +131,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data {
Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))])
}
/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host
/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused.
pub const FILE_REF_KEY: &str = "\u{0}fileRef";
/// The path of the `File` that `d`, an argument of a host class's member, stands for.
pub fn file_ref_path(d: &Data) -> Option<&str> {
let Data::Object(items) = d else { return None };
match items.as_slice() {
[(k, Data::String(path))] if k == FILE_REF_KEY => Some(path),
_ => None,
}
}
/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made.
pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
let Data::Object(items) = d else { return None };
+1 -1
View File
@@ -138,7 +138,7 @@ pub use ast::{
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts};
pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, host_ref, host_ref_parts};
pub use lexer::{Goal, Lexer};
pub use number::to_string as number_to_string;
pub use realm::{
+11 -1
View File
@@ -290,6 +290,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// `(` after a name: a call.
fn call(&mut self, line: Option<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['exportVariables'](f)`: a document method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(name) = h1.filter(|s| s.kind == T::Str)
&& catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str())
{
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
return;
}
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
let n = callee.text;
if is(h1, ".") {
@@ -310,7 +320,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.acc.feature(FeatureId::FileDialog, line);
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
self.acc.feature(FeatureId::FileRead, line);
} else if file && catalog::FILE_WRITES.contains(&n) {
} else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) {
self.acc.feature(FeatureId::FileWrite, line);
self.acc.outside(OutsideId::FilesWritten, line, None);
} else if n == catalog::EXECUTE {
+3
View File
@@ -76,6 +76,9 @@ pub(crate) const REFLECT: &str = "reflect";
// The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"];
// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"];
// Application methods that page doesn't list, named in public forum posts:
// https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand,
// doScript, loadAction, unloadAction) and
+23
View File
@@ -530,6 +530,29 @@ fn the_scripts_own_platform_names_are_not_the_platforms() {
assert_eq!(r.outside.iter().map(|o| o.id).collect::<Vec<_>>(), ["filesWritten"]);
}
/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one.
#[test]
fn export_variables_writes_a_file() {
let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n");
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3][..])]);
}
/// `exportVariables` called with its name as a string literal in brackets writes the file too;
/// reading the method without calling it does not.
#[test]
fn export_variables_in_brackets_writes_a_file() {
let r = report(concat!(
"var f = new File(p);\n",
"app.activeDocument['importVariables'](f);\n",
"app.activeDocument[\"exportVariables\"](f);\n",
"var d = app.activeDocument; d['exportVariables'] (f);\n",
"var n = d['exportVariables'];\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
}
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
/// them and setting them on another object does not.
#[test]
+2 -2
View File
@@ -6,6 +6,7 @@ use craft::ui::buttons::{Button, IconButton};
use craft::ui::canvas::CanvasSpace;
use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang};
use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::display::Text;
use craft::ui::menu::PanelRow;
use craft::ui::popover::Popover;
use craft::ui::primitives::IconSpec;
@@ -465,8 +466,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac
if *cmd == TASK_BAR_FIDELITY {
// The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped.
if let Some(v) = offer.fidelity {
// PLAN: assumed `freehand::fidelity_field` draws no label of its own
ui.label(*label);
Text::new(*label).show(ui);
if let Some(x) = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth").filter(|x| *x != v) {
run = Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}})));
}
+107 -8
View File
@@ -44,8 +44,12 @@ struct Open {
preview: LivePreview,
/// Set Role Swatch: the role the Swatch row was last filled for.
filled_for: Option<String>,
/// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle.
doc: Option<u64>,
/// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle, and its revert count
/// then.
doc: Option<(u64, u64)>,
/// The document checked for File > Revert, with its revert count when the dialog opened: `doc`, or the active
/// document for a dialog that previews.
reverts_of: Option<(u64, u64)>,
/// Names this dialog's own open among reopenings of the same command, for its OK and Cancel.
token: Arc<()>,
}
@@ -72,7 +76,9 @@ impl Setting {
/// whose objects the dialog edits).
pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map<String, Value>) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
if let Some(old) = app.command_dialog.open.take() {
if let Some(old) = app.command_dialog.open.take()
&& !reverted(app, &old)
{
old.preview.cancel(app);
}
let fixed = match params.remove("__params") {
@@ -80,9 +86,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
_ => Map::new(),
};
let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64());
let doc = params.remove("__doc").and_then(|v| v.as_u64());
let doc = params.remove("__doc").and_then(|v| v.as_u64()).map(|uid| {
let reverts = app.session.documents().iter().find(|st| st.uid == uid).map_or(0, |st| st.reverts);
(uid, reverts)
});
params.retain(|k, _| !k.starts_with("__"));
let previews = previews(command, &params);
let reverts_of = doc.or_else(|| app.session.active().filter(|_| previews).map(|st| (st.uid, st.reverts)));
let setting = Setting::of(app);
let fields = form::fields_of(&command_params(command, &params, setting), &params);
let token = Arc::new(());
@@ -111,6 +121,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
preview: LivePreview::default(),
filled_for: None,
doc,
reverts_of,
token,
});
Ok(Value::Null)
@@ -161,7 +172,7 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) {
}
});
}
if open.previews {
if open.previews && !reverted(app, open) {
let value = call(&open.command, &open.fixed, open.linked, json);
// The preview reports a refusal in the status bar itself.
let _ = open.preview.run(app, previewing, &open.label, &open.command, &value);
@@ -170,10 +181,15 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) {
/// OK: runs the command on the dialog's values (keeping a preview as the one undo step) and closes the dialog; an
/// error keeps it open with the reason under its rows. A dialog opened on one document's objects (`__doc`, its uid)
/// closes as Cancel does and runs nothing once another document is the active one.
/// closes as Cancel does and runs nothing once another document is the active one. That dialog, and a dialog that
/// previews, stays open and runs nothing once File > Revert replaced the content of the document it opened on.
fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> Result<Value, String> {
let open = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)).ok_or("the dialog is gone")?;
if open.doc.is_some() && open.doc != app.session.active().map(|st| st.uid) {
if reverted(app, &open) {
app.command_dialog.open = Some(open);
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
if open.doc.is_some_and(|(uid, _)| app.session.active().is_none_or(|st| st.uid != uid)) {
open.preview.cancel(app);
return Ok(Value::Null);
}
@@ -197,11 +213,20 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) ->
/// Cancel: rolls back the preview of the dialog `token` names.
fn cancel(app: &mut VectorcraftApp, token: &Arc<()>) {
if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)) {
if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token))
&& !reverted(app, &open)
{
open.preview.cancel(app);
}
}
/// Whether the active document is the one the dialog opened on (`__doc`, or the active one for a dialog that
/// previews), with its content replaced by File > Revert since: a preview shown before belonged to the content
/// thrown away.
fn reverted(app: &VectorcraftApp, open: &Open) -> bool {
open.reverts_of.is_some_and(|(uid, reverts)| app.session.active().is_some_and(|st| st.uid == uid && st.reverts != reverts))
}
/// The rows of `command`'s dialog: one per value it opens with that the command takes, in `order(command)` first and
/// the rest by name, Area Type Options' Text Flow last.
fn command_params(command: &str, opening: &Map<String, Value>, setting: Setting) -> Vec<Param> {
@@ -800,6 +825,46 @@ mod tests {
assert_eq!(cols(&app), 2, "one Undo takes the whole change back");
}
/// Once File > Revert replaced the document's content, Grid Repeat Options neither previews its values on the
/// restored repeat nor applies them on OK, which stays open with the reason; a dialog opened after the revert
/// applies its values.
#[test]
fn grid_repeat_options_refuse_values_from_before_file_revert() {
let (mut app, id) = prepared("object.repeat.options");
let dir = vectorcraft_testkit::TempDir::new("grid-repeat-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
crate::menus::invoke(&mut app, "object.repeat.options", json!({}));
set(&mut app, "preview", json!(true));
set(&mut app, "cols", json!(3));
assert_eq!(cols(&app), 3);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(cols(&app), 2, "the restored repeat");
set(&mut app, "cols", json!(4));
assert_eq!(cols(&app), 2, "no preview on the restored repeat");
assert!(!app.session.in_interaction());
let undo = app.session.active().unwrap().history.undo.len();
let dialog = id_of(&app);
answer_ok(&mut app);
assert_eq!(cols(&app), 2, "OK leaves the restored repeat as it was");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(
app.dialogs().unwrap().with(|h| h.held_state(dialog)),
Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted")
));
answer_cancel(&mut app);
assert_eq!(cols(&app), 2, "Cancel rolls nothing back on the restored repeat");
crate::menus::invoke(&mut app, "object.repeat.options", json!({}));
set(&mut app, "preview", json!(true));
set(&mut app, "cols", json!(5));
answer_ok(&mut app);
assert_eq!(cols(&app), 5, "a dialog opened after the revert applies its values");
}
/// Radial and Mirror Repeat Options have no Preview (their public pages list none): their fields apply on OK
/// only.
#[test]
@@ -990,6 +1055,40 @@ mod tests {
assert_eq!(fold_angle(&mut app, a), Some(90.0), "the first document's line is left as it was");
}
/// Set Fold Angle…'s OK changes nothing once File > Revert replaced the document's content, and the dialog stays
/// open with the reason: the line it opened on is gone, even when the restored file has a line with its id.
#[test]
fn set_fold_angle_s_ok_refuses_the_lines_file_revert_restored() {
let (mut app, a, _) = fold_lines();
let dir = vectorcraft_testkit::TempDir::new("fold-angle-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
pump(&mut app);
set(&mut app, "angle", json!(30.0));
app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let id = id_of(&app);
answer_ok(&mut app);
assert_eq!(fold_angle(&mut app, a), Some(90.0), "the restored line keeps its role's angle");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(
app.dialogs().unwrap().with(|h| h.held_state(id)),
Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted")
));
answer_cancel(&mut app);
crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
pump(&mut app);
set(&mut app, "angle", json!(30.0));
answer_ok(&mut app);
assert_eq!(fold_angle(&mut app, a), Some(30.0), "a dialog opened after the revert sets the angle");
}
/// Set Fold Angle…'s Angle row takes -180° to 180°, the range the command takes, and shows every place the angle
/// it opens on has.
#[test]
+21 -7
View File
@@ -10,7 +10,7 @@
//! choice and those that fail to relink go back to that dialog; opened from the Links panel's Find
//! in Folder… (`ui.findLinksInFolder`), they stay as they are.
//!
//! Fields: `document` (the document's uid), `missing` (`[{name, path, ids}]`), `modified` (the ids
//! Fields: `document` (the document's uid), `reverts` (its revert count when the dialog opened), `missing` (`[{name, path, ids}]`), `modified` (the ids
//! of the images whose file was modified, offered for update afterwards), `notes` (from
//! `missingLinks`: the open's notes, shown with the line about the modified files), `back` (the
//! files left without a choice and those that fail to relink go back to dialog `missingLinks`), `state`
@@ -282,10 +282,19 @@ impl FindLinksDialog {
/// The fields of a Find Linked Files dialog for the `missing` files of the active document.
fn dialog(app: &VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>, back: bool) -> Result<Fields, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
let (uid, reverts) = app.session.active().map(|d| (d.uid, d.reverts)).ok_or("no document open")?;
let picks = vec![Value::Null; missing.len()];
let fields =
json!({ "document": uid, "missing": missing, "modified": modified, "back": back, "state": "", "picks": picks, "touched": [], "copy": false });
let fields = json!({
"document": uid,
"reverts": reverts,
"missing": missing,
"modified": modified,
"back": back,
"state": "",
"picks": picks,
"touched": [],
"copy": false,
});
match fields {
Value::Object(fields) => Ok(fields),
_ => Err("the dialog has no fields".into()),
@@ -312,10 +321,11 @@ pub(super) fn from_missing_links(
) -> Result<(), String> {
let mut find = dialog(app, missing.clone(), modified.clone(), true)?;
let document = find["document"].as_u64().ok_or("no document open")?;
let reverts = find["reverts"].as_u64().ok_or("no document open")?;
find.insert("notes".into(), json!(notes));
start_search(app, &mut find, folder)?;
open(app, find)?;
app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true });
app.link_asks = Some(LinkAsk { document, reverts, missing, modified, notes, back: true });
Ok(())
}
@@ -384,13 +394,17 @@ fn is_image(app: &VectorcraftApp, id: &Value) -> bool {
st.and_then(|st| st.doc.stored_node(vectorcraft_doc::NodeId(id))).is_some_and(|(n, _)| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)))
}
/// Make the dialog's document the active one: it may be another tab's.
/// Make the dialog's document the active one: it may be another tab's. A document whose content File > Revert
/// replaced since the dialog opened is refused: the rows' ids named objects of the content thrown away.
fn activate(app: &mut VectorcraftApp, d: &Fields) -> Result<(), String> {
let uid = d.get("document").and_then(Value::as_u64);
let index = app.session.documents().iter().position(|doc| Some(doc.uid) == uid).ok_or("that document is no longer open")?;
if d.get("reverts").and_then(Value::as_u64) != app.session.documents().get(index).map(|doc| doc.reverts) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
if app.session.active().map(|st| st.uid) == uid {
return Ok(());
}
let index = app.session.documents().iter().position(|doc| Some(doc.uid) == uid).ok_or("that document is no longer open")?;
app.run("document.activate", json!({ "index": index })).map(|_| ())
}
+29 -2
View File
@@ -69,7 +69,8 @@ enum Target {
/// The paint target and selected stop or point shown when the popover opened.
#[derive(Clone, PartialEq, Eq)]
struct TargetKey {
document: u64,
/// The document's uid and revert count: File > Revert keeps the uid and replaces the content.
document: (u64, u64),
objects: Vec<NodeId>,
item: Option<usize>,
fill: bool,
@@ -87,7 +88,7 @@ impl TargetKey {
Target::Point(_, _, index) => (true, *index),
};
Some(Self {
document: doc.uid,
document: (doc.uid, doc.reverts),
objects: doc.selection.objects.clone(),
item: app.session.appearance_item(),
fill,
@@ -891,6 +892,32 @@ mod tests {
assert_eq!(stops(&app)[1].opacity, 0.25);
}
#[test]
fn the_popover_discards_a_pending_edit_after_file_revert() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("gradient-stop-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let art = app.session.doc().unwrap().selection.objects[0];
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [art.0]})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let before = app.session.doc().unwrap().doc.clone();
confirm(&mut app);
assert_eq!(app.session.doc().unwrap().doc, before, "OK must leave the restored gradient as it is");
assert!(!is_open(&app));
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
confirm(&mut app);
assert_eq!(stops(&app)[1].opacity, 0.25);
}
#[test]
fn the_popover_does_not_send_live_edits_to_another_stop() {
let mut app = app();
+48 -4
View File
@@ -109,6 +109,8 @@ impl<W: Copy> Asked<W> {
pub(crate) struct LinkAsk {
/// The document that owns the linked-file IDs.
pub(crate) document: u64,
/// That document's revert count when it was asked: File > Revert keeps the uid and replaces the content.
pub(crate) reverts: u64,
/// The missing files still asked about (`[{name, path, ids}]`), the next one first.
pub(crate) missing: Vec<Value>,
/// The ids of the images whose file was modified.
@@ -355,8 +357,8 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec<String>, Ve
/// Opens the dialog about the first of `missing`, keeping what the questions after it need
/// ([`LinkAsk`]). A window that isn't up has nothing to show a question in.
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>, notes: &[String]) {
let Some(document) = app.session.active().map(|st| st.uid) else { return };
open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false });
let Some((document, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return };
open_ask(app, LinkAsk { document, reverts, missing, modified, notes: notes.to_vec(), back: false });
}
fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) {
@@ -451,7 +453,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
}
return;
}
let LinkAsk { document, missing, modified, notes, .. } = ask;
// The ids asked about named objects of the content File > Revert threw away.
if app.session.active().is_some_and(|st| st.reverts != ask.reverts) {
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
return;
}
let LinkAsk { document, reverts, missing, modified, notes, .. } = ask;
let done = match answer {
MissingLinksAnswer::FindInFolder(folder) => {
super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None)
@@ -463,7 +470,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(None) => {}
Err(e) => {
app.status(e);
open_ask(app, LinkAsk { document, missing, modified, notes, back: false });
open_ask(app, LinkAsk { document, reverts, missing, modified, notes, back: false });
}
}
}
@@ -678,6 +685,43 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
/// After File > Revert, Replace leaves the restored document's links as they are: the ids it asked about named
/// objects of the content thrown away.
#[test]
fn a_missing_file_replacement_is_refused_after_file_revert() {
let (mut app, dir, _) = opened_without_links("revert-replace");
let replacement = dir.join("replacement.png");
std::fs::write(&replacement, png([0, 0, 200])).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement.to_string_lossy()))], true);
assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 2, "the restored links stay as they are");
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
assert!(!drive::is_open::<MissingLinksDialog>(&app));
let _ = std::fs::remove_dir_all(dir);
}
/// After File > Revert, Find Linked Files opened from Find in Folder… relinks nothing in the restored document.
#[test]
fn find_linked_files_relinks_nothing_after_file_revert() {
use crate::dialogs::find_links::FindLinksDialog;
let (mut app, dir, _) = opened_without_links("revert-find");
drive::answer::<MissingLinksDialog>(&mut app, &[("searchFolder", json!(dir.to_string_lossy()))], true);
assert!(drive::is_open::<FindLinksDialog>(&app));
let replacement = dir.join("replacement.png");
std::fs::write(&replacement, png([0, 0, 200])).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let picks = json!([replacement.to_string_lossy(), replacement.to_string_lossy()]);
drive::answer::<FindLinksDialog>(&mut app, &[("picks", picks)], true);
assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 2, "the restored links stay as they are");
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
let _ = std::fs::remove_dir_all(dir);
}
/// Replace relinks the first file and asks about the next; Ignore keeps its preview.
#[test]
fn opening_without_linked_files_asks_to_replace_or_ignore_each() {
+5 -7
View File
@@ -8,6 +8,7 @@ use std::sync::{Arc, RwLock};
use craft::behavior::{DisplayOrder, ItemSource, SelectionChange};
use craft::theme::Srgba;
use craft::ui::buttons::Button;
use craft::ui::choice::Swatch;
use craft::ui::contract::Entry;
use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked};
use craft::ui::layout_components::{Row, Stack};
@@ -684,15 +685,12 @@ pub(super) fn set_light_value(fields: &mut DialogFields, key: &str, value: Value
/// The light's colour: a swatch that asks the host's picker; the answer arrives in `__lightPick`.
fn light_color_row() -> Param {
Param::custom("lightColor", tl!("Color"), |ui, fields, cx| {
let hex = fields.text("lightColor").unwrap_or("#ffffff").to_owned();
let color = Srgba::from_hex(&hex).unwrap_or(Srgba::rgb(1.0, 1.0, 1.0));
// The row's body may run more than once in a pass: the picker opens after it.
let mut ask = false;
let row = Row::new().show(ui, |ui, _| ask = pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color"))));
if ask {
let color = fields.text("lightColor").and_then(Srgba::from_hex).unwrap_or(Srgba::rgb(1.0, 1.0, 1.0));
let swatch = Swatch::new(tl!("Color"), color).tooltip(tl!("Color")).show(ui);
if swatch.clicked {
cx.pick_color("__lightPick", color);
}
row.output
swatch.response
})
.opens_with("#ffffff")
}
@@ -546,3 +546,30 @@ fn lighting_presets_cancel_restores_an_existing_custom_light_rig() {
h.cancel();
assert_eq!(doc(&h), before);
}
/// The color well named Color, with the color it shows.
fn color_well(h: &ThreeD) -> Option<String> {
use craft::ui::contract::Role;
let tree = h.fixture.tree();
let well = h.fixture.by_role(Role::COLOR_WELL).into_iter().find(|t| tree.name_of(t.node) == Some("Color"));
well.and_then(|t| tree.value_of(t.node).map(str::to_owned))
}
/// The light color of 3D and Materials and the custom shading color of 3D (Classic) show as color wells with the
/// stored color.
#[test]
fn the_light_color_and_the_custom_shading_color_are_color_wells() {
let mut h = drawn(SQUARE, REVOLVE);
h.set("__page", json!("lighting"));
h.set("lightColor", json!("#ff8040"));
assert_eq!(color_well(&h).as_deref(), Some("#ff8040"), "the light color is a well that shows the light's color");
h.cancel();
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
h.set("__page", json!("lighting"));
h.set("surface", json!("plastic"));
h.set("shadingColor", json!("custom"));
h.set("shadingCustom", json!("#336699"));
assert_eq!(color_well(&h).as_deref(), Some("#336699"), "the custom shading color is a well that shows the color");
h.cancel();
}
+35 -2
View File
@@ -36,6 +36,8 @@ pub(crate) const OPTION_TOOLS: [&str; 4] = ["rectangularGrid", "polarGrid", "arc
const SIZE_KINDS: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"];
const CLICK_DOCUMENT: &str = "__clickDocument";
/// The clicked document's revert count: File > Revert keeps its uid and replaces the content clicked on.
const CLICK_REVERTS: &str = "__clickReverts";
const CLICK_ALT: &str = "__clickAlt";
/// Where a shape tool was clicked: the dialog's shape is drawn there, and with `alt` held a box shape
@@ -92,13 +94,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option<Click>) {
}
// Keep the placement with the draft whose fields OK receives.
if let Some(click) = click {
let Some(document) = app.session.active().map(|doc| doc.uid) else {
let Some((document, reverts)) = app.session.active().map(|doc| (doc.uid, doc.reverts)) else {
app.status(tl!("Open a document before drawing a shape").to_string());
return;
};
values.insert("x".into(), json!(click.at.x));
values.insert("y".into(), json!(click.at.y));
values.insert(CLICK_DOCUMENT.into(), json!(document.to_string()));
values.insert(CLICK_REVERTS.into(), json!(reverts.to_string()));
values.insert(CLICK_ALT.into(), json!(click.alt));
}
let ink = (kind == "arc" && click.is_none()).then(|| ArcInk::of(&app.session));
@@ -488,13 +491,16 @@ fn confirm(app: &mut VectorcraftApp, kind: &str, fields: &DialogFields) -> Resul
};
};
let document = document.parse::<u64>().map_err(|_| tl!("The shape click document is missing").to_string())?;
if app.session.active().is_none_or(|doc| doc.uid != document) {
let Some(active) = app.session.active().filter(|doc| doc.uid == document) else {
let reason = if app.session.documents().iter().any(|doc| doc.uid == document) {
tl!("Switch back to the document where you clicked to draw the shape")
} else {
tl!("The document where you clicked to draw the shape has closed")
};
return Err(reason.into());
};
if fields.text(CLICK_REVERTS).and_then(|r| r.parse::<u64>().ok()) != Some(active.reverts) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
let (Some(x), Some(y)) = (fields.number("x"), fields.number("y")) else {
return Err(tl!("The shape click position is missing").into());
@@ -699,6 +705,33 @@ mod tests {
assert!((bounds.width() - 32.0).abs() < 1e-6);
}
#[test]
fn rectangle_click_draws_nothing_after_file_revert() {
let (mut app, mut fx) = shown();
let dir = vectorcraft_testkit::TempDir::new("shape-click-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0}));
set(&app, &fx, "rectangle", "width", json!(32.0)).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
press_ok(&mut app, &mut fx, "rectangle");
assert_eq!(drawn(&app), 0, "OK must not draw on the restored drawing");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(matches!(
app.dialogs().unwrap().with(|h| h.held_state(dialog_id("rectangle"))),
Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted")
));
cancel(&mut app, &mut fx, "rectangle");
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0}));
press_ok(&mut app, &mut fx, "rectangle");
assert_eq!(drawn(&app), 1, "a click after the revert draws");
}
#[test]
fn a_reopened_rectangle_uses_the_replacement_click_and_modifier() {
let (mut app, mut fx) = shown();
@@ -12,6 +12,7 @@ use craft::ui::buttons::{Button, IconButton};
use craft::ui::canvas::Canvas;
use craft::ui::canvas::{CanvasSpace, canvas_space};
use craft::ui::canvas_controls::SelectionOutline;
use craft::ui::choice::Swatch;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Picture, Text};
use craft::ui::layout_components::Row;
@@ -195,11 +196,11 @@ fn shading_custom() -> Param {
fields.set(SHADING_CUSTOM, Srgba::from_rgb_array(rgb).to_hex());
}
let color = shading_color(fields);
let button = Button::new(color.to_hex().to_uppercase()).show(ui); // PLAN: assumed a swatch icon via IconSpec::Swatch
if button.clicked() {
let swatch = Swatch::new(tl!("Color"), color).show(ui);
if swatch.clicked {
cx.pick_color(SHADING_CUSTOM, color);
}
button.response
swatch.response
})
.opens_with("#000000")
}
+26
View File
@@ -156,4 +156,30 @@ mod tests {
let doc = &app.session.doc().unwrap().doc;
assert_eq!(doc.layers[0].children().unwrap().len(), 1);
}
#[test]
fn graph_size_does_not_draw_after_file_revert() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let dir = vectorcraft_testkit::TempDir::new("graph-click-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
let click = json!({"x": 40.0, "y": 30.0, "type": "column"});
open_tool_dialog(&mut app, "graph", click.clone());
app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 20, "height": 20})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.doc().unwrap().doc.clone();
confirm_graph(&mut app);
assert_eq!(app.session.doc().unwrap().doc, restored, "OK must not draw on the restored drawing");
assert!(app.any_dialog_open(), "the refused dialog stays open");
let ctx = app.ui_ctx.clone().unwrap();
app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, dialog_id("graph.create")));
super::super::host::pump(&mut app, &ctx);
open_tool_dialog(&mut app, "graph", click);
confirm_graph(&mut app);
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1, "a click after the revert draws");
}
}
+1 -4
View File
@@ -820,10 +820,7 @@ fn footer(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
});
popup(ui, tl!("Swatch Libraries"), out.responses.get(LIBRARIES), |ui| {
ui.set_min_width(200.0);
library_panel::library_menu::<SwatchLibraries>(app, ui);
});
popup(ui, tl!("Swatch Libraries"), out.responses.get(LIBRARIES), |ui| library_panel::library_menu::<SwatchLibraries>(app, ui));
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
@@ -1335,3 +1335,36 @@ fn show_recent_colors_keeps_collecting_and_reads_as_on_unless_false() {
};
assert_eq!((saved(json!(false)), saved(json!(true)), saved(json!("no"))), (false, true, true));
}
/// The footer's Swatch Libraries menu is as wide as the same rows in a swatch library panel's menu: the menu fits its
/// rows.
#[test]
fn the_swatch_libraries_menu_fits_its_rows_like_a_library_panels_menu() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
fn library(app: &mut VectorcraftApp, ui: &mut Ui) {
let panel = library_panel::last_open(&app.ui).expect("a library panel is open").panel();
library_panel::show(app, ui, &panel);
}
let with_library = || {
let mut app = app();
let id = library_panel::tests::menu_library_ids::<SwatchLibraries>(&app).into_iter().next().expect("a swatch library");
app.run("window.swatchLibrary", json!({"library": id})).unwrap();
app
};
// Space on the focused footer button opens its menu; the Swatches panel's footer sits below the harness's room.
let open = |panel: &mut Panel| {
panel.focus("Swatch Libraries Menu");
panel.key(Key::Space, Modifiers::NONE);
panel.frame();
};
let mut footer = Panel::new(with_library(), show);
open(&mut footer);
let footer_menu = footer.rect_role("Swatch Libraries", Role::MENU);
let mut panel = Panel::new(with_library(), library);
open(&mut panel);
let panel_menu = panel.rect_role("Swatch Libraries Menu", Role::MENU);
assert_eq!(footer_menu.width(), panel_menu.width(), "footer menu {footer_menu:?}, library panel menu {panel_menu:?}");
}
+1
View File
@@ -3,6 +3,7 @@
//! is gone, the notes and the reads of the folder.
use std::sync::Arc;
use std::time::Duration;
use craft::host::{AppInfo, Host, ManualJobs, ThreadJobs};
use craft::menu::Node;
+20
View File
@@ -1584,6 +1584,26 @@ fn the_smooth_tool_shows_fidelity_and_tool_options_for_a_path() {
});
}
/// The Smooth tool's "Fidelity:" label is a framework text in the bar: a label node in the access tree, drawn on one
/// line with its baseline on the Fidelity field's.
#[test]
fn the_smooth_tools_fidelity_label_is_one_line_beside_its_field() {
let mut app = app();
let path = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap());
select(&mut app, &[path]);
app.run("tool.select", json!({"tool": "smooth"})).unwrap();
on_canvas(&mut app, |rig| {
let fx = rig.settle();
let tree = fx.tree();
let labels = tree.with_role(craft::ui::contract::Role::LABEL);
assert!(labels.iter().any(|key| tree.name_of(*key) == Some("Fidelity:")), "the label is in the access tree");
let run = |text: &str| fx.texts().iter().find(|t| t.text == text).cloned().unwrap_or_else(|| panic!("no `{text}` painted"));
let (label, value) = (run("Fidelity:"), run("2.50 px"));
assert!(label.rect.height() < 2.0 * value.rect.height(), "the label is one line: {:?}", label.rect);
assert!((label.baseline - value.baseline).abs() <= 1.0, "the label sits on the field's baseline: {label:?} {value:?}");
});
}
/// After a switch to another document and back, the task bar shows the actions for the active
/// document's selection: an open path's Join in the first, a rectangle's Shape Properties in the second.
#[test]
+2 -1
View File
@@ -848,7 +848,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the
other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new
documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
documents, each document's selection and its page items, and each document's variables, data sets and variable
libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
runs a script in a named engine whose globals last between runs,
File › Scripts lists the scripts of the Scripts folder, and
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
+54 -8
View File
@@ -2653,9 +2653,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256
characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
have), `filesOpened` (files opened in other apps), `network`,
object; a document's `exportVariables` counts too; the same objects left out are not counted for the File-only
functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`,
which a Folder object does not have), `filesOpened` (files opened in other apps), `network`,
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
@@ -2870,7 +2870,8 @@ other files through `$`:
changed document. A value that changes nothing runs no command, and a change to another document leaves the active
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that
deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws
`Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
@@ -2894,6 +2895,29 @@ other files through `$`:
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
themselves, such as a path's fill, are not defined yet and read as `undefined`.
- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and
`exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables`
(https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets`
(https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/) have `length`, `parent`, `[i]`, `index(key)`,
`getByName(name)`, `add()` and `removeAll()`. A `Variable` (https://ai-scripting.docsforadobe.dev/jsobjref/Variable/)
has `name`, `kind`, `pageItems` and `remove()`, and a `Dataset` (https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/)
has `name`, `display()`, `update()` and `remove()`. Every page item has `visibilityVariable`, and a `TextFrame`,
`PlacedItem`, `RasterItem` or `GraphItem` has `contentVariable` as well
(https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each change runs a `variable.*` or `dataset.*` command:
`variables.add()` runs `variable.define` of a text variable named `Variable1`, `Variable2` and so on (the first free
name), `dataSets.add()` runs `dataset.capture`, `display()` and assigning `activeDataset` run `dataset.select`,
`update()` runs `dataset.update {name}`, assigning `visibilityVariable` or `contentVariable` runs
`variable.setBinding`, `importVariables` runs `variable.loadLibrary` and `exportVariables` runs
`variable.saveLibrary`. `kind` is one of the strings of the enumeration `VariableKind`
(`"VariableKind.TEXTUAL"`, `VISIBILITY`, `IMAGE`, `GRAPH` and `Unknown`); `Unknown` cannot be assigned.
VectorCraft's own rules: a `Variable` or `Dataset` names its variable or data set by name. A rename made through
it keeps it working; once the name leaves the document any other way (a delete, an undo, a rename or kind change by
another command, or an import that replaces the data sets), it throws `Stale variable` or `Stale data set`, also
after the name comes back. A run gives out at most 10,000 of each. `visibilityVariable` and `contentVariable` give
the first bound variable of their kind in the order the variables were defined, or `null`, and `null` unbinds.
`importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or
write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs
no command.
- `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/)
with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each
`Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page
@@ -4749,7 +4773,13 @@ already walks Image Trace. Short agent entry points:
defined in. Names compare without regard to case; by object, unbound variables come first and variables bound
to several objects last, and ties go by name. Another `by` value, or a `descending` that is not true or false,
is an error. The sort is panel state, not saved and not an undo step; `variable.list` lists the variables in
that order and reports it as `sort: {by, descending}`.
that order and reports it as `sort: {by, descending}`. `variable.setBinding {id, slot: visibility|content,
variable?}` binds one object to `variable` for one slot and unbinds the object's other variables of that slot's
kind: `visibility` takes a visibility variable, and `content` the kind that drives the object (text for type, image
for a linked image, graph for a graph). Without `variable`, or with null, it unbinds them all. A variable of
another kind, an object of no content kind, and an embedded image for an image variable are errors, and nothing
changes. One undo step, and none when the object already has just that binding → `{id, slot, variable,
unbound}`.
- Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also
renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`,
`dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` /
@@ -5532,8 +5562,9 @@ locked; `skipped` counts those objects.
A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes
or no, or a graph value longer than 262,144 bytes.
`dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the
data set holds. A variable whose objects report no value, because they are deleted or, for a text, image or graph
`dataset.update {all?, name?}` writes what the bound objects hold now into the active data set, for each variable that
the data set holds. With `name`, it writes into that data set instead and the active data set stays as it is; a
`name` that is not a string, or names no data set, is an error. A variable whose objects report no value, because they are deleted or, for a text, image or graph
variable, locked or inside a locked layer or group, or for any variable on a locked artboard, keeps the data set's value. With `all: true`
it also adds every other variable that the
objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it
@@ -9849,6 +9880,20 @@ with the defaults.
them.
- `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns
`{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open.
- `file.newProfiles.applyDefaults {name}` (Use Profile Defaults, VectorCraft's own command) gives the active document
the default fill and stroke and the default font of another profile. The document's Default Graphic Style takes the
fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] takes the profile's
attributes, with the profile's colors converted to the document's color mode and the swatches, patterns, symbols and
brushes they paint with added. A composite font of the profile that those attributes name replaces the document's
composite font of that name, as `type.compositeFonts.import` does. A category without a file gives the shipped
defaults. The change is one undo step, which also puts back the fill and stroke new art took, and none is recorded
when applying the profile leaves the document unchanged. As
`graphicStyle.redefine` and `charStyle.redefine` do, objects still linked to the Default Graphic Style and type in
[Normal Character Style] take the new definitions and keep their overrides. New art then starts as `paint.default`
gives it, and new type in the profile's font. It returns `{name, changed, warnings?}`, and an error when the
profile's file can't be read, its [Normal Character Style] has attributes `charStyle.new` does not take, or the
composite font it names can't join the document's composite fonts (`type.compositeFonts.set` checks them the same
way).
- Under automation roots, `file.newProfiles.edit` needs write and read access to the profile's file and
`file.newProfiles.reset` needs write access. An error names the file whole only inside the read roots, and
otherwise by its file name.
@@ -14997,7 +15042,8 @@ options existed keep their old look (appearance applied after the distortion).
An envelope opened from a `.ai` can have margins, written to native files as `boundsMargin` and reported by
`object.envelope.info` when they are not zero: `[top, bottom, left, right]`, as shares of the content's height and
width. While `distortAppearance` is on, the content maps from its geometric bounds grown by the margins, and while it
width. When the content's height or width is shorter than 1e-6 pt (zero included), as on a straight line, the margins
along that side are shares of the other side. While `distortAppearance` is on, the content maps from its geometric bounds grown by the margins, and while it
is off, the content maps from its geometric bounds. Leaving Edit Contents measures the margins again when the content's
strokes reach differently than when Edit Contents began, and always for an envelope whose file opened in Edit Contents.
New envelopes have no margins, and no command sets them.
+5 -1
View File
@@ -57,6 +57,8 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe
Character-style edits keep manual leading overrides when Dynamic Text's Block cannot fit the frame. When Block can fit the frame, its generated leading follows the edited style. A regression in `crates/engine/src/cmd/typecmd/block_tests.rs` covers a frame whose inset leaves no room.
Script page-item and layer objects become stale after `file.revert`, including when the file reuses node IDs. The document object and its collections remain available and return new objects for the reverted content. `crates/engine/src/tests/script_dom.rs` covers reads, assignments, and relative targets for moves and copies.
Script appearance and geometry setters reject objects on locked artboards. Assigning the current opacity remains allowed when it changes no graph styling. Position, size and stacking-order setters also reject objects excluded by selection filtering, including locked guide paths. `crates/engine/src/tests/script_dom.rs` covers refused edits, unchanged documents and undo history, and editing a guide after unlocking it.
Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
@@ -978,6 +980,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both.
- **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`.
- **Default fill and stroke from a profile:** when a New Document profile's Default Graphic Style is redefined (for example no fill and a 0.25 pt red stroke), documents from that profile start new art with that style's fills, strokes and effects, and Default Fill and Stroke (`paint.default`, D) gives the defaults and the selection the same look in those documents (VectorCraft's own rule). Test: `tests::newdoc::a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke`.
- **Another profile's defaults in an open document:** Use Profile Defaults (`file.newProfiles.applyDefaults`, VectorCraft's own command) gives the active document the Default Graphic Style and [Normal Character Style] of another New Document profile, with the swatches they paint with, in one undo step, so new art and new type start with that profile's fill, stroke and font. Test: `tests::newdoc::an_open_document_takes_another_profiles_default_fill_stroke_and_font`.
- **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy).
- **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies).
- **Repeated brush names in a file:** a document or brush library file whose brushes repeat a name opens with the first brush of that name as stored and each later one numbered, as "Name 2", "Name 3" and so on, skipping names the file already has. Strokes that name the brush keep drawing the first one, and `brush.list`, `brush.options`, `brush.delete`, `brush.library` and the Brushes panel then reach each brush by its own name. This numbering is VectorCraft's own rule. Tests in `crates/brush/src/tests.rs`, `tests/brushsym.rs` and `tests/brushlib.rs` cover it.
@@ -1090,6 +1093,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- 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: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
@@ -2403,7 +2407,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`).
A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`).
A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`).
In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws; where they don't, even with the drawn art of every live envelope put back, and are used all the same, trusted, with the objects that differ coming in as the page's art, or opened alone, it stays live where, in the pixels it and its drawn art ink (drawn together without the rest of the layers), the layers with it differ from the page in no more than its own check allows and the envelopes that stay differ there in no more than half of what the page check allows, and nothing above it clips, masks or moves it); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; after those tries (and before a grid moved onto its drawn art), it is also tried mapped from the box of what it paints, where that is another box, as users' files map some such type: its glyph outlines with their fills and strokes baked as the envelope bakes them, so geometry effects on them count (a stroke a Transform effect moves paints where it is moved to), each measured by its visual bounds (exact for miter joins, a tip counting where the miter limit keeps it, and for round joins; an upper bound for bevel joins, miters the limit cuts, width profiles and square-capped dashes), and a contour of zero length, which paints nothing, left out; effects on the type object itself are left out, as VectorCraft applies them after the envelope bends the type. The drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art.
In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box. Contents with no width or no height, such as a single stroked straight line, follow the same rule, and the margins across the line are shares of its length. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws; where they don't, even with the drawn art of every live envelope put back, and are used all the same, trusted, with the objects that differ coming in as the page's art, or opened alone, it stays live where, in the pixels it and its drawn art ink (drawn together without the rest of the layers), the layers with it differ from the page in no more than its own check allows and the envelopes that stay differ there in no more than half of what the page check allows, and nothing above it clips, masks or moves it); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; after those tries (and before a grid moved onto its drawn art), it is also tried mapped from the box of what it paints, where that is another box, as users' files map some such type: its glyph outlines with their fills and strokes baked as the envelope bakes them, so geometry effects on them count (a stroke a Transform effect moves paints where it is moved to), each measured by its visual bounds (exact for miter joins, a tip counting where the miter limit keeps it, and for round joins; an upper bound for bevel joins, miters the limit cuts, width profiles and square-capped dashes), and a contour of zero length, which paints nothing, left out; effects on the type object itself are left out, as VectorCraft applies them after the envelope bends the type. The drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art.
In a `.ai` opened from its editing data, an envelope in another envelope's contents opens as a live envelope inside the live outer one, with Edit Contents on or off at either level, also where its record lies straight in the outer envelope's `AIDeformArtKey` block with no group around it; each level edits its own contents without removing its distortion, as the help page describes for one envelope (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html). Each envelope is compared with its own drawn art: an inner one that doesn't match keeps its drawn art as the outer envelope's contents, and an outer one that doesn't match keeps its own drawn art. An inner record left without its `XP` stops waiting when the outer dictionary ends, and an envelope in an opacity mask's art reads as part of the mask (`an_envelope_in_an_envelope_s_contents_opens_live_inside_it` and the tests after it in `crates/eps/src/import/ai/tests.rs`).
In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`).
In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`).