mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into feat/scripts-api-d3-layers-artboards
This commit is contained in:
commit
cd3a0da644
375 files changed
+24589
-3335
No files matched your search
@@ -1022,9 +1022,16 @@ pub(super) fn after_kept_command(h: &Host) {
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
edit_item_with(h, item, |h| command(h, id, params))
|
||||
}
|
||||
|
||||
/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document
|
||||
/// 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);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
@@ -2548,8 +2555,12 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the
|
||||
/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path
|
||||
/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does
|
||||
/// nothing.
|
||||
/// nothing. Type in a document in the back that is not measured yet is measured first, as the
|
||||
/// switch to that document would measure it.
|
||||
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option<Rect>, Frame), HostError> {
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && rests_on_type(h, item) {
|
||||
h.session.borrow_mut().measure_back_type(item.doc.uid);
|
||||
}
|
||||
with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?)))
|
||||
}
|
||||
|
||||
@@ -2621,20 +2632,45 @@ fn item_height(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height())))
|
||||
}
|
||||
|
||||
/// Whether the item's bounds can rest on laid-out type: it holds type, a symbol instance or a
|
||||
/// placed document. Such bounds in a document in the back may be laid out in another document's
|
||||
/// composite fonts, so the setters measure them only after the switch to the document.
|
||||
fn rests_on_type(h: &Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).is_none_or(|n| {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_)));
|
||||
found
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one
|
||||
/// stays).
|
||||
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
|
||||
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
|
||||
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
|
||||
edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
// The distance to move, or `None` when the item is already there or has no bounds.
|
||||
let delta = |h: &Host| -> std::result::Result<Option<(f64, f64)>, HostError> {
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(None) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
|
||||
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
|
||||
Ok((dx.abs() > 1e-9 || dy.abs() > 1e-9).then_some((dx, dy)))
|
||||
};
|
||||
// An item already in place stays, and its document stays in the back.
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && delta(h)?.is_none() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// Measured again once the document is active.
|
||||
edit_item_with(h, item, |h| {
|
||||
if let Some((dx, dy)) = delta(h)? {
|
||||
command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -2668,18 +2704,29 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
return Err(HostError::Error(format!("the object has no {what} to scale")));
|
||||
}
|
||||
if (now - size).abs() < 1e-9 {
|
||||
// The bounds to scale and the percentage, or `None` when the item already has that size or has
|
||||
// no bounds.
|
||||
let scale = |h: &Host| -> std::result::Result<Option<(Rect, f64)>, HostError> {
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(None) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
return Err(HostError::Error(format!("the object has no {what} to scale")));
|
||||
}
|
||||
Ok(((now - size).abs() >= 1e-9).then_some((r, size / now * 100.0)))
|
||||
};
|
||||
// An item already that size stays, and its document stays in the back.
|
||||
if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && scale(h)?.is_none() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let pct = size / now * 100.0;
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"});
|
||||
edit_item(h, item, "object.scale", &p)?;
|
||||
// Measured again once the document is active, so the ratio applies to the bounds the scale
|
||||
// works on.
|
||||
edit_item_with(h, item, |h| {
|
||||
if let Some((r, pct)) = scale(h)? {
|
||||
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
|
||||
command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,9 +69,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, 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, item_rect, 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, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method,
|
||||
named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -248,8 +248,9 @@ 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 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.
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
|
||||
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
|
||||
/// points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
@@ -427,13 +428,32 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
@@ -443,10 +463,15 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
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()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -454,10 +479,13 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(_) => match items_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -483,7 +511,7 @@ fn items_remove_all(h: &super::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}")));
|
||||
}
|
||||
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<_>>()})))?;
|
||||
|
||||
@@ -545,6 +545,8 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile.
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
@@ -693,6 +695,7 @@ fn map_color(h: &Host, slot: usize, job: &mut Job) {
|
||||
let source = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "SOURCEPROFILE");
|
||||
job.profile = set.iter().find(|(k, _)| *k == "name").map(|(_, v)| string_of(v));
|
||||
job.source = source;
|
||||
job.custom = set.iter().any(|(k, v)| *k == "colorProfileMode" && member_of(v) == "CUSTOMPROFILE");
|
||||
let g = job.group("color");
|
||||
for (k, v) in &set {
|
||||
if *k == "intent" {
|
||||
@@ -992,7 +995,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// each assigned name against the list it must come from, and puts the checked names into the
|
||||
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws.
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
@@ -1022,6 +1025,9 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
}
|
||||
job.group("advanced").insert("flattenerPreset".into(), json!(n));
|
||||
}
|
||||
if job.custom && job.profile.is_none() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.profile.take() {
|
||||
let what = "PrintColorManagementOptions.name";
|
||||
let n = plain_name(what, "color profile", &name)?;
|
||||
|
||||
@@ -366,7 +366,12 @@ const AI_KEPT: &[(&str, Default)] = &[
|
||||
];
|
||||
|
||||
fn ai_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))]
|
||||
vec![
|
||||
("compatibility", text("Compatibility.ILLUSTRATOR19")),
|
||||
("compressed", Data::Bool(true)),
|
||||
("pdfCompatible", Data::Bool(true)),
|
||||
("embedICCProfile", Data::Bool(false)),
|
||||
]
|
||||
}
|
||||
|
||||
fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
@@ -1010,12 +1015,13 @@ const SAVES_SOME_ARTBOARDS: &str =
|
||||
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// Whether the file that saving `st` with its remembered options writes would omit artboards. A
|
||||
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai`
|
||||
/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its
|
||||
/// `range` names only the separate files. An EPS file embeds the whole document in its main file,
|
||||
/// so its `artboardRange` never omits an artboard from what reopens.
|
||||
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file holds every
|
||||
/// artboard, and its `range` names only the separate files of `separateArtboards`. A `.ai` file
|
||||
/// other than a legacy version 7 one with `separateArtboards` holds every artboard too. An EPS
|
||||
/// file embeds the whole document in its main file, so its `artboardRange` never omits an artboard
|
||||
/// from what reopens.
|
||||
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
if st.format == "eps" {
|
||||
if matches!(st.format, "eps" | "vectorcraft" | "template") {
|
||||
return false;
|
||||
}
|
||||
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
|
||||
@@ -1027,7 +1033,7 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
return true;
|
||||
}
|
||||
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
|
||||
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
|
||||
if matches!(st.format, "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
|
||||
return false;
|
||||
}
|
||||
let count = st.doc.artboards.len();
|
||||
|
||||
@@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8.
|
||||
fn decode(s: &str) -> String {
|
||||
pub(crate) fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
|
||||
@@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool {
|
||||
p.split(['/', '\\']).any(|name| name == "..")
|
||||
}
|
||||
|
||||
/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give
|
||||
/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…`
|
||||
/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a
|
||||
/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written
|
||||
/// misses. A `//host/share` path, and a form with a `..` name, is left out.
|
||||
pub fn uri_forms(value: &str, windows: bool) -> Vec<String> {
|
||||
if !value.starts_with('/') || value.starts_with("//") {
|
||||
return Vec::new();
|
||||
}
|
||||
let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| {
|
||||
let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
let letter = first.as_bytes();
|
||||
(letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char))
|
||||
});
|
||||
let mut forms = Vec::new();
|
||||
for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) {
|
||||
let decoded = crate::script::files::decode(form);
|
||||
for f in [decoded.as_str(), form] {
|
||||
if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) {
|
||||
forms.push(f.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// A real path as people read it.
|
||||
fn display(path: &Path) -> Arc<str> {
|
||||
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
|
||||
@@ -575,13 +601,18 @@ impl Files {
|
||||
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
|
||||
// A script given as text has no folder, and so no file it may read.
|
||||
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
|
||||
// Each candidate, and whether the scope's refusal passes it over.
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
|
||||
// Each candidate, and whether the scope's refusal passes it over. The path as written comes
|
||||
// first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in
|
||||
// URI notation are tried, and when none of them is read either, the error of the path as written stands.
|
||||
let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) };
|
||||
let mut literal_error = None;
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())];
|
||||
candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true)));
|
||||
if search && !path.is_absolute() {
|
||||
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
|
||||
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
|
||||
}
|
||||
for (candidate, passed_over_when_refused) in candidates {
|
||||
for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() {
|
||||
let Some(candidate) = candidate else { return Err(refused()) };
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
@@ -590,12 +621,22 @@ impl Files {
|
||||
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
|
||||
Ok(found) => return Ok(found),
|
||||
Err(ScriptRead::Missing) => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {
|
||||
if i == 0 {
|
||||
literal_error = Some(refused());
|
||||
}
|
||||
}
|
||||
Err(ScriptRead::Refused) => return Err(refused()),
|
||||
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
|
||||
Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => {
|
||||
literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}")));
|
||||
}
|
||||
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
|
||||
}
|
||||
}
|
||||
if let Some(error) = literal_error {
|
||||
return Err(error);
|
||||
}
|
||||
Err((FailKind::Error, format!("include file not found: {value}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -498,11 +498,13 @@ struct World {
|
||||
|
||||
/// The choices outside the documents that a script's commands can change: the preferences, the
|
||||
/// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state.
|
||||
/// item, the Eyedropper's sample, the envelope defaults, the Caps Lock state and whether Overprint
|
||||
/// Preview turns on when the run ends.
|
||||
#[derive(Clone)]
|
||||
struct Choices {
|
||||
prefs: crate::Prefs,
|
||||
caps_lock: bool,
|
||||
overprint_after_run: bool,
|
||||
eyedropper_sample: Option<Arc<vectorcraft_doc::Node>>,
|
||||
global_edit_options: cmd::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
@@ -518,6 +520,7 @@ impl Choices {
|
||||
Self {
|
||||
prefs: s.prefs.clone(),
|
||||
caps_lock: s.caps_lock,
|
||||
overprint_after_run: s.overprint_after_run,
|
||||
eyedropper_sample: s.eyedropper_sample.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
@@ -532,6 +535,7 @@ impl Choices {
|
||||
fn put(self, s: &mut Session) {
|
||||
s.prefs = self.prefs;
|
||||
s.caps_lock = self.caps_lock;
|
||||
s.overprint_after_run = self.overprint_after_run;
|
||||
s.eyedropper_sample = self.eyedropper_sample;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
@@ -546,6 +550,7 @@ impl Choices {
|
||||
use std::mem::swap;
|
||||
swap(&mut self.prefs, &mut s.prefs);
|
||||
swap(&mut self.caps_lock, &mut s.caps_lock);
|
||||
swap(&mut self.overprint_after_run, &mut s.overprint_after_run);
|
||||
swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample);
|
||||
swap(&mut self.global_edit_options, &mut s.global_edit_options);
|
||||
swap(&mut self.select_similar, &mut s.select_similar);
|
||||
@@ -659,6 +664,8 @@ pub(crate) struct Savepoint {
|
||||
pending_paint: Option<crate::Paint>,
|
||||
choices: Choices,
|
||||
journal: usize,
|
||||
/// The plug-in events queued before the command ([`Session::plugin_events_mark`]).
|
||||
plugin_events: u64,
|
||||
}
|
||||
|
||||
impl Savepoint {
|
||||
@@ -693,6 +700,7 @@ impl Savepoint {
|
||||
pending_paint: s.pending_paint.clone(),
|
||||
choices: Choices::of(s),
|
||||
journal: s.journal.len(),
|
||||
plugin_events: s.plugin_events_mark(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -745,6 +753,8 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
// The documents the command opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(self.plugin_events);
|
||||
s.sync_front_profiles();
|
||||
exact
|
||||
}
|
||||
@@ -2197,6 +2207,8 @@ impl Session {
|
||||
lost
|
||||
});
|
||||
drop(lost);
|
||||
// The job's working copy went with it, with the documents the run opened.
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
@@ -2592,6 +2604,7 @@ impl Session {
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
self.end_job(job, e.kind == RunErrorKind::Internal);
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
@@ -2668,6 +2681,9 @@ impl Session {
|
||||
self.script_stop.clear();
|
||||
self.reset_tool();
|
||||
cmd::compositefonts::sync(self);
|
||||
if std::mem::take(&mut self.overprint_after_run) {
|
||||
cmd::colormgmt::turn_on_overprint_preview(self);
|
||||
}
|
||||
let host = &job.host;
|
||||
let mut report = json!({
|
||||
"ok": true,
|
||||
@@ -2697,6 +2713,7 @@ impl Session {
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
let tool = host.dom.chosen_tool();
|
||||
self.end_job(job, false);
|
||||
self.plugin_events_script_ended(true);
|
||||
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
|
||||
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
|
||||
if let Some(id) = tool
|
||||
|
||||
Reference in new issue
Block a user