mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into feat/scripts-export-autocad
This commit is contained in:
commit
7f10f7aa96
265 files changed
+13563
-1270
No files matched your search
+139
-36
@@ -94,9 +94,10 @@ use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod print;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -209,6 +210,8 @@ pub(super) struct State {
|
||||
saving: Cell<bool>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
/// The print option objects ([`print`]).
|
||||
printing: print::State,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
@@ -228,6 +231,17 @@ impl State {
|
||||
self.saving.get()
|
||||
}
|
||||
|
||||
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
|
||||
/// whether jobs an earlier run prepared still wait.
|
||||
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
|
||||
self.printing.start(printers, waiting);
|
||||
}
|
||||
|
||||
/// The jobs the run prepared for a printer, which the run no longer holds.
|
||||
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
|
||||
self.printing.take_jobs()
|
||||
}
|
||||
|
||||
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
|
||||
/// when the run ends without an error.
|
||||
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
|
||||
@@ -620,10 +634,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
}
|
||||
|
||||
/// The ids of a document's page items, topmost first, each group or compound path before the
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read).
|
||||
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again,
|
||||
/// after an edit or for another document, counts against the run's host-call allowance as a list
|
||||
/// of that many objects does ([`list_charge`]).
|
||||
fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
|
||||
for n in nodes.iter().rev() {
|
||||
@@ -641,9 +657,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
walk(&st.doc.layers, &mut ids);
|
||||
h.charge_call(list_charge(ids.len()))?;
|
||||
let ids = Rc::new(ids);
|
||||
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The bytes a list of `n` objects that a collection builds again counts against the run's
|
||||
/// host-call allowance, as the selection's list counts them ([`selection_of`]).
|
||||
pub(super) fn list_charge(n: usize) -> u64 {
|
||||
16u64.saturating_mul(n as u64)
|
||||
}
|
||||
|
||||
/// The objects directly in the layers and sublayers of a document: what deleting every page item
|
||||
@@ -901,8 +924,8 @@ fn on_doc_steps<T>(
|
||||
restored = restore_layer(h, uid, layer.0, &layer.1);
|
||||
}
|
||||
}
|
||||
// The document that was active is active again before any error is given: `f`'s error first,
|
||||
// then the selection's, then the switch back's.
|
||||
// The document that was active is active again before any error is given: an error that ends
|
||||
// the run first, then `f`'s error, then the selection's, then the switch back's.
|
||||
let back = match active {
|
||||
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
|
||||
_ => Ok(()),
|
||||
@@ -914,12 +937,35 @@ fn on_doc_steps<T>(
|
||||
{
|
||||
st.activated = activated;
|
||||
}
|
||||
first_error(r, restored, back)
|
||||
}
|
||||
|
||||
/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer
|
||||
/// (`restored`) and the active document (`back`): an error that ends the run first, since a
|
||||
/// script could catch `f`'s ordinary error, then the first error in that order.
|
||||
fn first_error<T>(
|
||||
r: std::result::Result<T, HostError>,
|
||||
restored: std::result::Result<(), HostError>,
|
||||
back: std::result::Result<(), HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !r.as_ref().is_err_and(ends_run) {
|
||||
restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?;
|
||||
}
|
||||
let v = r?;
|
||||
restored?;
|
||||
back?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether `e` ends the run, so that a script cannot catch it.
|
||||
fn ends_run(e: &HostError) -> bool {
|
||||
match e {
|
||||
HostError::Abort(_) => true,
|
||||
HostError::Marked { error, .. } => ends_run(error),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
@@ -1013,13 +1059,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter
|
||||
/// or a `\`) letters in one case.
|
||||
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
fn path_key(p: &str) -> String {
|
||||
let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':');
|
||||
let p = p.replace('\\', "/");
|
||||
let p = p.trim_end_matches('/').to_string();
|
||||
if windows { p.to_lowercase() } else { p }
|
||||
let b = p.as_bytes();
|
||||
let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
|
||||
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's
|
||||
@@ -1503,6 +1549,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
})
|
||||
}
|
||||
|
||||
/// `documents.addDocumentNoUI(startupPreset)`: a new document from the New Document profile
|
||||
/// `startupPreset` names, as `addDocument(startupPreset)` makes it, without the New Document
|
||||
/// dialog. Arguments after `startupPreset` are ignored.
|
||||
fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
|
||||
docs_add_document(h, &a[..a.len().min(2)])
|
||||
}
|
||||
|
||||
/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page
|
||||
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> gives; the other settings are
|
||||
/// left out. The settings stay with the run, which hands the script an object of the
|
||||
@@ -1581,6 +1634,19 @@ fn preset_of(h: &Host, d: &Data) -> Option<usize> {
|
||||
(i < h.dom.presets.borrow().len()).then_some(i)
|
||||
}
|
||||
|
||||
/// `DocumentPreset.typename`: a `TypeError` for a preset from an earlier run, as its settings give.
|
||||
fn preset_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
|
||||
Ok(text("DocumentPreset"))
|
||||
}
|
||||
|
||||
/// `DocumentPreset.toString()`: `[DocumentPreset]`, or a `TypeError` for a preset from an earlier
|
||||
/// run.
|
||||
fn preset_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
|
||||
Ok(text("[DocumentPreset]"))
|
||||
}
|
||||
|
||||
/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one.
|
||||
fn preset_enum(key: &str) -> Option<&'static str> {
|
||||
Some(match key {
|
||||
@@ -2061,7 +2127,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).len());
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
@@ -2102,7 +2168,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(item_at(h, doc, i)),
|
||||
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,
|
||||
@@ -2113,8 +2179,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2126,7 +2192,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_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));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -2138,7 +2204,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)) {
|
||||
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -2623,8 +2689,9 @@ struct Destination {
|
||||
|
||||
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
|
||||
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a
|
||||
/// clipping path cannot go below it.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
@@ -2657,6 +2724,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
|
||||
(parent, Some(target))
|
||||
}
|
||||
};
|
||||
// The clipping path stays at the bottom of its clip group or clipping layer. Moving the
|
||||
// clipping path below itself leaves it where it is.
|
||||
if how == Placement::Below
|
||||
&& (target != item.id || copy)
|
||||
&& d.node(parent).is_some_and(crate::doc::Node::clips)
|
||||
&& d.position(target).is_some_and(|(_, i, _)| i == 0)
|
||||
{
|
||||
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
|
||||
}
|
||||
if !editable(d, parent) {
|
||||
return Err(HostError::Error("the layer or group is hidden or locked".into()));
|
||||
}
|
||||
@@ -2711,7 +2787,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(arg(a, 1), Data::Undefined) {
|
||||
return Err(HostError::Type("move needs a relative object".into()));
|
||||
}
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
|
||||
if to.beside != Some(item.id) {
|
||||
place(h, item.doc, item.id, &to)?;
|
||||
}
|
||||
@@ -2752,7 +2828,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
None
|
||||
}
|
||||
target => Some(destination(h, item, target, arg(a, 2))?),
|
||||
target => Some(destination(h, item, target, arg(a, 2), true)?),
|
||||
};
|
||||
let id = atomically(h, |h| {
|
||||
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
|
||||
@@ -2784,17 +2860,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (before, after) = with_doc(h, item.doc, |_, st| {
|
||||
let at = st.doc.position(item.id);
|
||||
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
|
||||
(at.map(|(_, i, _)| i), count)
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
let top = i + 1 >= after;
|
||||
let unchanged = match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => top,
|
||||
_ => i == 0,
|
||||
};
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
@@ -2901,7 +2982,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS) {
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
@@ -2942,6 +3023,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(print::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
@@ -2951,8 +3033,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
new_preset(&h)
|
||||
});
|
||||
let mut members = vec![
|
||||
("typename".to_string(), typename_of("DocumentPreset"), typed("string")),
|
||||
("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])),
|
||||
("typename".to_string(), get(link, preset_typename), typed("string")),
|
||||
("toString".to_string(), method(link, preset_to_string), returns("string", &[])),
|
||||
];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k)))));
|
||||
HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) }
|
||||
@@ -2990,6 +3072,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
method(l, docs_add_document),
|
||||
returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]),
|
||||
),
|
||||
("addDocumentNoUI", method(l, docs_add_document_no_ui), returns("Document", &[("startupPreset", "string")])),
|
||||
("toString", class_text("Documents"), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, docs_at)),
|
||||
@@ -3020,8 +3103,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
@@ -3132,6 +3216,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.extend(print::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
@@ -3159,6 +3244,24 @@ mod tests {
|
||||
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
|
||||
}
|
||||
|
||||
/// A stop from putting back the selection or the active document is not hidden by the edit's
|
||||
/// own error, which a script could catch; ordinary errors keep their order.
|
||||
#[test]
|
||||
fn an_edit_gives_a_stop_ahead_of_its_own_error() {
|
||||
let error = |m: &str| HostError::Error(m.into());
|
||||
let stop = || HostError::Abort("stop".into());
|
||||
let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 };
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked()));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop()));
|
||||
// The edit's own stop comes first, and with no stop the edit's error does.
|
||||
assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into())));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit")));
|
||||
assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection")));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_lists_are_kept_for_several_documents() {
|
||||
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! - 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, throws `Cannot edit` with nothing changed.
|
||||
//! 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.
|
||||
//! - 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
|
||||
@@ -106,6 +108,18 @@ 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> {
|
||||
if !editable(&st.doc, id) {
|
||||
return Err(cannot_edit(id));
|
||||
}
|
||||
if super::on_locked_artboard(h, st, id) {
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path `d` names, which must still be in its document.
|
||||
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let item = item_of(h, d)?;
|
||||
@@ -234,7 +248,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, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// 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);
|
||||
@@ -246,15 +260,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
|
||||
flush(h)?;
|
||||
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
|
||||
let r = f(&mut subs);
|
||||
let (same, ok, aligned) = read_path(h, item, |st, _, pd| {
|
||||
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, editable(d, item.id), aligned)
|
||||
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
|
||||
})?;
|
||||
if !same {
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
refused?;
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
if aligned {
|
||||
flush(h)?;
|
||||
@@ -337,15 +349,12 @@ fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
|
||||
/// must be one the user could edit.
|
||||
/// must be one the user could edit ([`refuse_path_edit`]).
|
||||
/// 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> {
|
||||
let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id));
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.entry("ids").or_insert_with(|| json!([item.id.0]));
|
||||
}
|
||||
@@ -367,16 +376,18 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
let all = super::page_items(h, st);
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -396,7 +407,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -408,14 +419,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
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) };
|
||||
Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
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())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, 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()));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -434,18 +445,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, or one in a hidden or locked layer or group, stops it before anything is deleted.
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st);
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused)
|
||||
});
|
||||
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))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
|
||||
}
|
||||
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)));
|
||||
}
|
||||
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<_>>()})))?;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -859,18 +859,18 @@ fn typename(d: &Data) -> Option<&str> {
|
||||
// ---- Files ----
|
||||
|
||||
/// The path of the `File` argument `d`, or a `TypeError` naming the method.
|
||||
fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
|
||||
pub(super) fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> {
|
||||
vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File")))
|
||||
}
|
||||
|
||||
/// The error a refused path throws: the `File` error and the path.
|
||||
fn refused(message: &str, path: &str) -> HostError {
|
||||
pub(super) fn refused(message: &str, path: &str) -> HostError {
|
||||
HostError::Error(format!("{message}: {path}"))
|
||||
}
|
||||
|
||||
/// Runs `f` with the commands' reads and writes held to the script's own grants
|
||||
/// ([`super::super::files::Disk::exact`]).
|
||||
fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
|
||||
h.disk.borrow_mut().exact = true;
|
||||
let r = f();
|
||||
h.disk.borrow_mut().exact = false;
|
||||
@@ -889,7 +889,7 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
}
|
||||
|
||||
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
|
||||
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
|
||||
pub(super) fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
|
||||
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control
|
||||
Ok(())
|
||||
}),
|
||||
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
for id in ids.iter() {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
|
||||
@@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
|
||||
}
|
||||
|
||||
/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the
|
||||
/// document is unchanged.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// document is unchanged. Building the list again counts the page items it looks through against
|
||||
/// the run's host-call allowance.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return ids.clone();
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids: Vec<NodeId> = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Vec<NodeId> = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let ids = Rc::new(ids);
|
||||
*h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
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).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(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) };
|
||||
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.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 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 = frame_ids(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()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
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 ids = frame_ids(h, st)?;
|
||||
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();
|
||||
(ids, refused, on_locked)
|
||||
});
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
|
||||
|
||||
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostEr
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
|
||||
@@ -47,6 +47,10 @@
|
||||
//! run. An engine keeps no document and no run: its host functions reach the run through a link
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
//!
|
||||
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
|
||||
//! only after the run's changes are kept, for the frontend to send once the person approves them
|
||||
//! ([`printing`]).
|
||||
|
||||
pub mod actions;
|
||||
pub mod console;
|
||||
@@ -54,6 +58,7 @@ pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod printing;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
@@ -1405,6 +1410,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
|
||||
}
|
||||
|
||||
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
|
||||
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
|
||||
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
|
||||
command_crossing(host, id, params, false).map(|(_, value)| value)
|
||||
}
|
||||
|
||||
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
|
||||
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
|
||||
// Point changes that wait in the object model are written before any command runs.
|
||||
dom::flush(host)?;
|
||||
let session = host.session.clone();
|
||||
@@ -1430,10 +1446,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
};
|
||||
let mark = host.growth_mark();
|
||||
let crossed = host.charge_growth(objects, added).and_then(|()| {
|
||||
if !cross {
|
||||
return Ok(None);
|
||||
}
|
||||
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
|
||||
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
|
||||
host.charge_call(data_size(&data))?;
|
||||
Ok(data)
|
||||
Ok(Some(data))
|
||||
});
|
||||
// A command whose result does not reach the script is put back, like one that failed, and so is
|
||||
// the growth it was charged.
|
||||
@@ -1985,6 +2004,22 @@ impl Session {
|
||||
self.script_report.as_ref()
|
||||
}
|
||||
|
||||
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
|
||||
pub fn script_prints_waiting(&self) -> bool {
|
||||
!self.script_prints.is_empty()
|
||||
}
|
||||
|
||||
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
|
||||
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
|
||||
&self.script_prints
|
||||
}
|
||||
|
||||
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
|
||||
/// the frontend sends them or drops them ([`printing`]).
|
||||
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
|
||||
std::mem::take(&mut self.script_prints)
|
||||
}
|
||||
|
||||
/// The Script Console: the lines of this session's runs, oldest first.
|
||||
pub fn script_console(&self) -> &console::Console {
|
||||
&self.script_console
|
||||
@@ -2344,6 +2379,9 @@ impl Session {
|
||||
),
|
||||
linked: std::cell::OnceCell::new(),
|
||||
});
|
||||
// The printers the frontend listed are this run's alone, and a run may not print while
|
||||
// jobs an earlier run prepared still wait for the person.
|
||||
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
|
||||
*link.borrow_mut() = Some(host.clone());
|
||||
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
|
||||
Ok(args) => args,
|
||||
@@ -2641,6 +2679,12 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
|
||||
let prints = host.dom.take_prints();
|
||||
if !prints.is_empty() {
|
||||
report["prints"] = json!(prints.len());
|
||||
self.script_prints = prints;
|
||||
}
|
||||
let rejections = rejections_report(host, &job.realm);
|
||||
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
|
||||
o.insert("unhandledRejections".into(), Value::Array(rejections));
|
||||
@@ -2894,6 +2938,8 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
}
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
s.script_in_run = false;
|
||||
// A panic in a member that opened the fence for one command skips its own reset.
|
||||
s.script_unfenced = None;
|
||||
job.world.swap(s);
|
||||
s.depth = depth;
|
||||
s.sync_front_profiles();
|
||||
@@ -2960,6 +3006,8 @@ thread_local! {
|
||||
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: makes the next slice panic.
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes the next command a member runs past the script fence panic before it runs.
|
||||
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
|
||||
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
|
||||
//! prepares ([`PreparedPrint`]).
|
||||
//!
|
||||
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
|
||||
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
|
||||
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
|
||||
//! for the frontend, which sends them only when the person at the computer approves them.
|
||||
//!
|
||||
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
|
||||
//! a command line.
|
||||
//!
|
||||
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
|
||||
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
|
||||
|
||||
/// The most printers a run lists.
|
||||
pub const MAX_PRINTERS: usize = 256;
|
||||
/// The longest printer name a run lists, in bytes.
|
||||
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
|
||||
/// The most printer jobs one run prepares.
|
||||
pub const MAX_JOBS: usize = 4;
|
||||
/// The most sheets of paper the jobs of one run hold together, every copy counted.
|
||||
pub const MAX_SHEETS: u64 = 100;
|
||||
/// The most bytes the jobs of one run hold together.
|
||||
pub const MAX_JOB_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The printers a frontend lists for a run, by name, with the system's default printer.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Printers {
|
||||
names: Vec<String>,
|
||||
default: Option<usize>,
|
||||
/// The printer turns no landscape page to fit its paper: jobs are written upright
|
||||
/// (`file.print`'s `forPrinter`).
|
||||
pub for_printer: bool,
|
||||
}
|
||||
|
||||
impl Printers {
|
||||
/// The printers of `list` (name, whether it is the default), in its order. A name that is
|
||||
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`] or holds a control character is left out, and
|
||||
/// so is a name that repeats an earlier one, though its default mark is kept. Every printer
|
||||
/// after the first [`MAX_PRINTERS`] is left out, except the default printer, which takes the
|
||||
/// last place when it comes later.
|
||||
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
let mut default = None;
|
||||
for (name, is_default) in list {
|
||||
let full = names.len() >= MAX_PRINTERS;
|
||||
if full && default.is_some() {
|
||||
break;
|
||||
}
|
||||
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) {
|
||||
continue;
|
||||
}
|
||||
if let Some(i) = names.iter().position(|n| *n == name) {
|
||||
if is_default && default.is_none() {
|
||||
default = Some(i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if full {
|
||||
if is_default && let Some(last) = names.last_mut() {
|
||||
*last = name;
|
||||
default = Some(MAX_PRINTERS - 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_default && default.is_none() {
|
||||
default = Some(names.len());
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
Self { names, default, for_printer }
|
||||
}
|
||||
|
||||
/// The printers' names.
|
||||
pub fn names(&self) -> &[String] {
|
||||
&self.names
|
||||
}
|
||||
|
||||
/// The system's default printer, when the list holds it.
|
||||
pub fn default_name(&self) -> Option<&str> {
|
||||
self.default.map(|i| self.names[i].as_str())
|
||||
}
|
||||
|
||||
/// Whether the list holds a printer named exactly `name`.
|
||||
pub fn has(&self, name: &str) -> bool {
|
||||
self.names.iter().any(|n| n == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PreparedPrint {
|
||||
/// The printer, by the name the run's list gave it.
|
||||
pub printer: String,
|
||||
/// The title of the document it prints, the job's name in the print queue.
|
||||
pub title: String,
|
||||
pub pdf: Vec<u8>,
|
||||
/// The sheets of paper it prints, every copy counted.
|
||||
pub sheets: u64,
|
||||
}
|
||||
Reference in new issue
Block a user