mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/global-edit-stale-points
This commit is contained in:
commit
5ff65970f9
135 files changed
+5722
-421
No files matched your search
@@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with.
|
||||
// started with, nor the Artboard tool's selection from the start of the run.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
@@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
Some(chosen) => std::slice::from_ref(chosen),
|
||||
None => h.active_artboards.as_slice(),
|
||||
};
|
||||
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid));
|
||||
let start = Start { active, picks, batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
|
||||
@@ -125,6 +125,7 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
/// ([`variables::before_command`]).
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
|
||||
tracing::before_command(h);
|
||||
variables::before_command(h, id)
|
||||
}
|
||||
|
||||
@@ -427,7 +428,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
|
||||
|
||||
/// Notes the changes a command made to the points of the paths the run has read
|
||||
/// ([`paths::see_all_points`]).
|
||||
pub(super) fn see_points(h: &Host) {
|
||||
pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> {
|
||||
paths::see_all_points(h)
|
||||
}
|
||||
|
||||
@@ -1070,7 +1071,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res
|
||||
/// is made active, so bounds it reads take in type that the switch measured again (in the
|
||||
/// document's own composite fonts, [`Session::set_active`]).
|
||||
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
paths::see_all_points(h);
|
||||
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, f));
|
||||
h.dom.editing.set(kept);
|
||||
|
||||
@@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool {
|
||||
|
||||
/// The real path of the `File` `d` gives as an image to place or relink: one the script may read
|
||||
/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of
|
||||
/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no
|
||||
/// error names the path.
|
||||
/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path.
|
||||
/// What the file holds is checked by the command that places or relinks it, which reads it once.
|
||||
fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
|
||||
let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?;
|
||||
if path.len() > super::super::files::MAX_PATH_CHARS {
|
||||
@@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result<String, HostError> {
|
||||
if meta.len() > MAX_PLACED_BYTES {
|
||||
return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20)));
|
||||
}
|
||||
let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned();
|
||||
// What the file holds, read the way `file.place` reads it, before the document changes.
|
||||
let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?;
|
||||
if field(&info, "pixelWidth").is_none() {
|
||||
return Err(HostError::Error(NOT_AN_IMAGE.into()));
|
||||
Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink`
|
||||
/// refusing a file that holds no image before the document changes: that refusal is
|
||||
/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check
|
||||
/// and for the image it places.
|
||||
fn image_only<T>(h: &Host, f: impl FnOnce(&Host) -> Result<T, HostError>) -> Result<T, HostError> {
|
||||
let kept = h.session.borrow().image_only.replace(Some(true));
|
||||
let r = f(h);
|
||||
let refused = h.session.borrow().image_only.replace(kept) == Some(false);
|
||||
match r {
|
||||
Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())),
|
||||
r => r,
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
// ---- PlacedItem ----
|
||||
@@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
|
||||
// The placement and its check run under one savepoint, so an error after the place leaves
|
||||
// no linked image behind.
|
||||
let id = super::atomically(h, |h| {
|
||||
let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?;
|
||||
let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?;
|
||||
let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64));
|
||||
let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId);
|
||||
let linked =
|
||||
@@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
|
||||
fn placed_relink(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_of(h, a, "PlacedItem")?;
|
||||
let path = image_path(h, arg(a, 1), "relink's file")?;
|
||||
edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?;
|
||||
image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -473,7 +481,8 @@ fn area_of(m: Affine) -> bool {
|
||||
|
||||
/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix.
|
||||
/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted
|
||||
/// image is refused before anything changes; the matrix the image has already changes nothing.
|
||||
/// image is refused before anything changes, and so is a locked or hidden image or one on a locked
|
||||
/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing.
|
||||
fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
let item = this_of(h, a, cls)?;
|
||||
let m = matrix_value(arg(a, 1))?;
|
||||
@@ -484,6 +493,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
if n.is_distorted_image() {
|
||||
return Err(HostError::Error(DISTORTED.into()));
|
||||
}
|
||||
// The transform methods' refusals: a locked or hidden image, one inside a locked or hidden
|
||||
// layer or group, and one on a locked artboard, whether or not the matrix changes.
|
||||
let d = &st.doc;
|
||||
let line = d.ancestry(item.id);
|
||||
let any = |f: fn(&vectorcraft_doc::Node) -> bool| {
|
||||
line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f)))
|
||||
};
|
||||
if any(|n| n.locked) {
|
||||
return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0)));
|
||||
}
|
||||
if any(|n| !n.visible) {
|
||||
return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0)));
|
||||
}
|
||||
if super::on_locked_artboard(h, st, item.id) {
|
||||
return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0)));
|
||||
}
|
||||
let f = frame(st)?;
|
||||
let target = Affine::new(match h.dom.coords.get() {
|
||||
Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]],
|
||||
|
||||
@@ -309,7 +309,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
|
||||
let selected = with_doc(h, doc, |_, st| {
|
||||
// The scan is charged by every selected object it looks at.
|
||||
let objects = &st.selection.objects;
|
||||
let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)));
|
||||
h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?;
|
||||
Ok::<_, HostError>(found.is_some())
|
||||
})?;
|
||||
Ok(Data::Bool(selected))
|
||||
}
|
||||
|
||||
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
|
||||
@@ -336,7 +343,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
|
||||
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let (ids, over) = with_doc(h, doc, |_, st| {
|
||||
let (ids, over) = with_doc(h, doc, |s, st| {
|
||||
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
|
||||
let selected = &st.selection.objects;
|
||||
h.charge_call(selected.len() as u64)?;
|
||||
@@ -349,10 +356,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
// The walk is charged by every node it looks at, hidden and locked ones included, whether
|
||||
// or not anything is added.
|
||||
h.charge_call(count)?;
|
||||
// While an object is isolated, the art that holds it is replaced by the isolated object,
|
||||
// or by what an isolated group or other container holds, as Select All takes it.
|
||||
let isolated = st.isolation.and_then(|i| st.doc.node(i));
|
||||
let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default();
|
||||
let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template()));
|
||||
let mut candidates = Vec::with_capacity(art.len());
|
||||
for o in art {
|
||||
match isolated {
|
||||
Some(_) if path.contains(&o) && !editable => {}
|
||||
Some(c) if path.contains(&o) && c.is_container() => {
|
||||
// The same walk as the layer's, through any sublayer the container holds.
|
||||
let visited = collect_editable_art(c, &mut candidates);
|
||||
h.charge_call(visited)?;
|
||||
}
|
||||
Some(c) if path.contains(&o) => candidates.push(c.id),
|
||||
_ => candidates.push(o),
|
||||
}
|
||||
}
|
||||
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
|
||||
let mut ids = Vec::new();
|
||||
for o in art {
|
||||
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
|
||||
for o in candidates {
|
||||
if have.contains(&o)
|
||||
|| !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o)
|
||||
|| (s.guides_locked() && crate::is_guide_path(&st.doc, o))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Only art that would be added counts toward the limit.
|
||||
|
||||
@@ -862,7 +862,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if clipping {
|
||||
return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0)));
|
||||
}
|
||||
see_all_points(h);
|
||||
see_all_points(h)?;
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = on_doc(h, item.doc.uid, true, |h| {
|
||||
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
|
||||
@@ -1236,6 +1236,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c
|
||||
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
|
||||
}
|
||||
|
||||
/// The largest stroke weight in the path `item`'s own appearance, in points.
|
||||
pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result<f64, HostError> {
|
||||
read_path(h, item, |_, n, _| {
|
||||
n.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width),
|
||||
vectorcraft_doc::AppearanceItem::Fill(_) => None,
|
||||
})
|
||||
.fold(0.0, f64::max)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
|
||||
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
|
||||
@@ -1377,24 +1391,32 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
|
||||
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
|
||||
/// object model's own, and their points stay valid; the other Global Edit members, which take the
|
||||
/// object model's edit too, are looked at as well. A document that is the one the run last looked
|
||||
/// at is skipped, as are its paths.
|
||||
pub(super) fn see_all_points(h: &super::Host) {
|
||||
let keys: Vec<(u64, u64)> = {
|
||||
/// at is skipped, as are its paths. The look is charged by the objects it looks at.
|
||||
pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
let (keys, looked_at): (Vec<(u64, u64)>, u64) = {
|
||||
let s = h.session.borrow();
|
||||
let mut docs = h.dom.point_docs.borrow_mut();
|
||||
let seen = h.dom.point_nodes.borrow();
|
||||
let mut keys = Vec::new();
|
||||
let mut looked_at = 0u64;
|
||||
docs.retain(|uid, before| {
|
||||
let state = s.documents().iter().find(|d| d.uid == *uid);
|
||||
let after = state.map(|st| &st.doc);
|
||||
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
|
||||
return true;
|
||||
}
|
||||
// A document none of whose paths the run still holds points of is not looked at; reading
|
||||
// points again keeps it as it is then.
|
||||
if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) {
|
||||
return false;
|
||||
}
|
||||
// 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. While Global Edit is on,
|
||||
// an edit of the selected member (also one made by moving a group that holds it) is
|
||||
// given to the other members, so each of them, or the outermost Objects on Path group
|
||||
// holding it, is looked at too. Subtrees the command left as they were are skipped.
|
||||
// Each node is paired with the node of the same id under the same parent now, so that no
|
||||
// node is searched for through the whole document.
|
||||
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
|
||||
Some(item) => {
|
||||
let root = |id: NodeId| {
|
||||
@@ -1405,19 +1427,44 @@ pub(super) fn see_all_points(h: &super::Host) {
|
||||
};
|
||||
let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten();
|
||||
let mut roots = std::collections::HashSet::new();
|
||||
std::iter::once(item.id).chain(members).map(root).filter(|id| roots.insert(*id)).filter_map(|id| node_arc(before, id)).collect()
|
||||
std::iter::once(item.id)
|
||||
.chain(members)
|
||||
.map(root)
|
||||
.filter(|id| roots.insert(*id))
|
||||
.filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))))
|
||||
.collect()
|
||||
}
|
||||
None => before.layers.iter().collect(),
|
||||
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
|
||||
};
|
||||
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)) {
|
||||
// A group that moved to another parent keeps its node, so a node with children that is
|
||||
// not found under its old parent is looked for among all the nodes now, listed once.
|
||||
let mut all: Option<std::collections::HashMap<NodeId, &Arc<crate::doc::Node>>> = None;
|
||||
while let Some((node, mut now)) = todo.pop() {
|
||||
looked_at += 1;
|
||||
if now.is_none()
|
||||
&& node.children().is_some()
|
||||
&& let Some(d) = after
|
||||
{
|
||||
let all = all.get_or_insert_with(|| {
|
||||
let mut m = std::collections::HashMap::new();
|
||||
let mut stack: Vec<&Arc<crate::doc::Node>> = d.layers.iter().collect();
|
||||
while let Some(n) = stack.pop() {
|
||||
m.insert(n.id, n);
|
||||
stack.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
looked_at += m.len() as u64;
|
||||
m
|
||||
});
|
||||
now = all.get(&node.id).copied();
|
||||
}
|
||||
if now.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);
|
||||
todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at));
|
||||
}
|
||||
}
|
||||
if let Some(after) = after {
|
||||
@@ -1429,8 +1476,11 @@ pub(super) fn see_all_points(h: &super::Host) {
|
||||
});
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
keys
|
||||
(keys, looked_at)
|
||||
};
|
||||
if looked_at > 0 {
|
||||
h.charge_call(looked_at)?;
|
||||
}
|
||||
let editing = h.dom.editing.get();
|
||||
for (uid, id) in keys {
|
||||
let own = || match editing {
|
||||
@@ -1443,6 +1493,20 @@ pub(super) fn see_all_points(h: &super::Host) {
|
||||
};
|
||||
see_points(h, (uid, id), own);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the
|
||||
/// nodes of `after` it looks at.
|
||||
fn paired<'a>(
|
||||
before: &'a [Arc<crate::doc::Node>],
|
||||
after: Option<&'a Vec<Arc<crate::doc::Node>>>,
|
||||
looked_at: &mut u64,
|
||||
) -> Vec<(&'a Arc<crate::doc::Node>, Option<&'a Arc<crate::doc::Node>>)> {
|
||||
let after = after.map_or(&[][..], Vec::as_slice);
|
||||
*looked_at += after.len() as u64;
|
||||
let now: std::collections::HashMap<NodeId, &Arc<crate::doc::Node>> = after.iter().map(|n| (n.id, n)).collect();
|
||||
before.iter().map(|n| (n, now.get(&n.id).copied())).collect()
|
||||
}
|
||||
|
||||
fn points_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
|
||||
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
|
||||
//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one
|
||||
//! `unit`, more than 0 and at most 1000.
|
||||
//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is
|
||||
//! one drawing unit. It is at least 0.0001 and at most 1000.
|
||||
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
|
||||
//! the default its help page gives and throws an error that says it is not available yet at any
|
||||
//! other value; a property the help pages do not list throws an error that names it, unless it is
|
||||
@@ -739,10 +739,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result:
|
||||
Data::Number(n) if n.is_finite() => *n,
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
};
|
||||
if !(n > 0.0 && n <= 1000.0) {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000")));
|
||||
// A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is
|
||||
// 0.0001%.
|
||||
if !(0.0001..=1000.0).contains(&n) {
|
||||
return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000")));
|
||||
}
|
||||
p.insert("scale".into(), json!(n));
|
||||
p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start())));
|
||||
}
|
||||
"version" => {
|
||||
let version = match pick("AutoCADCompatibility")? {
|
||||
@@ -1025,7 +1027,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
|
||||
}
|
||||
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
|
||||
@@ -128,6 +128,10 @@ pub(super) struct State {
|
||||
prev: RefCell<HashMap<(u64, u64), u64>>,
|
||||
sources: RefCell<HashMap<(u64, u64), NodeId>>,
|
||||
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
|
||||
/// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`])
|
||||
/// and the lowest id the run could allocate after the first note or the latest revert
|
||||
/// ([`note_document`]).
|
||||
marks: RefCell<HashMap<u64, (u64, u64)>>,
|
||||
retraces: Cell<usize>,
|
||||
}
|
||||
|
||||
@@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Before each command a script runs: notes the active document ([`note_document`]).
|
||||
pub(super) fn before_command(h: &Host) {
|
||||
let s = h.session.borrow();
|
||||
if let Some(st) = s.active() {
|
||||
note_document(h, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the next object id when the run first notes the document `st`. A revert resets
|
||||
/// the mark to the reloaded document's next object id and keeps the descendant snapshots.
|
||||
/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it.
|
||||
fn note_document(h: &Host, st: &crate::DocState) {
|
||||
let mut marks = h.dom.tracing.marks.borrow_mut();
|
||||
match marks.get_mut(&st.uid) {
|
||||
Some((reverts, _)) if *reverts == st.reverts => {}
|
||||
Some((reverts, mark)) => {
|
||||
*reverts = st.reverts;
|
||||
*mark = st.doc.peek_next_id();
|
||||
}
|
||||
None => {
|
||||
marks.insert(st.uid, (st.reverts, st.doc.peek_next_id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the lowest id the run could allocate in document `uid` after its first note or latest
|
||||
/// revert ([`note_document`]).
|
||||
fn mark(h: &Host, uid: u64) -> Option<u64> {
|
||||
h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark)
|
||||
}
|
||||
|
||||
pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool {
|
||||
let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied();
|
||||
source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
|
||||
@@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<
|
||||
/// and "Cannot edit page item" when it holds a locked object other than its source image, which
|
||||
/// the replacement would discard. The objects looked at are charged to the run either way.
|
||||
fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
let (visited, result) = read_group(h, item, |_, group| {
|
||||
let (visited, result) = read_group(h, item, |st, group| {
|
||||
note_document(h, st);
|
||||
remember_source(h, item.doc.uid, group);
|
||||
// The objects the trace made, as the tracing records them; a tracing saved without that
|
||||
// record is checked against the objects it held when this run first saw it.
|
||||
// A tracing with a record is checked against the objects its trace made. A tracing without
|
||||
// a record is checked against its first descendant snapshot, which survives reverts.
|
||||
// If the group id is below the document's mark, members at or above the mark are also added.
|
||||
// A revert resets the mark to the reloaded document's next object id.
|
||||
let made = group.trace_made();
|
||||
let descendants = h.dom.tracing.descendants.borrow();
|
||||
let ids = match made {
|
||||
Some(_) => None,
|
||||
None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?),
|
||||
None => descendants.get(&(item.doc.uid, item.id.0)),
|
||||
};
|
||||
let newer = match made {
|
||||
Some(_) => None,
|
||||
None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m),
|
||||
};
|
||||
let source = group.children().and_then(|c| c.first()).map(|n| n.id);
|
||||
let mut visited = 0u64;
|
||||
@@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
|
||||
(Some(m), _) => !m.contains(n.id),
|
||||
(None, Some(ids)) => !ids.contains(&n.id),
|
||||
(None, None) => false,
|
||||
};
|
||||
} || newer.is_some_and(|m| n.id.0 >= m);
|
||||
// Added artwork is reported before a locked object, whichever comes first.
|
||||
if added {
|
||||
return Ok((visited, Err(HostError::Error(refusal.into()))));
|
||||
|
||||
@@ -20,9 +20,13 @@
|
||||
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
|
||||
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
|
||||
//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to
|
||||
//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any
|
||||
//! other value, and a scale of strokes and effects with positions left as they are, throws an
|
||||
//! error that says so.
|
||||
//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points.
|
||||
//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight
|
||||
//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale
|
||||
//! of strokes and effects with positions left as they are, throws an error that says so.
|
||||
//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN`
|
||||
//! still uses the first artboard's bottom-left corner; other named points use the origin.
|
||||
//! Its linked opacity mask, strokes, effects and patterns transform with the same options.
|
||||
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
|
||||
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
|
||||
//! with nothing changed, and so are
|
||||
@@ -37,16 +41,16 @@ use super::matrix::{self, Matrix};
|
||||
use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc};
|
||||
|
||||
/// The error for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
|
||||
pub(super) 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";
|
||||
pub(super) 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";
|
||||
pub(super) const HIDDEN: &str = "cannot transform hidden objects";
|
||||
|
||||
/// The identity matrix.
|
||||
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
@@ -136,8 +140,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> {
|
||||
}
|
||||
|
||||
/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name`
|
||||
/// ([`anchor_name`]) names.
|
||||
fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Point, HostError> {
|
||||
/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`.
|
||||
fn anchor(h: &Host, item: Item, r: Option<Rect>, name: &str) -> std::result::Result<Point, HostError> {
|
||||
if r.is_none() && !paths::is_path(h, item) {
|
||||
return Err(HostError::Error("the object has no bounds".into()));
|
||||
}
|
||||
if name == "DOCUMENTORIGIN" {
|
||||
return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])));
|
||||
}
|
||||
let Some(r) = r else {
|
||||
return Ok(Point::ORIGIN);
|
||||
};
|
||||
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
Ok(match name {
|
||||
"TOPLEFT" => Point::new(r.x0, r.y0),
|
||||
@@ -148,7 +161,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Poin
|
||||
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
|
||||
"BOTTOM" => Point::new(cx, r.y1),
|
||||
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
|
||||
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
|
||||
_ => Point::new(cx, cy),
|
||||
})
|
||||
}
|
||||
@@ -222,12 +234,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
|
||||
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.
|
||||
// The identity acts the same about every point for any object.
|
||||
let o = match (about, bounds) {
|
||||
_ if m == IDENTITY => Point::ORIGIN,
|
||||
(Some(name), Some(r)) => anchor(h, item, r, name)?,
|
||||
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
|
||||
(Some(name), r) => anchor(h, item, r, name)?,
|
||||
(None, _) => Point::ORIGIN,
|
||||
};
|
||||
let xf = on_page(m, o);
|
||||
@@ -249,6 +259,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
|
||||
}
|
||||
let c = xf.as_coeffs();
|
||||
let identity = xf == Affine::IDENTITY;
|
||||
// Every stroke layer's weight is checked with the factor `object.transform` applies.
|
||||
let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None };
|
||||
if let Some(k) = factor
|
||||
&& paths::is_path(h, item)
|
||||
&& (!k.is_finite() || {
|
||||
let width = paths::largest_stroke_weight(h, item)? * k;
|
||||
!width.is_finite() || width > paths::MAX_STROKE_WIDTH
|
||||
})
|
||||
{
|
||||
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
|
||||
}
|
||||
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
|
||||
// The transformation and the stroke weight change together or not at all.
|
||||
atomically(h, |h| {
|
||||
|
||||
@@ -1519,8 +1519,10 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
dom::see_points(host);
|
||||
// The command stays kept when the look at its changes passes a limit, which ends the run.
|
||||
let seen = dom::see_points(host);
|
||||
dom::after_kept_command(host);
|
||||
seen?;
|
||||
} else {
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user