Scripts: review fixes for the document defaults and the object model

- appearance.setNewArt is listed among the commands a plug-in may call, so
  every_command_is_reviewed passes.
- appearance.setNewArt refuses `tint` on a pattern that has no swatch entry,
  and its help and docs/mcp.md say an omitted `weight` keeps the stored weight.
- The dash checks of appearance.setNewArt, strokeDashes and
  defaultStrokeDashes share one helper.
- defaultStrokeWidth, defaultStrokeMiterLimit and defaultStrokeDashOffset
  compare exactly, so a slightly different value reaches new art.
- An RGB default in a CMYK document is compared in the document's color mode,
  and a color read back from a path or a default (a Gray too small for its
  value to name) assigns back without a command.
- addDocument starts from the profile's built-in first preset even when a
  saved preset has the same name.
- A saved preset's rows are read as at most 1000.
- The page item and path lists are kept for each open document, the
  selection list stops at its limit, the typename of a removed PathPoint and
  of a stale PathPoints or PathItems throws, and an item edit whose
  selection cannot be restored is undone with it.
- A path's subpath starts are counted once and kept while its points keep
  their layout, so reading or setting each of its points in turn no longer
  walks every subpath for each point.
- A run that ended while waiting for a growth answer is checked against its
  allowance again before it is kept.
- docs/mcp.md says which file limits apply to reading a profile's file.
This commit is contained in:
dotCooCoo committed 2026-11-25 15:07:36 -08:00
1 parent a61c4d87e8
commit f5afa0b84a
14 files changed
+425 -89

No files matched your search

