Merge main into fix/remove-all-empty-compound-mask

This commit is contained in:
dotCooCoo committed 2026-12-03 01:54:59 -08:00
commit 895b542409
38 files changed
+2704 -329

No files matched your search

+125 -36
View File
@@ -54,7 +54,7 @@
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of
//! the paths in the object; a clipping group counts its clipping path only.
//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
//! in view-number order, and none without one. View objects keep their window's identity when
//! windows are renumbered. The screen mode is the app's:
@@ -99,9 +99,12 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod clipboard;
mod colors;
mod defaults;
mod images;
pub(super) mod layers;
mod matrix;
mod paths;
pub mod preferences;
mod print;
mod save_open;
@@ -111,6 +114,9 @@ mod tracing;
mod transform;
mod variables;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
/// What [`after_command`] compares with, taken before each command a script runs
@@ -124,13 +130,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
variables::after_command(h, before);
}
mod colors;
mod defaults;
mod paths;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -218,9 +217,6 @@ pub(super) struct State {
/// Each path whose points the run read, as the run last saw it, by document uid and then path
/// id ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
/// The path whose points the object model is writing with `path.setAnchors`, the only path
/// that command changes ([`paths`]).
one_path: Cell<Option<Item>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
@@ -292,11 +288,13 @@ impl State {
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
/// and no change to the document's saved state, and the growth its commands were charged is not
/// counted.
/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not
/// put them back.
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
if h.dom.saving.get() {
return f(h);
}
flush(h)?;
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
let styles = text::styles::mark(h);
let mark = h.growth_mark();
@@ -459,7 +457,7 @@ fn point_method(link: &Link, f: Member) -> HostMember {
pub(super) type Described = (String, HostMember, MemberInfo);
/// A property's or a method's result's type for `reflect`.
fn typed(data_type: &str) -> MemberInfo {
pub(super) fn typed(data_type: &str) -> MemberInfo {
MemberInfo { data_type: data_type.into(), ..MemberInfo::default() }
}
@@ -470,7 +468,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, layer, page item, path point or text range `this` is still there.
/// the check that a document, layer, page item, path point, text range or `GroupItems` collection
/// `this` is still there.
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
/// `reflect` leaves it out.
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
@@ -495,6 +494,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"TextRange" => {
text::check_range(&h, arg(&a, 0))?;
}
"GroupItems" => {
layers::check_groups(&h, arg(&a, 0))?;
}
_ => {}
}
Err(HostError::Error(message.clone()))
@@ -2333,13 +2335,17 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
return layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = top_items(&st.doc);
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
// A clipping layer emptied of its art releases its mask, so art added later is not made its
// clipping path.
let released = masks_cleared_by(&st.doc, &ids);
let tracing = release_makes_tracing(&st.doc, &released, &ids);
(ids, refused, on_locked, released, tracing)
});
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -2349,8 +2355,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if tracing {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
Ok(Data::Undefined)
}
@@ -2638,26 +2647,39 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
bounds(h, a, true)
}
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
/// object with nothing in it.
/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths
/// in the item.
fn item_control(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, true)?;
let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds));
match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) {
Some(r) => Ok(f.bounds(h.dom.coords.get(), r)),
None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
}
// An object with nothing in it reads zeros, as its other bounds do.
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
// Each object and anchor the walk visits is charged, so reading a large group's bounds again
// and again counts against the run.
let mut steps = 0u64;
let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps)));
h.charge_call(steps)?;
Ok(f.bounds(h.dom.coords.get(), r))
}
/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown
/// paths in its children (a clip group's from its clipping path).
fn handle_bounds(n: &crate::doc::Node) -> Option<Rect> {
match &n.kind {
NodeKind::Path { path, .. } => path.control_bounds(),
NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)),
_ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))),
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
/// path's.
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
*steps += 1;
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return r;
}
for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) {
*steps += 1;
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
}
let children = n.children().map_or(&[][..], Vec::as_slice);
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
for c in children {
r = take_in_handles(c, r, steps);
}
r
}
fn item_position(h: &Host, a: &[Data]) -> Answer {
@@ -2830,11 +2852,55 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id]));
// A clip group named as a tracing, released with an image left first, would become one too.
if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
// A compound path whose last path this is stays, empty, as it does after `move`.
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
let params = json!({"ids": [item.id.0], "keepEmpty": true});
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, &params)));
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping
/// path releases its mask, so the object above it does not become the clipping path.
pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter()
.filter_map(|i| {
let p = d.parent_of(*i)?;
let n = d.node(p)?;
(n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p)
})
.collect()
}
/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups
/// an ordinary group named as a tracing with an image first in it, which would make it a tracing.
pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool {
if released.is_empty() {
return false;
}
let removed: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
released.iter().filter_map(|g| d.node(*g)).any(|g| {
matches!(g.kind, NodeKind::Group { .. })
&& g.name.as_deref() == Some(crate::cmd::TRACE_NAME)
&& g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))
})
}
/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`.
pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result<Data, HostError> {
for g in released {
command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?;
}
command(h, "edit.clear", params)
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
@@ -2983,6 +3049,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option<usize>) ->
}
}
/// Whether deleting every object in `removed` together would leave one of their parents, an
/// ordinary group named as a tracing, with an image first in it, which would make it a tracing.
pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool {
let going: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
let mut parents: Vec<NodeId> = removed.iter().filter_map(|i| d.parent_of(*i)).collect();
parents.sort_unstable_by_key(|p| p.0);
parents.dedup();
parents
.into_iter()
.filter(|p| named_as_tracing(d, *p))
.any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))))
}
/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place.
fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
let index = with_doc(h, doc, |_, st| {
@@ -2998,6 +3077,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
}
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
// The clipping path itself, put back where it is, stays the clipping path.
let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0);
let at = match (to.how, to.beside) {
(Placement::Top, _) => count,
(Placement::Bottom, _) => 0,
@@ -3009,11 +3090,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
{
i -= 1;
}
if how == Placement::Above { i + 1 } else { i }
let at = if how == Placement::Above { i + 1 } else { i };
// A place behind a clipping path is refused; an object put into the clip group
// itself goes directly above the clipping path.
if clips && at == 0 && !mask_stays {
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
}
at
}
(_, None) => count,
};
let at = if clips { at.max(1) } else { at };
// Any other place for the clipping path is left to `node.move`, which refuses it.
let stays = mask_stays && at == 0;
let at = if clips && !stays { at.max(1) } else { at };
// The index `node.move` puts the object at: art stays below the ruler guides.
// This is `Node::insert_index` on the parent's children without the object, read in place
// so that no list of them is copied.
@@ -3172,7 +3261,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
pub(super) fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
+61 -16
View File
@@ -12,8 +12,8 @@
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the
//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's
//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems`
//! hold every group or compound path at any depth, in the order of the document's `pageItems`.
//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes
//! a sublayer on top of that layer's contents. The new layer becomes the current one.
@@ -68,6 +68,8 @@ enum Kind {
Compound,
/// Paths (`PathItem`).
Path,
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
Text,
}
impl Kind {
@@ -77,6 +79,7 @@ impl Kind {
Kind::Group => "GroupItems",
Kind::Compound => "CompoundPathItems",
Kind::Path => "PathItems",
Kind::Text => "TextFrames",
}
}
@@ -86,6 +89,7 @@ impl Kind {
Kind::Group => typename(n) == Some("GroupItem"),
Kind::Compound => typename(n) == Some("CompoundPathItem"),
Kind::Path => typename(n) == Some("PathItem"),
Kind::Text => typename(n) == Some("TextFrame"),
}
}
}
@@ -245,7 +249,9 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v}))
// The number the getter reports, or one that stores as the opacity the layer has, leaves the
// layer as it is.
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v}))
}
fn layer_color(h: &Host, a: &[Data]) -> Answer {
@@ -289,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
}
/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is
/// not counted.
/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop
/// lists the layers once. Each read is still charged for the search through the list.
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let parent = st.doc.parent_of(id);
let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len));
h.charge_call(count as u64)?;
let list = layer_list(&st.doc, parent);
let list = layers_listed(h, st, st.doc.parent_of(id))?;
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
@@ -642,6 +646,10 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
if ids.len() > crate::cmd::layer::MAX_ROWS {
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -760,8 +768,17 @@ fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
};
}
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) };
with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
// The text of a number that is not an array index is looked up as a name.
None => with_doc(h, doc, |_, st| {
let ids = art_list(h, st, kind, c)?;
h.charge_call(ids.len() as u64)?;
let name = vectorcraft_js::number_to_string(*n);
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
}),
}
}
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
@@ -778,6 +795,11 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
match arg(a, 1) {
Data::String(_) => art_by_name(h, a, kind),
// A number is a position only. A stale collection throws its stale error first.
Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => {
art_scope(h, arg(a, 0), kind.class())?;
Err(HostError::Error(NOT_FOUND.into()))
}
Data::Number(_) => match art_at(h, a, kind)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
@@ -848,6 +870,10 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
}
@@ -997,6 +1023,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Compound)
}
fn held_text(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Text)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
art_scope(h, d, Kind::Text.class())
}
/// The type objects directly in `container`, topmost first.
pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result<Rc<Vec<NodeId>>> {
art_list(h, st, Kind::Text, Some(container))
}
// ---- GroupItem and CompoundPathItem ----
fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result<Item> {
@@ -1050,8 +1090,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
("pageItems", get(l, held_page_items), listed("PageItems")),
("groupItems", get(l, held_groups), listed("GroupItems")),
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
("textFrames", get(l, held_text), listed("TextFrames")),
]);
m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m
}
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
@@ -1332,9 +1373,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
Ok(text("[Layers]"))
}
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Group.class())?;
check_groups(h, arg(a, 0))?;
Ok(text("[GroupItems]"))
}
/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone.
pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> {
art_scope(h, d, Kind::Group.class()).map(|_| ())
}
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Compound.class())?;
Ok(text("[CompoundPathItems]"))
@@ -1526,17 +1571,17 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("pageItems", get(l, held_page_items), listed("PageItems")),
("groupItems", get(l, held_groups), listed("GroupItems")),
("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")),
("textFrames", get(l, held_text), listed("TextFrames")),
("zOrderPosition", get(l, layer_z_position), typed("number")),
("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")),
("isIsolated", get(l, layer_is_isolated), typed("boolean")),
("move", method(l, layer_move), typed("Layer")),
("move", method(l, layer_move), returns("Layer", &[("relativeObject", "*"), ("insertionLocation", "ElementPlacement")])),
("remove", method(l, layer_remove), returns("undefined", &[])),
("zOrder", method(l, layer_z_order), typed("undefined")),
("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
("toString", method(l, layer_to_string), returns("string", &[])),
]);
layer.extend(
["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"]
.map(|m| later(l, "Layer", m)),
["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)),
);
vec![
class("Layer", None, layer, None),
+225 -131
View File
@@ -17,7 +17,8 @@
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard.
//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a
//! range error when it is assigned.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
@@ -52,9 +53,7 @@
//! throws an error that says it is not available yet on a path inside a compound path, throws
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
//! are locked; assigning the value the path has runs no command.
//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
//! `changeStrokePattern` given as different values throw an error; gradients move with the art,
//! so `changeFillGradients` false throws an error that says it is not available yet.
//! - The transforms are `PageItem`'s, with their rules in [`super::transform`].
use std::rc::Rc;
use std::sync::Arc;
@@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
@@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is
/// hidden or locked, or it is on a locked artboard.
fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option<HostError> {
if !editable(&st.doc, id) {
return Err(cannot_edit(id));
Some(cannot_edit(id))
} else if super::on_locked_artboard(h, st, id) {
Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)))
} else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) {
Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)))
} else {
None
}
if super::on_locked_artboard(h, st, id) {
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
}
/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin.
fn in_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
Ok(())
}
/// The path `d` names, which must still be in its document.
@@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError
path_of(h, arg(a, 0))
}
/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
return Err(HostError::Error(STALE_ITEM.into()));
}
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
path_of(h, &path_ref(h, Item { doc, id }))
}
@@ -149,12 +162,10 @@ fn read_path<T>(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d
})
}
/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count).
fn path_ref(h: &super::Host, item: Item) -> Data {
let s = h.session.borrow();
match s.documents().iter().find(|d| d.uid == item.doc.uid) {
Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)),
None => Data::Null,
}
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
host_ref("PathItem", &handle)
}
/// The index of the first point of each subpath of `subs`, followed by the number of points.
@@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
for (s, sp) in subs.iter().enumerate() {
#[cfg(test)]
tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1));
if i < sp.anchors.len() {
return Some((s, i));
}
@@ -248,7 +261,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
/// locked or is on a locked artboard ([`protected`]), 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> {
@@ -264,10 +277,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
let same = pd.subpaths == subs;
(same, if same { None } else { protected(h, st, item.id) }, aligned)
})?;
if !same {
refused?;
if let Some(e) = refused {
return Err(e);
}
*h.dom.pending.borrow_mut() = Some((item, subs));
if aligned {
flush(h)?;
@@ -325,12 +341,29 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
}
let subpaths: Vec<Value> =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
// Changes made before this one are looked at in full first.
see_all_points(h);
let kept = h.dom.one_path.replace(Some(item));
let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}));
h.dom.one_path.set(kept);
r?;
super::atomically(h, |h| {
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
let selection = &mut st.selection;
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
}
if let Some(segments) = selection.segments.get_mut(&item.id) {
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
if segments.is_empty() {
selection.segments.remove(&item.id);
}
}
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
selection.key_anchor = None;
}
if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id))
&& (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()))
{
selection.remove(item.id);
}
}
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))
})?;
Ok(())
}
@@ -340,26 +373,36 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
}
/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active
/// layer, then puts the drawing mode back.
fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal);
let r = f();
h.session.borrow_mut().draw_mode = kept;
r
/// Runs a path creation command with its layer placement recorded.
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
let mut params = params.clone();
params["onLayer"] = json!(parent.map(|p| p.0));
super::command_value(h, id, &params)
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit ([`refuse_path_edit`]).
/// must be one the user could edit ([`protected`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) {
return Err(e);
}
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
o.insert("objectOnly".into(), json!(true));
}
}
keeping_paint(h, || edit_item(h, item, id, &params))
let result = keeping_paint(h, || edit_item(h, item, id, &params))?;
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
}
Ok(result)
}
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
@@ -503,6 +546,11 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
if h.session.borrow().menu.guides_locked
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
}
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
@@ -522,10 +570,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// The id in the result of a command that made an object, read from the command's own result so
/// that an id above 2^53 stays exact.
fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
}
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
@@ -535,7 +583,8 @@ fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
let made = keeping_paint(h, || {
on_doc(h, doc.uid, true, |h| {
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
if reversed {
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
}
@@ -700,9 +749,10 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
let ap = h.session.borrow().new_art();
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
};
let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
if unpainted {
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?;
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
}
Ok(id)
})
@@ -716,8 +766,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let [high, low] = id_parts(item.id);
Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low]))
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
Ok(host_ref("PathPoints", &handle))
}
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
@@ -728,7 +778,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
let closed = boolean(arg(a, 1), "closed")?;
let item = this_path(h, a)?;
edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
edit_points(h, item, |subs| {
if subs.is_empty() && closed {
subs.push(SubPath::new(Vec::new(), closed));
} else {
subs.iter_mut().for_each(|sp| sp.closed = closed);
}
})?;
Ok(Data::Undefined)
}
@@ -835,8 +891,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
let c = h.dom.coords.get();
let anchors: Vec<Anchor> =
script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
write_path(h, item, subs)?;
cut_points(h, item);
Ok(Data::Undefined)
@@ -924,10 +980,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul
Ok(match linked {
true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}),
true => json!({"swatch": name}),
false => json!({"color": colors::param(color)}),
false => json!({"color": colors::param(color), "keepModel": true}),
})
}
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})),
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})),
Paint::Gradient(g) => {
let mut g = g.clone();
if g.geom.is_some() || g.freeform.is_some() {
@@ -1200,8 +1256,8 @@ pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
Ok(item)
}
@@ -1240,8 +1296,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
}
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
let [high, low] = id_parts(item.id);
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
handle.extend([float(i as u64), float(point_cuts(h, item))]);
host_ref("PathPoint", &handle)
}
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
@@ -1293,7 +1350,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
POINT_LOOKS.with(|n| n.set(n.get() + 1));
let node = {
let s = h.session.borrow();
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned())
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| {
h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone());
node_arc(&st.doc, NodeId(key.1)).cloned()
})
};
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
// stale.
@@ -1316,53 +1376,47 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// change that a later command reverses still makes the points stale. Paths under the object that
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths. While the object model writes one path's points
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
/// Objects on Path group are looked at in its document.
/// at is skipped, as are its paths.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
if seen.values().all(|paths| paths.is_empty()) {
return;
}
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
let one = h.dom.one_path.get();
let seen = h.dom.point_nodes.borrow();
let mut keys = Vec::new();
// The documents that changed since the last look, kept as they are now.
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
// Editing a path in an Objects on Path group can move other paths in the group.
let mut moved = Vec::new();
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
Some(st) => {
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
let d = &st.doc;
let group = d.ancestry(item.id).and_then(|a| {
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
});
if let Some(g) = group {
g.walk(&mut |n: &crate::doc::Node| {
if n.id != item.id && paths.contains_key(&n.id.0) {
moved.push((*uid, n.id.0));
}
});
}
}
docs.insert(*uid, st.doc.clone());
docs.retain(|uid, before| {
let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc);
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
return true;
}
// Editing a path in an Objects on Path group can move the other paths in the group, so
// the outermost such group is looked at in place of the path.
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
Some(item) => {
let group = before
.ancestry(item.id)
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)));
node_arc(before, group.unwrap_or(item.id)).into_iter().collect()
}
None => {
docs.remove(uid);
None => before.layers.iter().collect(),
};
while let Some(node) = todo.pop() {
if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) {
continue;
}
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
keys.push((*uid, node.id.0));
}
if let Some(children) = node.children() {
todo.extend(children);
}
}
match one {
Some(item) if item.doc.uid == *uid => {
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
keys.append(&mut moved);
}
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
if let Some(after) = after {
*before = after.clone();
true
} else {
false
}
}
});
keys
};
let editing = h.dom.editing.get();
@@ -1444,8 +1498,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
/// point of the path removed or replaced since `this` was read.
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
@@ -1482,17 +1536,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul
let p = point(arg(a, 1), what)?;
let (item, _) = this_point(h, a)?;
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
on_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
/// `p`, a point a script gave in document coordinates, when it is on the canvas (within
/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise.
fn on_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
in_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer {
@@ -1560,12 +1604,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[
if held {
return true;
}
if !sel.contains(id) || sel.segments.contains_key(&id) {
if !sel.contains(id) {
return false;
}
match sel.partial(id) {
None => true,
Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)),
Some(picked) => locate(subs, i).is_some_and(|(s, j)| {
picked.contains(&(s, j))
&& !sel
.segments
.get(&id)
.is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j)))
}),
}
}
@@ -1577,12 +1627,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
/// [`super::State`] are written first only when they add or remove points of this path, since
/// the selection names anchors by their place in the document's path.
/// [`super::State`] are written first when they add or remove points of this path or invalidate
/// selected segments.
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
let moved = match &*h.dom.pending.borrow() {
Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?,
Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| {
!same_layout(subs, &pd.subpaths)
|| st
.selection
.segments
.get(&item.id)
.is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count())))
})?,
_ => false,
};
if moved {
@@ -1650,22 +1707,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
let picked: Vec<usize> = read_path(h, item, |st, _, pd| {
let sel = &st.selection;
let held = held_selected(&st.doc, sel, item.id);
if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) {
if !held && !sel.contains(item.id) {
return Vec::new();
}
let mut out = Vec::new();
let mut first = 0;
let segments = sel.segments.get(&item.id);
let ends: std::collections::BTreeSet<_> = segments
.into_iter()
.flatten()
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
.flatten()
.collect();
let partial = sel.partial(item.id).filter(|_| !held);
let mut picked = Vec::new();
let mut offset = 0;
for (s, sp) in pd.subpaths.iter().enumerate() {
let n = sp.anchors.len();
out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j));
first += n;
for j in 0..sp.anchors.len() {
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
picked.push(offset + j);
}
}
offset += sp.anchors.len();
}
out
picked
})?;
h.charge_call(picked.len() as u64)?;
let [high, low] = id_parts(item.id);
let cuts = float(point_cuts(h, item));
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
Ok(Data::Array(points))
}
@@ -1723,10 +1789,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::d
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
// The current layer and the highlighted Layers rows are put back after the selection is set.
let (layer, rows) = with_doc(h, item.doc, |_, st| (st.active_layer, st.highlighted_rows()));
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
super::restore_selection(h, &doc, &sel)?;
super::restore_layer(h, item.doc.uid, layer, &rows)
})?;
}
}
@@ -1815,7 +1884,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
),
("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")),
("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }),
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
@@ -1897,13 +1966,38 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
use crate::Session;
thread_local! {
pub(super) static LOCATE_STEPS: Cell<usize> = const { Cell::new(0) };
}
#[test]
fn selected_points_do_not_rescan_subpaths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128];
s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap();
s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap();
LOCATE_STEPS.with(|steps| steps.set(0));
let out = s
.execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"}))
.unwrap();
assert_eq!(out["log"], json!([2]));
LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get()));
}
#[test]
fn a_made_id_above_two_to_the_53_stays_exact() {
assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7)));
assert!(made_id(&json!({"id": 1.5})).is_err());
assert!(made_id(&json!({})).is_err());
let made = |v: Value| made_id(&(Data::Undefined, v));
assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made(json!({"id": 7})), Ok(NodeId(7)));
assert!(made(json!({"id": 1.5})).is_err());
assert!(made(json!({})).is_err());
}
}
+235 -57
View File
@@ -1,12 +1,16 @@
//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its
//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its
//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and
//! `paragraphAttributes`, and `app.textFonts`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`,
//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden
//! or locked layer or group throws.
//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so
//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves
//! out to the whole character. One item of `characters` is one code point.
@@ -33,6 +37,8 @@
//! value; set on an empty range it changes nothing. A paragraph attribute reads the first
//! paragraph the range touches and sets every one of them. A text range has the members of
//! both its `characterAttributes` and its `paragraphAttributes`.
//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes
//! the paint away. `strokeWeight` is 0 to 1000 points.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
@@ -40,13 +46,14 @@ use std::rc::Rc;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref};
use super::{
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item,
editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property,
returns, text, typed, typename_of, whole, with_doc,
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of,
doc_ref, edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc,
page_items, point, property, returns, text, typed, typename_of, whole, with_doc,
};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -59,6 +66,10 @@ pub const STALE_RANGE: &str = "Stale text range";
/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit
/// is stale.
const MAX_EDITS: usize = 100_000;
/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of
/// the other frames are given up; their text, generations and edits stay, and each frame's tables
/// are made again when it is next read.
const INDEX_BUDGET: usize = 64 << 20;
/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units.
pub(super) struct Index {
@@ -102,6 +113,22 @@ impl Index {
Self { text, chars, bytes, words, paras }
}
/// The text alone, without its offset tables, for a frame whose tables were given up under
/// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read.
fn bare(text: String) -> Self {
Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() }
}
fn is_bare(&self) -> bool {
self.chars.is_empty()
}
/// The bytes the offset tables hold.
fn table_bytes(&self) -> usize {
let pairs = self.words.capacity() + self.paras.capacity();
(self.chars.capacity() + self.bytes.capacity()) * size_of::<usize>() + pairs * size_of::<(usize, usize)>()
}
fn len(&self) -> usize {
self.chars.last().copied().unwrap_or(0)
}
@@ -202,10 +229,32 @@ pub(in crate::script) struct TextState {
made: Cell<u64>,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
/// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]).
table_bytes: Cell<usize>,
/// The styles the run's style objects name.
styles: styles::StyleState,
}
/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within
/// [`INDEX_BUDGET`], giving up the tables of other frames first.
fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) {
let mut total = state.table_bytes.get() + index.table_bytes();
if let Some(l) = frames.get_mut(&key) {
total -= l.index.table_bytes();
l.index = Rc::new(index);
}
for (k, l) in frames.iter_mut() {
if total <= INDEX_BUDGET {
break;
}
if *k != key && !l.index.is_bare() {
total -= l.index.table_bytes();
l.index = Rc::new(Index::bare(l.index.text.clone()));
}
}
state.table_bytes.set(total);
}
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
match &st.doc.node(id)?.kind {
NodeKind::Text(t) => Some(t),
@@ -231,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc<Index
let mut frames = h.dom.text.frames.borrow_mut();
let key = (st.uid, id.0);
let now = Arc::as_ptr(&st.doc);
match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {}
let fresh = match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None,
Some(l) => {
if l.reverts != st.reverts || !same_text(t, &l.index.text) {
let changed = l.reverts != st.reverts || !same_text(t, &l.index.text);
if changed {
l.stamp += 1;
l.floor = l.stamp;
l.edits.clear();
l.index = Rc::new(Index::new(t.plain_text()));
}
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
changed.then(|| t.plain_text())
}
None => {
let l = Log {
doc: Arc::downgrade(&st.doc),
reverts: st.reverts,
index: Rc::new(Index::new(t.plain_text())),
index: Rc::new(Index::bare(String::new())),
stamp: 0,
floor: 0,
edits: VecDeque::new(),
};
frames.insert(key, l);
Some(t.plain_text())
}
};
// Tables given up under the budget are made again from the text the log keeps.
let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone()));
if let Some(text) = fresh {
set_index(&h.dom.text, &mut frames, key, Index::new(text));
}
let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
Ok((l.index.clone(), l.stamp))
@@ -303,6 +359,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc<Index>, usize, usize, u
})
}
/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing
/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a
/// locked artboard.
fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
refuse_protected(h, item, "TextFrame")?;
edit_item(h, item, id, params)
}
/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is
/// hidden or locked, or it is on a locked artboard.
fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> {
let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id)));
if !ok {
return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0)));
}
if on_locked {
return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0)));
}
Ok(())
}
/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`.
/// When the text is not what that edit gives, every earlier range goes stale.
fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
@@ -323,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser
l.floor = l.stamp;
l.edits.clear();
}
l.index = Rc::new(Index::new(now));
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now));
Ok(())
})
}
@@ -453,7 +530,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
return Ok(Data::Undefined);
}
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
record(h, r.item, &index, s, e - s, &insert)?;
Ok(Data::Undefined)
}
@@ -547,6 +624,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option<NodeId>) -> Answer {
/// `null` when the type has nothing to outline and the command removed it.
fn frame_outline(h: &Host, a: &[Data]) -> Answer {
let item = this_frame(h, a)?;
refuse_protected(h, item, "TextFrame")?;
let (_, r) = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
super::command_value(h, "type.createOutlines", &json!({}))
@@ -568,6 +646,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer {
Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))),
Some(true) => {}
}
refuse_protected(h, item, "TextFrame")?;
let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" };
let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?;
new_ref(h, item.doc, result_id(&r).or(Some(item.id)))
@@ -730,35 +809,44 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
let (r, part) = this_part(h, a)?;
let contents = contents_of(arg(a, 1))?;
let (index, s, e, _) = resolve(h, r)?;
let at = if before || matches!(arg(a, 2), Data::Undefined) {
// The place, and whether it is the end of a range, which rounds up to a character boundary.
let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) {
let (items, spans) = part_spans(&index, part, s, e);
let span = |k: usize| match spans {
None => index.char_span(k),
Some(list) => list.get(k).copied(),
};
if before {
items.clone().next().and_then(span).map_or(s, |(x, _)| x)
(items.clone().next().and_then(span).map_or(s, |(x, _)| x), false)
} else {
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
(items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true)
}
} else {
let rel = arg(a, 2);
let target = if handle_of(rel, "TextFrame").is_some() {
whole_span(h, item_of(h, rel)?)?.1
} else if handle_of(rel, "TextRange").is_some() {
span_of(h, rel, &["TextRange"])?
} else {
span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))?
// A range of a removed frame keeps its own error.
span_of(h, rel, &["TextRange"]).map_err(|e| match e {
HostError::Error(m) if m == STALE_RANGE => HostError::Error(m),
_ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()),
})?
};
if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id {
return Err(HostError::Error("relativeObject must be text of the same text frame".into()));
}
let (_, ts, te, _) = resolve(h, target)?;
if text_placement(arg(a, 3))? { te } else { ts }
if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) }
};
// A place inside a character (between the two halves of a surrogate pair) moves to its edge.
let b = index.byte(at, after);
let at = index.text[..b].encode_utf16().count();
if contents.is_empty() {
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
return Ok(range_ref(h, r.item, at, at, stamp, "TextRange"));
}
let b = index.byte(at, false);
let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next());
let (lead, trail) = match part {
Part::Characters => ("", ""),
@@ -774,7 +862,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
),
};
let insert = format!("{lead}{contents}{trail}");
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
record(h, r.item, &index, at, 0, &insert)?;
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
let start = at + lead.encode_utf16().count();
@@ -804,9 +892,12 @@ enum Attr {
Underline,
StrikeThrough,
TextFont,
FillColor,
StrokeColor,
StrokeWeight,
}
const ATTRS: [(&str, Attr); 11] = [
const ATTRS: [(&str, Attr); 14] = [
("size", Attr::Size),
("leading", Attr::Leading),
("autoLeading", Attr::AutoLeading),
@@ -818,6 +909,9 @@ const ATTRS: [(&str, Attr); 11] = [
("underline", Attr::Underline),
("strikeThrough", Attr::StrikeThrough),
("textFont", Attr::TextFont),
("fillColor", Attr::FillColor),
("strokeColor", Attr::StrokeColor),
("strokeWeight", Attr::StrokeWeight),
];
/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with
@@ -920,9 +1014,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize)
Attr::Underline => Data::Bool(s.underline),
Attr::StrikeThrough => Data::Bool(s.strikethrough),
Attr::TextFont => font_ref(h, &s.font_family, &s.font_style),
Attr::FillColor => colors::of_paint(&s.fill),
Attr::StrokeColor => colors::of_paint(&s.stroke),
Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)),
}
}
/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a
/// `strokeWidth` it is given.
fn stroke_scale(t: &TextObject) -> f64 {
vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0)
}
/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after.
fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> {
let finite = || number(v, name);
@@ -991,6 +1094,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &
let (family, style) = font_of(h, v)?;
(json!({"font": family, "style": style}), font_ref(h, &family, &style))
}
Attr::FillColor | Attr::StrokeColor => {
let color = colors::assigned(v, name)?;
let paint = color.map_or(Paint::None, Paint::solid);
let given = color.map_or_else(|| json!("none"), |c| colors::param(&c));
let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" };
(json!({ key: given }), colors::of_paint(&paint))
}
Attr::StrokeWeight => {
let n = finite()?;
if !(0.0..=1000.0).contains(&n) {
return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into()));
}
(json!({"strokeWidth": n}), num(n))
}
})
}
@@ -1024,7 +1141,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?;
// A leading set on characters with auto leading fixes it even where auto gives that value.
let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants);
let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p));
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p));
let fixed = match (attr, &wants) {
(Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?),
_ => None,
@@ -1042,7 +1160,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
super::atomically(h, |h| {
for (start, end, leading) in &spans {
let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading});
edit_item(h, r.item, "text.setRangeStyle", &p)?;
edit_text(h, r.item, "text.setRangeStyle", &p)?;
}
Ok(())
})?;
@@ -1054,7 +1172,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?;
let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?;
if let Attr::TextFont = attr {
let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?;
@@ -1216,7 +1334,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
edit_item(h, r.item, id, &p)?;
edit_text(h, r.item, id, &p)?;
Ok(Data::Undefined)
}
@@ -1250,32 +1368,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, Ho
Ok(ids)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
super::layers::text_scope(h, arg(a, 0))
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "TextFrames")
Ok(frames_scope(h, a)?.0)
}
/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those
/// directly in a layer or group, topmost first.
fn listed(h: &Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
match container {
None => frame_ids(h, st),
Some(c) => super::layers::text_list(h, st, c),
}
}
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
let (doc, c) = frames_scope(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
let (doc, c) = frames_scope(h, a)?;
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
}
fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let ids = listed(h, st, c)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1303,29 +1435,40 @@ fn vertical_of(d: &Data) -> std::result::Result<bool, HostError> {
}
}
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`.
fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on
/// top of the contents of `container` when there is one.
fn point_text(h: &Host, (doc, container): (Doc, Option<NodeId>), anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?;
let (_, r) =
on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?;
let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical});
if let Some(c) = container {
check_open(h, doc, c)?;
if let Some(o) = params.as_object_mut() {
o.insert("parent".into(), json!(c.0));
}
}
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &params))?;
new_ref(h, doc, result_id(&r))
}
/// The error for a layer or group that takes no new type.
const SHUT_CONTAINER: &str = "the layer or group is hidden or locked";
/// `add()`: empty point type at the origin.
fn frames_add(h: &Host, a: &[Data]) -> Answer {
point_text(h, frames_doc(h, a)?, None, false)
point_text(h, frames_scope(h, a)?, None, false)
}
/// `pointText(anchor, orientation?)`.
fn frames_point_text(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let scope = frames_scope(h, a)?;
let anchor = point(arg(a, 1), "anchor")?;
point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?)
point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?)
}
/// Turns the path `d` names into area type or type on a path with `text.createInPath`.
/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves
/// it on top of the contents of the collection's layer or group when there is one.
fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, container) = frames_scope(h, a)?;
if handle_of(arg(a, 1), "PathItem").is_none() {
return Err(HostError::Type("textPath must be a PathItem".into()));
}
@@ -1336,6 +1479,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
}
refuse_protected(h, path, "PathItem")?;
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
let vertical = vertical_of(arg(a, orientation))?;
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
@@ -1344,12 +1488,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
}
let mode = if on_path { "onPath" } else { "area" };
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
// Makes the type, threaded after or before the base frame when there is one.
let make = |h: &Host| -> std::result::Result<Option<NodeId>, HostError> {
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
}
Ok(id)
};
let Some(c) = container else {
return new_ref(h, doc, make(h)?);
};
check_open(h, doc, c)?;
// The path is moved as well as converted, so it must be one that `move` takes.
if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) {
return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0)));
}
new_ref(h, doc, id)
super::refuse_protected_edit(h, path)?;
let id = super::atomically(h, |h| {
let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?;
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
Ok(id)
})?;
new_ref(h, doc, Some(id))
}
/// Refuses a hidden or locked layer or group as the place for new type.
fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> {
if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) }
}
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
@@ -1362,17 +1529,22 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, true, &[2, 3])
}
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
/// locked artboard, stops it first, as `PageItems.removeAll()` does.
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does.
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let (doc, c) = frames_scope(h, a)?;
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = listed(h, st, c)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
// Type that clips a group or layer releases its mask, so the object above it is not made
// the clipping path.
let released = super::masks_cleared_by(&st.doc, &ids);
// So would deleting the type above an image in an ordinary group named as a tracing.
let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids);
Ok::<_, HostError>((ids, refused, on_locked, released, tracing))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -1380,10 +1552,15 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
// A clip group named as a tracing, released with an image left first, would become one.
if tracing {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, &params)))?;
}
Ok(Data::Undefined)
}
@@ -1557,6 +1734,7 @@ fn attr_type(attr: Attr) -> &'static str {
match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
Attr::FillColor | Attr::StrokeColor => "Color",
_ => "number",
}
}
@@ -1738,8 +1916,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, frames_typename), typed("string")),
("length", get(l, frames_length), typed("number")),
("parent", get(l, frames_parent), typed("Document")),
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
("parent", get(l, frames_parent), typed("*")),
("index", method(l, frames_index), returns("TextFrame", &[("itemKey", "*")])),
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
("add", method(l, frames_add), returns("TextFrame", &[])),
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
+8 -1
View File
@@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
span_of(h, d, &TEXT)
}
/// `applyTo(textItem, clearingOverrides?)`.
/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the
/// text frame is protected as for any other text edit.
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
let target = target_span(h, arg(a, 1))?;
@@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("the text is in another document than the style".into()));
}
let (index, s, e, _) = resolve(h, target)?;
super::refuse_protected(h, target.item, "TextFrame")?;
h.charge_call(16 + (e - s) as u64)?;
let (start, end) = if style.para {
let (_, ba, bb) = para_range(&index, s, e);
@@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
None => Data::Undefined,
},
// A style's colors and stroke weight are not available yet (`char_members`).
Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined,
}
}
@@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec<Described> {
ATTRS
.iter()
.map(|&(name, attr)| {
if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) {
return super::super::later(link, "CharacterAttributes", name);
}
let data_type = match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
+8 -1
View File
@@ -24,7 +24,8 @@
//! other value, and a scale of strokes and effects with positions left as they are, throws an
//! error that says so.
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
//! with nothing changed, and so are
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
//! past the canvas.
@@ -41,6 +42,9 @@ const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"
/// The error for a locked object.
const LOCKED: &str = "cannot transform locked objects";
/// The error for a guide while guides are locked.
const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked";
/// The error for a hidden object.
const HIDDEN: &str = "cannot transform hidden objects";
@@ -215,6 +219,9 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) {
return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0)));
}
// The identity acts the same about every point, so an object without bounds (an empty path)
// takes it too.
let o = match (about, bounds) {