+41 -7
View File
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set New Art Appearance",
[],
None,
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. A stroke painted on new art without one gets a 1 pt weight unless `weight` is given. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
always,
set_new_art
),
@@ -75,6 +75,38 @@ const MAX_DASHES: usize = 64;
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
/// What [`dash_fault`] finds wrong with a list of dash and gap lengths.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum DashFault {
/// More than [`MAX_DASHES`] lengths.
TooMany,
/// A length that is not a number from 0 to [`MAX_DASH_LENGTH`].
OutOfRange,
/// Lengths that are all 0.
AllZero,
}
/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the
/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good.
/// An empty list (a solid line) is good.
pub(crate) fn dash_fault(lengths: &[f64]) -> Option<DashFault> {
if lengths.len() > MAX_DASHES {
Some(DashFault::TooMany)
} else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) {
Some(DashFault::OutOfRange)
} else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) {
Some(DashFault::AllZero)
} else {
None
}
}
/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of
/// the document in front.
pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color {
super::paint::new_color(s, &json!({}), c)
}
/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before
/// anything changes.
fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
@@ -84,7 +116,8 @@ fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
if !v.is_object() {
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
}
if v.get("tint").is_some() && v.get("swatch").is_none() {
let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some());
if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) {
return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`")));
}
let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?;
@@ -113,11 +146,12 @@ fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => {}
Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
Some(Value::Array(a)) => {
if !a.iter().all(|v| v.as_f64().is_some_and(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(&n))) {
return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}")));
}
if !a.is_empty() && a.iter().all(|v| v.as_f64() == Some(0.0)) {
return Err(bad(C, "dash needs a length that is not 0"));
let lengths: Option<Vec<f64>> = a.iter().map(Value::as_f64).collect();
match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) {
None => {}
Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))),
Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")),
}
}
Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))),
+9 -2
View File
@@ -171,8 +171,9 @@ pub struct DocSettings {
pub layout: ArtboardLayout,
/// Columns of a grid layout.
pub columns: u32,
/// Rows of a grid by column, in place of `columns` when more than 0.
#[serde(skip_serializing_if = "is_zero")]
/// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a
/// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`).
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
pub rows: u32,
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
/// outside that range is read as the nearer end).
@@ -594,6 +595,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
}
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
/// place) stays 0.
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
@@ -103,6 +103,7 @@ pub(super) const ALLOWED: &[&str] = &[
"appearance.removeItem",
"appearance.setActiveItem",
"appearance.setItem",
"appearance.setNewArt",
"appearance.showAllHidden",
"appearance.targetContents",
"appearance.transfer",
+68 -20
View File
@@ -96,12 +96,15 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Option<ItemList>>,
/// The last list of a document's paths ([`paths`]), kept while that document is unchanged.
paths: RefCell<Option<ItemList>>,
items: RefCell<Vec<ItemList>>,
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
paths: RefCell<Vec<ItemList>>,
/// A path and its subpaths with the point changes the run has made to it and not written yet
/// ([`flush`]).
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
/// The index of the first point of each subpath of the path whose points the run read last,
/// and what they were counted from ([`paths`]).
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
/// How many times the points the run read of each path went stale, by document uid and path id
/// ([`paths`]).
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
@@ -148,6 +151,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
const KEPT_LISTS: usize = 8;
/// The list kept in `lists` for the document `st`, while that document is unchanged.
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
}
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
let mut l = lists.borrow_mut();
l.retain(|(uid, ..)| *uid != st.uid);
if l.len() >= KEPT_LISTS {
l.remove(0);
}
l.push((st.uid, st.doc.clone(), ids.clone()));
}
type Answer = std::result::Result<Data, HostError>;
/// A member function: the run's host and the call's arguments, `this` first.
@@ -396,13 +417,11 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
}
/// The ids of a document's page items in paint order ([`State`] keeps the last list).
/// The ids of a document's page items in paint order ([`State`] keeps the last list of each
/// document).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some((uid, doc, ids)) = &*h.dom.items.borrow()
&& *uid == st.uid
&& Arc::ptr_eq(doc, &st.doc)
{
return ids.clone();
if let Some(ids) = kept_list(&h.dom.items, st) {
return ids;
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes {
@@ -420,7 +439,7 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
let mut ids = Vec::new();
walk(&st.doc.layers, &mut ids);
let ids = Rc::new(ids);
*h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone()));
keep_list(&h.dom.items, st, &ids);
ids
}
@@ -639,12 +658,13 @@ fn on_doc<T>(
Ok(v)
}
/// Runs `id` with `params` on the item's document, its selection kept. The points the run read of
/// the item's paths stay valid through the change ([`paths::see_all_points`]).
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
/// paths stay valid through the change ([`paths::see_all_points`]).
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| command(h, id, params));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
h.dom.editing.set(kept);
r
}
@@ -934,6 +954,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
})
}
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
/// built-in preset with `presetSettings` over them.
const BUILT_IN_SETTINGS: &[&str] = &[
"width",
"height",
"units",
"artboards",
"artboardLayout",
"bleed",
"backgroundContents",
"colorMode",
"rasterEffectsPpi",
"previewMode",
"alignNewObjectsToPixelGrid",
];
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
/// place of the profile's.
@@ -977,15 +1013,26 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
}
// The document starts from the first preset of the profile's category (Print: Letter).
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
if let Some(m) = mode {
p.entry("colorMode").or_insert_with(|| json!(m));
}
// The document starts from the first built-in preset of the profile's category (Print:
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
// does not stand in for it. Settings `file.new` refuses are left for it to report.
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
if let Some(first) = first {
p.insert("preset".into(), json!(first.name));
if let Ok(full) = first.with_params(&Value::Object(p.clone()), "file.new")
&& let Value::Object(settings) = full.to_json()
{
for key in BUILT_IN_SETTINGS {
if let Some(v) = settings.get(*key) {
p.insert((*key).into(), v.clone());
}
}
}
}
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
// A profile whose file could not be read throws, and the document `file.new` made with the
// defaults is put back, with the Recent sizes as they were.
atomically(h, |h| {
@@ -1193,7 +1240,8 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
fn selection_of(h: &Host, uid: u64) -> Answer {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let ids: Vec<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
let ids: Vec<NodeId> =
st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).take(MAX_LISTED + 1).collect();
if ids.is_empty() {
return Ok(Data::Null);
}
+18
View File
@@ -90,6 +90,24 @@ pub(super) fn of_paint(paint: &Paint) -> Data {
}
}
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
/// stand for an ink amount that no Gray value names exactly).
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
match (assigned, now) {
(None, Paint::None) => true,
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
_ => false,
}
}
/// Whether the color object `d` has the class and every component of `shown`.
fn shows(d: &Data, shown: &Data) -> bool {
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
}
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
+4 -8
View File
@@ -55,11 +55,7 @@ fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
let color = colors::assigned(arg(a, 1), what)?;
let now = top_paint(&new_art(h, a)?, fill);
let same = match (&color, &now) {
(None, Paint::None) => true,
(Some(c), Paint::Solid { color, swatch: None, .. }) => c == color,
_ => false,
};
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
let paint = match color {
Some(c) => json!({"color": colors::param(&c)}),
None => json!({"none": true}),
@@ -109,7 +105,7 @@ fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
}
this_doc(h, a)?;
let now = h.session.borrow().paint.stroke_width;
set(h, (now - w).abs() < 1e-9, json!({"weight": w}))
set(h, now == w, json!({"weight": w}))
}
fn default_cap(h: &Host, a: &[Data]) -> Answer {
@@ -152,7 +148,7 @@ fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
}
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
set(h, (now - v).abs() < 1e-9, json!({"miterLimit": v}))
set(h, now == v, json!({"miterLimit": v}))
}
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
@@ -183,7 +179,7 @@ fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
}
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
set(h, (now - v).abs() < 1e-9, json!({"dashOffset": v}))
set(h, now == v, json!({"dashOffset": v}))
}
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
+140 -38
View File
@@ -69,7 +69,7 @@ use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc,
float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get,
point_method, point_property, property, this_doc, typename_of, whole, with_doc,
point_method, point_property, property, this_doc, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
@@ -140,9 +140,63 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low])
}
/// How many points a path with the subpaths `subs` has.
fn point_count(subs: &[SubPath]) -> usize {
subs.iter().map(|sp| sp.anchors.len()).sum()
/// The index of the first point of each subpath of `subs`, followed by the number of points.
fn starts(subs: &[SubPath]) -> Vec<usize> {
let mut out = Vec::with_capacity(subs.len() + 1);
let mut n = 0;
for sp in subs {
out.push(n);
n += sp.anchors.len();
}
out.push(n);
out
}
/// The subpath and the place in it of point `i`, given the [`starts`] of a path's subpaths.
fn locate_at(starts: &[usize], i: usize) -> Option<(usize, usize)> {
if i >= *starts.last()? {
return None;
}
let s = starts.partition_point(|first| *first <= i).checked_sub(1)?;
Some((s, i - starts.get(s)?))
}
/// What the [`starts`] that [`super::State`] keeps were counted from: a path's node as its document
/// holds it, by document uid, or the waiting point changes of a path ([`edit_points`]).
pub(super) enum Counted {
Node(u64, Arc<crate::doc::Node>),
Waiting(Item),
}
/// The [`starts`] of the path of `item`, its waiting point changes included. They are kept while
/// the path's node is the same one, or until the waiting changes add or remove points.
fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize>>, HostError> {
let waiting = matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item));
if waiting {
if let Some((Counted::Waiting(k), kept)) = &*h.dom.point_starts.borrow()
&& same_path(*k, item)
{
return Ok(kept.clone());
}
let counted = Rc::new(read_points(h, item, starts)?);
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone()));
return Ok(counted);
}
let node = with_doc(h, item.doc, |_, st| node_arc(&st.doc, item.id).cloned()).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if let Some((Counted::Node(uid, kept_node), kept)) = &*h.dom.point_starts.borrow()
&& *uid == item.doc.uid
&& Arc::ptr_eq(kept_node, &node)
{
return Ok(kept.clone());
}
let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths));
*h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone()));
Ok(counted)
}
/// How many points the path of `item` has, its waiting point changes included ([`point_starts`]).
fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostError> {
Ok(point_starts(h, item)?.last().copied().unwrap_or(0))
}
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
@@ -180,6 +234,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
/// that is, is written at once, so that its points read as the grid snaps them.
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
forget_waiting_starts(h);
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
&& same_path(*waiting, item)
{
@@ -205,6 +260,33 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
Ok(r)
}
/// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can
/// make wrong.
fn forget_waiting_starts(h: &super::Host) {
let mut kept = h.dom.point_starts.borrow_mut();
if matches!(&*kept, Some((Counted::Waiting(_), _))) {
*kept = None;
}
}
/// Changes the anchor at index `i` of the path of `item` with `f` ([`edit_points`]). The change
/// adds and removes no points, so the [`starts`] of the path stay kept.
fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> {
let counted = point_starts(h, item)?;
let at = locate_at(&counted, i);
edit_points(h, item, |subs| {
if let Some((s, j)) = at
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
{
f(an);
}
})?;
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted));
}
Ok(())
}
/// Gives the path of `item` the subpaths `subs` ([`edit_points`]).
fn write_path(h: &super::Host, item: Item, subs: Vec<SubPath>) -> std::result::Result<(), HostError> {
edit_points(h, item, |s| *s = subs)
@@ -214,6 +296,7 @@ fn write_path(h: &super::Host, item: Item, subs: Vec<SubPath>) -> std::result::R
/// the path has those points already.
pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) };
forget_waiting_starts(h);
let same = {
let s = h.session.borrow();
let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id));
@@ -278,16 +361,13 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
/// The ids of a document's paths, in the order of its page items.
fn path_items(h: &super::Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some((uid, doc, ids)) = &*h.dom.paths.borrow()
&& *uid == st.uid
&& std::sync::Arc::ptr_eq(doc, &st.doc)
{
return ids.clone();
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
return ids;
}
let all = super::page_items(h, st);
let ids: Rc<Vec<NodeId>> =
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
*h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone()));
super::keep_list(&h.dom.paths, st, &ids);
ids
}
@@ -300,6 +380,12 @@ fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError>
doc_of(h, arg(a, 0), "PathItems")
}
/// `typename` of the paths of a document that is still open.
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
items_doc(h, a)?;
Ok(Data::String("PathItems".into()))
}
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64)))
@@ -818,12 +904,7 @@ fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer {
let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?;
let (item, look) = this_look(h, a)?;
let now = if fill { &look.fill } else { &look.stroke };
let same = match (&color, now) {
(None, Paint::None) => true,
(Some(c), Paint::Solid { color, swatch: None, .. }) => c == color,
_ => false,
};
if !same {
if !colors::unchanged(arg(a, 1), color, now, |c| c) {
set_paint(h, item, fill, color)?;
}
Ok(Data::Undefined)
@@ -928,13 +1009,13 @@ pub(super) fn dash_lengths(d: &Data, what: &str) -> std::result::Result<Vec<f64>
Data::Array(list) => list.iter().map(|d| number(d, "each dash length")).collect::<std::result::Result<_, _>>()?,
_ => return Err(HostError::Type(format!("{what} must be an array of lengths"))),
};
if lengths.iter().any(|l| !(0.0..=MAX_STROKE_WIDTH * 1000.0).contains(l)) {
return Err(HostError::Range("each dash length must be from 0 to 1000000 points".into()));
use crate::cmd::newart::DashFault;
match crate::cmd::newart::dash_fault(&lengths) {
None => Ok(lengths),
Some(DashFault::TooMany) => Err(HostError::Range(format!("{what} takes at most {MAX_DASHES} lengths"))),
Some(DashFault::OutOfRange) => Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())),
Some(DashFault::AllZero) => Err(HostError::Range(format!("{what} needs a length that is not 0"))),
}
if !lengths.is_empty() && lengths.iter().all(|l| *l == 0.0) {
return Err(HostError::Range(format!("{what} needs a length that is not 0")));
}
Ok(lengths)
}
/// `strokeDashes = [lengths]`, as [`dash_lengths`] takes them.
@@ -1129,9 +1210,15 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostErr
path_at(h, *run, *uid, *high, *low)
}
/// `typename` of the points of a path that is still in its document.
fn points_typename(h: &super::Host, a: &[Data]) -> Answer {
points_path(h, a)?;
Ok(Data::String("PathPoints".into()))
}
fn points_length(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
read_points(h, item, |subs| num(float(point_count(subs) as u64)))
Ok(num(float(points_of(h, item)? as u64)))
}
fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
@@ -1255,7 +1342,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
let n = read_points(h, item, point_count)?;
let n = points_of(h, item)?;
Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined })
}
@@ -1273,18 +1360,33 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer {
fn points_add(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])));
let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?;
let mut counted = point_starts(h, item)?;
let n = counted.last().copied().unwrap_or(0);
if n >= MAX_POINTS {
return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points")));
}
let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?;
let p = match last {
Some(p) => p,
None => origin?,
};
// The kept starts are dropped, so that `counted` is their only copy and grows in place.
*h.dom.point_starts.borrow_mut() = None;
edit_points(h, item, |subs| match subs.last_mut() {
Some(sp) => sp.anchors.push(Anchor::corner(p)),
None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)),
})?;
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
let grown = Rc::make_mut(&mut counted);
if grown.len() > 1 {
if let Some(total) = grown.last_mut() {
*total += 1;
}
} else {
*grown = vec![0, 1];
}
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted));
}
Ok(point_ref(h, item, n))
}
@@ -1307,8 +1409,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It
return Err(HostError::Error(STALE_POINT.into()));
}
let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?;
let n = read_points(h, item, point_count)?;
if i >= n {
if i >= points_of(h, item)? {
return Err(HostError::Error(STALE_POINT.into()));
}
Ok((item, i))
@@ -1319,8 +1420,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords,
let (item, i) = this_point(h, a)?;
let c = h.dom.coords.get();
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
let at = locate_at(&point_starts(h, item)?, i);
read_points(h, item, |subs| {
let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j)));
let anchor = at.and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j)));
anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into()))
})?
}
@@ -1329,13 +1431,7 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords,
/// coordinates (for a point property) or the value itself.
fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer {
let (item, i) = this_point(h, a)?;
edit_points(h, item, |subs| {
if let Some((s, j)) = locate(subs, i)
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
{
f(an);
}
})?;
edit_anchor(h, item, i, f)?;
Ok(Data::Undefined)
}
@@ -1392,6 +1488,12 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer {
Ok(path_ref(h, item))
}
/// `typename` of a point that is still on its path.
fn pt_typename(h: &super::Host, a: &[Data]) -> Answer {
this_point(h, a)?;
Ok(Data::String("PathPoint".into()))
}
/// Whether a group or compound path that holds the path `id` is selected, which selects the path
/// as a whole whatever the path's own selection is.
fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool {
@@ -1573,7 +1675,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
"PathItems",
None,
named(vec![
("typename", typename_of("PathItems")),
("typename", get(l, items_typename)),
("length", get(l, items_length)),
("parent", get(l, items_parent)),
("index", method(l, items_index)),
@@ -1592,7 +1694,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
"PathPoints",
None,
named(vec![
("typename", typename_of("PathPoints")),
("typename", point_get(l, points_typename)),
("length", point_get(l, points_length)),
("parent", point_get(l, points_parent)),
("index", point_method(l, points_index)),
@@ -1605,7 +1707,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
"PathPoint",
None,
named(vec![
("typename", typename_of("PathPoint")),
("typename", point_get(l, pt_typename)),
("parent", point_get(l, pt_parent)),
("anchor", point_property(l, pt_anchor, pt_set_anchor)),
("leftDirection", point_property(l, pt_left, pt_set_left)),
+11
View File
@@ -2227,6 +2227,17 @@ impl Session {
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
// One more allowance may still leave the growth past it: the person is asked again
// while they may be, and past that the run ends unkept.
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
return Some(self.script_failed(job, &e));
}
if job.host.waiting.get() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
return None;
}
return Some(self.script_ended(job));
}
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
+15
View File
@@ -1,6 +1,8 @@
//! The new-art template (M3.65): Stroke panel options and graphic styles chosen with nothing
//! selected, New Art Has Basic Appearance and `paint.default`.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, Dash, LineCap, Node};
@@ -396,6 +398,19 @@ fn set_new_art_refuses_bad_values_with_nothing_changed() {
}
}
#[test]
fn set_new_art_refuses_a_tint_on_a_pattern_without_a_swatch_entry() {
let mut s = session();
let id = rect(&mut s, 20.0);
let name = run(&mut s, "object.pattern.make", json!({"ids": [id.0], "edit": false}))["name"].as_str().unwrap().to_string();
run(&mut s, "select.none", json!({}));
Arc::make_mut(&mut s.doc_mut().unwrap().doc).remove_swatch(&name);
let before = s.paint.clone();
assert!(s.execute("appearance.setNewArt", &json!({"fill": {"swatch": name, "tint": 50}})).is_err(), "accepted a tint on {name}");
assert_eq!(s.paint, before);
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"fill": {"swatch": name}})), json!({"changed": true}));
}
#[test]
fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
let mut s = session();
+8
View File
@@ -1037,3 +1037,11 @@ fn the_new_layer_takes_an_id_no_profile_art_has() {
// Ids given out later skip the symbol's art too.
assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next);
}
#[test]
fn a_saved_presets_rows_are_read_within_the_artboard_limit() {
let rows = |n: u32| serde_json::from_value::<crate::cmd::newdoc::DocSettings>(json!({"rows": n})).unwrap().rows;
assert_eq!(rows(1001), crate::cmd::newdoc::MAX_ARTBOARDS, "file.new takes the listed rows again");
assert_eq!(rows(0), 0, "0 stays: columns in their place");
assert_eq!(rows(12), 12, "more rows than artboards stay");
}
+12 -2
View File
@@ -805,6 +805,16 @@ fn note_is_the_attributes_note() {
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
}
#[test]
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
let mut s = Session::new();
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
}
#[test]
fn document_preset_applies_only_its_given_fields() {
let mut s = Session::new();
@@ -1019,8 +1029,8 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
let (mut s, _, _) = doc();
let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let p = path.to_string_lossy().replace('\\', "\\\\");
let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));");
let (p, other) = (json!(path.to_string_lossy()), json!(format!("{}.other", path.to_string_lossy())));
let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));");
let out = log(&mut s, &query);
assert_eq!(out, vec![json!(true), json!(false)]);
// Read roots that leave out the document's file: the same path does not count.
+30 -5
View File
@@ -38,15 +38,14 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node {
fn a_wider_default_stroke_goes_to_the_next_path_drawn() {
let (mut s, picked) = doc();
let (look, steps) = (node(&s, picked).appearance, undo_steps(&s));
let r = run(&mut s, "var d = app.activeDocument; var w = d.defaultStrokeWidth; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth > w);")
.unwrap();
assert_eq!(r["log"], json!([true]));
let wider = s.paint.stroke_width + 1.0;
let r = run(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth);").unwrap();
assert_eq!(r["log"][0].as_f64(), Some(wider));
assert_eq!(undo_steps(&s), steps, "a default alone is no undo step");
assert_eq!(node(&s, picked).appearance, look, "the selected path kept its stroke");
let wider = s.new_art().stroke().unwrap().width;
assert_eq!(s.new_art().stroke().unwrap().width, wider);
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(200, 100, 50, 50); vc.log(p.strokeWidth);");
assert_eq!(out.iter().map(Value::as_f64).collect::<Vec<_>>(), vec![Some(wider)]);
assert!(wider > 1.0);
}
#[test]
@@ -121,6 +120,32 @@ fn default_stroke_options_read_back_and_a_same_value_runs_no_command() {
assert_eq!(log(&mut s, "var d = app.activeDocument; d.defaultStrokeDashes = {}; vc.log(d.defaultStrokeDashes.length);"), vec![json!(0)]);
}
#[test]
fn a_slightly_different_number_reaches_new_art() {
let (mut s, _) = doc();
log(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 1; d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2];");
log(
&mut s,
"var d = app.activeDocument; d.defaultStrokeWidth = 1.0000000005; d.defaultStrokeMiterLimit = 7.0000000005;\
d.defaultStrokeDashOffset = 0.0000000005;",
);
let st = s.new_art().stroke().unwrap().clone();
assert_eq!(st.width, 1.000_000_000_5);
assert_eq!(st.miter_limit, 7.000_000_000_5);
assert_eq!(st.dash.map(|d| d.offset), Some(0.000_000_000_5));
}
#[test]
fn an_rgb_default_in_a_cmyk_document_runs_no_command_the_second_time() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
let set = "var d = app.activeDocument, c = new RGBColor(); c.red = 200; c.green = 40; c.blue = 90; d.defaultFillColor = c;";
let first = run(&mut s, set).unwrap();
assert_ne!(first["slowestCommands"], json!([]), "the first assignment changes new art");
let again = run(&mut s, set).unwrap();
assert_eq!(again["slowestCommands"], json!([]), "the same RGB value runs no command");
}
#[test]
fn scale_factor_is_one_and_read_only() {
let (mut s, _) = doc();
+63 -3
View File
@@ -282,6 +282,25 @@ fn points_read_before_a_removal_or_replacement_go_stale() {
json!("Stale path point")
]
);
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[1], pt = p.pathPoints[0]; vc.log(pt.typename); pt.remove();\
try { vc.log(pt.typename); } catch (e) { vc.log(e.message); }",
);
assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point")]);
// The points of a removed path, and collections kept from an earlier run, throw on typename as on
// their other members.
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[0], pp = p.pathPoints; vc.log([pp.typename, app.activeDocument.pathItems.typename]); p.remove();\
var a = '', b = ''; try { pp.length; } catch (e) { a = e.message; } try { pp.typename; } catch (e) { b = e.message; } vc.log(a !== '' && a === b);",
);
assert_eq!(out, vec![json!(["PathPoints", "PathItems"]), json!(true)]);
run(&mut s, "#targetengine keep\nvar items = app.activeDocument.pathItems, pts = items[0].pathPoints;").unwrap();
for (member, message) in [("items.typename", "Stale document"), ("pts.typename", "Stale")] {
let e = failure(&mut s, &format!("#targetengine keep\n{member};"));
assert!(e.contains(message), "{member}: {e}");
}
}
#[test]
@@ -468,6 +487,14 @@ fn a_color_read_from_a_path_assigns_back_unchanged() {
var g = new GrayColor(); g.gray = 25; p.strokeColor = g; vc.log([p.fillColor.red, p.fillColor.green, p.strokeColor.gray]);",
);
assert_eq!(out, vec![json!([200, 0.5, 25])], "whole and short values read as they were given");
// A Gray ink amount too small for its Gray value to name: assigning the color read back changes nothing.
let (mut s, a, _) = doc();
let k = f32::from_bits(0x1f00_0000);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(a).unwrap().appearance.set_fill(Paint::solid(Color::Gray { k }));
let steps = undo_steps(&s);
let r = run(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").unwrap();
assert_eq!(paint_of(&s, a, true), Paint::solid(Color::Gray { k }));
assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])));
}
#[test]
@@ -869,16 +896,49 @@ fn area_sign_follows_direction() {
fn many_path_edits_are_one_undo_step() {
let (mut s, a, b) = doc();
let steps = undo_steps(&s);
let look = |s: &Session| [a, b].map(|id| (node(s, id).appearance, node(s, id).path_data().map(|pd| pd.subpaths.clone())));
let before = look(&s);
log(
&mut s,
"var p = app.activeDocument.pathItems, c = new RGBColor(); c.green = 200;\
for (var i = 0; i < p.length; i++) { p[i].fillColor = c; p[i].strokeWidth = 3; p[i].pathPoints[0].anchor = [0, 0]; }",
);
assert_eq!(undo_steps(&s), steps + 1);
assert_ne!(look(&s), before);
s.execute("edit.undo", &json!({})).unwrap();
for id in [a, b] {
assert!((node(&s, id).appearance.stroke_width() - 1.0).abs() < 1e-9);
}
assert_eq!(look(&s), before, "one Undo puts back the fill, the stroke width and the anchor of both paths");
}
#[test]
fn point_indexes_follow_subpaths_through_edits_adds_and_removals() {
let (mut s, a, _) = doc();
let source = format!(
"function A(x) {{ return {{x: x, y: 5, in: [x, 5], out: [x, 5], smooth: false}}; }}\
function xs() {{ var out = []; for (var i = 0; i < pp.length; i++) out.push(pp[i].anchor[0]); return out; }}\
var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\
vc.run('path.setAnchors', {{id: {id}, subpaths: [{{anchors: [A(0), A(1)], closed: false}}, {{anchors: [A(10), A(11), A(12)], closed: false}},\
{{anchors: [A(20)], closed: false}}]}});\
vc.log(xs()); pp[3].anchor = [50, pp[3].anchor[1]]; vc.log([pp[3].anchor[0], pp[4].anchor[0], pp[5].anchor[0]]);\
pp.add(); vc.log([pp.length, pp[6].anchor[0]]);\
pp[0].remove(); vc.log(xs()); pp[0].remove(); vc.log(xs()); pp[4].anchor = [70, 0]; vc.log(xs());",
id = a.0
);
let out = log(&mut s, &source);
let out: Vec<Value> = out.iter().map(rounded).collect();
assert_eq!(
out,
vec![
json!([0, 1, 10, 11, 12, 20]),
json!([50, 12, 20]),
json!([7, 20]),
json!([1, 10, 50, 12, 20, 20]),
json!([10, 50, 12, 20, 20]),
json!([10, 50, 12, 20, 70]),
]
);
let subs = node(&s, a).path_data().unwrap().subpaths.clone();
let xs: Vec<Vec<f64>> = subs.iter().map(|sp| sp.anchors.iter().map(|an| (an.p.x * 1000.0).round() / 1000.0).collect()).collect();
assert_eq!(xs, vec![vec![10.0, 50.0, 12.0], vec![20.0, 70.0]]);
}
fn selected_anchors(s: &Session, id: NodeId) -> Option<Vec<(usize, usize)>> {
+5 -4
View File
@@ -9147,8 +9147,9 @@ resets it.
`appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference.
`appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?,
strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its
art, the active proxy and Recent Colors as they were. `fill` and `stroke` take a paint as `paint.setFill` does; a
stroke painted on new art without one gets a 1 pt weight unless `weight` is given. Every value is checked before
art, the active proxy and Recent Colors as they were. `fill` and `stroke` take a paint as `paint.setFill` does, and
`tint` only with a global or spot `swatch`. Without `weight` the stored stroke weight stays; a stroke painted on new
art without one gets 1 pt only when that stored weight is 0. Every value is checked before
anything changes, and any change while New Art Has Basic Appearance is off and an object is selected is an error. It
returns `{changed}`, false when the next object would look the same.
@@ -9462,8 +9463,8 @@ runs, as `document.open` reads its file when it runs. A file larger than 64 MiB
When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the
folder (whether or not the file exists), the document starts with the defaults and
`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and
a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's
file. The
a script's `app.documents.addDocument` throws it. Reading the profile's file is not limited to the script's folder (the
`File` and `Folder` rule in [Script engines](#script-engines)), but the request's automation read roots still apply. The
reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's
file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used
adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the