Merge main into feat/scripts-text-paint

This commit is contained in:
dotCooCoo committed 2026-11-25 10:23:06 -08:00
commit ae19db09d6
304 files changed
+19030 -1648

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export EPS",
[],
None,
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default; paper white fills and strokes knock out with document.setup discardWhiteOverprint; white linked to a spot swatch that has a color, at a tint above 0%, still overprints)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
has_doc,
export_eps
)]
+7
View File
@@ -849,6 +849,13 @@ impl ReadFile {
r
}
/// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a
/// file that stopped for its profile question, or the linked files and the type of an answered
/// one?
pub fn read_left(&self) -> bool {
self.rest.is_some() || self.links_left.is_some()
}
/// The rest of [`read_for_open_asking`], once: the color management policies with the profile
/// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked
/// files and the type. The app runs it off the UI thread once the question is answered.
+18
View File
@@ -212,11 +212,29 @@ fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() {
fn overprints_are_kept_or_discarded() {
let mut s = session(100.0, 100.0, 1);
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": true})).unwrap();
let kept = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(kept.contains("true op\n"), "{kept}");
let dropped = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none", "overprints": "discard"})).unwrap()));
assert!(!dropped.contains("true op"));
// A white fill or stroke that overprints knocks out with Discard White Overprint (on by
// default), and overprints without it, as in PDF export.
let white = json!({"c": 0, "m": 0, "y": 0, "k": 0});
let filled = [json!({"ids": [id], "color": white}), json!({"ids": [id], "none": true})];
let stroked = [json!({"ids": [id], "none": true}), json!({"ids": [id], "color": white})];
for (i, [fill, stroke]) in [filled, stroked].iter().enumerate() {
s.execute("paint.setFill", fill).unwrap();
s.execute("paint.setStroke", stroke).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": i == 0, "overprintStroke": i == 1})).unwrap();
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
let knocked_out = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(!knocked_out.contains("true op"), "{i}: {knocked_out}");
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
let overprinted = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(overprinted.contains("true op\n"), "{i}: {overprinted}");
}
}
#[test]
+322 -53
View File
@@ -43,6 +43,11 @@
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
//!
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
//! also given the parts of the active document it names in `_context.document`, whether or not
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
@@ -52,10 +57,13 @@ use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
use crate::store::StoreTurn;
use crate::store::{PluginLoad, StoreTurn};
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
mod context;
pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
match e {
@@ -102,6 +110,9 @@ pub fn describe(p: &Plugin) -> Value {
if !m.inputs.is_empty() {
v["inputs"] = json!(m.inputs);
}
if !m.context.is_empty() {
v["context"] = json!(m.context);
}
if m.paint_output {
v["paintOutput"] = json!(true);
}
@@ -254,15 +265,25 @@ impl FilterRun {
params["_context"]["mode"] = json!("command");
params["_context"]["command"] = json!(cmd.id);
}
// The parts of the document its manifest asks for (`context`), selection or not. Each row
// costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions.
let sections = m.context_sections();
let mut charged = 0;
if !sections.is_empty() && may.contains(&Permission::DocRead) {
let given = context::document_context(st, &sections, c)?;
params["_context"]["document"] = given.value;
charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM);
}
let params = serde_json::to_vec(&params).map_err(|e| bad(c, e.to_string()))?;
// The input and the parameters may use half the plug-in's memory together.
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
let limits = match s.prefs.plugin_instruction_budget {
let mut limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
limits.fuel_base = limits.fuel_base.saturating_sub(charged);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
@@ -296,11 +317,17 @@ impl FilterRun {
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
/// it was made, less what its document context costs.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// The parameters it hands the plug-in, `_context` included.
#[cfg(test)]
pub(crate) fn params_json(&self) -> Value {
serde_json::from_slice(&self.params).unwrap_or(Value::Null)
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
/// session ([`FilterRun::run_with_calls`]).
pub fn calls(&self) -> bool {
@@ -1010,12 +1037,16 @@ thread_local! {
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
/// Tests: runs once in the next `plugin.reload` on this thread after its load started and before
/// it installs, as another session loading a folder in between would.
pub(crate) static BEFORE_RELOAD_INSTALLS: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
/// Held by `plugin.install` from its first read of the grant until the store holds what it
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
/// other across sessions.
/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins
/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run
/// one after the other across sessions. It is not held while the modules load, so a session's
/// plug-in commands don't wait for another session's loads.
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
@@ -1033,6 +1064,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
}
}
/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting.
pub(crate) fn try_hold_plugin_changes() -> Option<std::sync::MutexGuard<'static, ()>> {
match PLUGIN_CHANGES.try_lock() {
Ok(held) => Some(held),
Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()),
Err(std::sync::TryLockError::WouldBlock) => None,
}
}
/// Tests: whether [`PLUGIN_CHANGES`] could be taken now.
#[cfg(test)]
pub(crate) fn plugin_changes_free() -> bool {
!matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock))
}
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
@@ -1282,31 +1328,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
}
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
/// happened.
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no
/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next
/// [`sync_prefs`] loads the folder again.
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64, bool);
/// The [`FolderRecord`] of the plug-in folder last loaded.
static FOLDER: Mutex<Option<FolderRecord>> = Mutex::new(None);
/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`]
/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and
/// a `plugin.reload` keeps its report only when no load started after it.
static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
/// (startup, `prefs.set`). Native only.
pub(crate) fn sync_prefs(s: &Session) {
let folder = s.prefs.plugins_folder.trim();
/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the
/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it
/// returns once the folder's plug-ins are installed, also while another session is still loading
/// the same folder. Native only.
pub(crate) fn sync_prefs(s: &mut Session) {
let folder = s.prefs.plugins_folder.trim().to_string();
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
if folder.is_empty() || safe_mode::active() {
return;
}
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
// This session's own load of the folder, still running, is waited for unless loads go on in the
// background.
if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) {
if !s.plugin_loads_in_background {
s.finish_plugin_loads();
}
return;
}
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
let token = {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A folder another session is still loading is loaded here too: that load may end with its
// session, and this one returns once its own plug-ins are installed.
// A load in which a file found no thread to load it is tried again.
if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) {
return;
}
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
token
};
let load = start_folder(s, &folder, Some(token));
s.queue_plugin_load(PluginLoad::Folder(load));
}
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
/// loaded, it is forgotten, so setting the preference to it again loads it again.
pub(crate) fn forget_prefs_folder(old: &str) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) {
*last = None;
}
}
@@ -1326,42 +1402,232 @@ pub fn load_prefs_folder(s: &mut Session) {
sync_prefs(s);
}
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
/// disabled list when loading changed it.
/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none.
#[cfg(not(target_arch = "wasm32"))]
fn load_folder(s: &Session, folder: &str) -> Value {
if let Err(e) = crate::file_access::check_read(folder) {
return json!({"folder": folder, "error": e});
}
// A file in it may be a link to one elsewhere.
let allow = |f: &std::path::Path| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
};
// A `plugin.install` in another session or process finishes writing the store first. When the
// store can't be locked, the folder still loads, and the store isn't written.
let _held = hold_plugin_changes();
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
Ok(r) => {
for id in &r.loaded {
s.attach_plugin_storage(&turn, id);
}
if r.disabled_changed {
s.store_disabled_plugins_in(&turn);
}
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
type FolderModules = registry::FolderLoad;
#[cfg(target_arch = "wasm32")]
type FolderModules = std::convert::Infallible;
/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the
/// modules load and [`end_folder`] ends.
pub(crate) struct FolderPending {
folder: String,
/// The plug-in store whose grants it loads with.
store: Option<std::path::PathBuf>,
/// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last
/// loaded ([`sync_prefs`]).
record: Option<u64>,
/// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a
/// load started after it.
reload: bool,
/// The modules loading, or the report of a folder that can't be loaded; `None` once ended.
load: Option<std::result::Result<FolderModules, Value>>,
/// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]).
canceled: bool,
}
impl FolderPending {
/// Whether every module has been installed or reported.
pub(crate) fn done(&self) -> bool {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.done(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
Err(e) => json!({"folder": folder, "error": e.to_string()}),
}
/// Starts the modules loading, unless they started already.
pub(crate) fn start(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.start();
}
}
/// The installs and removals its modules are checked against (`None`: the folder couldn't be
/// listed, or the load ended).
pub(crate) fn changes(&self) -> Option<&registry::LoadChanges> {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// [`FolderPending::changes`], to adopt an earlier load's.
pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes_mut()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// Whether something can be installed or reported now, without waiting.
pub(crate) fn ready(&mut self) -> bool {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.ready(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
}
/// Waits until the next module in file-name order has loaded or failed.
pub(crate) fn wait(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.wait();
}
}
/// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`]
/// then keeps no report as the folder last loaded.
pub(crate) fn cancel(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.cancel();
}
self.canceled = true;
}
/// Whether it is a load of `folder` with the plug-in store `store`.
pub(crate) fn loads(&self, folder: &str, store: &Option<std::path::PathBuf>) -> bool {
self.folder == folder && self.store == *store
}
}
impl Drop for FolderPending {
/// A load dropped before it ended (its session closed) leaves no folder reported as loading, so
/// the next session that applies the preference loads it.
fn drop(&mut self) {
if let Some(token) = self.record.filter(|_| self.load.is_some()) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
*last = None;
}
}
}
}
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
#[cfg(not(target_arch = "wasm32"))]
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let pending =
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
if let Err(e) = crate::file_access::check_read(folder) {
return pending(Err(json!({"folder": folder, "error": e})));
}
// A file in it may be a link to one elsewhere. Each file is checked again on its worker
// thread, in the scope in force here (the automation roots and the script gate), as the
// folder itself was.
let scope = crate::file_access::ScopeHandle::capture_now();
let allow = move |f: &std::path::Path| {
scope.clone().run(|| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
})
};
// The modules start loading once the loads queued before them are done.
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
}
#[cfg(target_arch = "wasm32")]
fn load_folder(_: &Session, folder: &str) -> Value {
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
}
/// Installs what `load` has loaded so far, in file-name order up to the first module still
/// loading, without waiting: those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once). Runs while
/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process
/// finishes writing the store first; when the store can't be locked, the folder still installs,
/// and the store isn't written.
pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut load.load
&& !load.done()
{
for id in load.install_ready(s.plugin_folder_approver()) {
s.attach_plugin_storage(turn, &id);
}
// A disabled plug-in's file matched by its id is saved in the same turn.
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
load.disabled_saved();
}
}
#[cfg(target_arch = "wasm32")]
let _ = (s, load, turn);
}
/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
let r = modules.finish();
if r.disabled_changed {
s.store_disabled_plugins_in(turn);
}
let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>();
(json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread)
}
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match never {},
Some(Err(report)) => (report, false),
None => (Value::Null, false),
};
if let Some(token) = load.record {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no
// folder reported, so the next session that applies the preference loads it. A
// `plugin.reload`'s report replaces the record unless a load started after it, or the
// folder couldn't be loaded.
let current = if load.reload {
FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none()
} else {
last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token)
};
if current {
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) };
}
}
report
}
/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is
/// kept as the folder last loaded unless a load started after this one.
fn load_folder_now(s: &mut Session, folder: &str) -> Value {
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut load = start_folder(s, folder, Some(token));
load.reload = true;
#[cfg(test)]
if let Some(between) = BEFORE_RELOAD_INSTALLS.take() {
between();
}
s.finish_plugin_load(PluginLoad::Folder(load))
}
/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no
/// loader thread to load it.
#[cfg(test)]
pub(crate) fn folder_found_no_thread() {
if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
record.4 = true;
}
}
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1373,11 +1639,12 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
if folder.is_empty() {
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
}
let report = load_folder(s, &folder);
// Loads started earlier install first, so this one's plug-ins replace theirs.
s.finish_plugin_loads();
let report = load_folder_now(s, &folder);
if let Some(e) = report.get("error").and_then(Value::as_str) {
return Err(EngineError::Other(e.to_string()));
}
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
Ok(report)
}
@@ -1426,7 +1693,7 @@ fn shown_report(mut report: Value) -> Value {
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
Ok(
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
@@ -1434,13 +1701,15 @@ fn list(_: &mut Session, _: &Value) -> Result<Value> {
}
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet.
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
let pending: Vec<Value> = safe_mode::previous().iter().map(shown_item).collect();
Ok(json!({
"active": safe_mode::active(),
"source": safe_mode::source().map(safe_mode::Source::name),
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
"pendingItem": pending.first(),
"pendingItems": pending,
}))
}
@@ -1579,7 +1848,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1651,7 +1920,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Safe Mode",
[],
None,
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command",
always,
safe_mode_state
),
+147
View File
@@ -0,0 +1,147 @@
//! A plug-in run's document context (`_context.document`): the parts of the active document its
//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or
//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an
//! object, a file path or a link target.
use serde_json::{Value, json};
use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind};
use vectorcraft_plugins::ContextSection;
use super::super::{Result, bad};
use crate::DocState;
/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds.
pub const MAX_CONTEXT_ITEMS: usize = 10_000;
/// Most bytes the rows of a document context take as JSON.
pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024;
/// Instructions each row costs: they come off the run's instruction budget.
pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000;
/// A document context, and the rows it holds.
pub(super) struct DocumentContext {
pub value: Value,
pub items: usize,
}
/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key
/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or
/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case.
pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result<DocumentContext> {
let d = &st.doc;
let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() };
let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect());
let mut items = 0;
for s in sections {
items += match s {
ContextSection::Settings => 0,
ContextSection::Artboards => d.artboards.len(),
ContextSection::Layers => layers.len(),
ContextSection::Swatches => swatches().count(),
};
}
let too_large = || {
bad(
c,
format!(
"the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes"
),
)
};
if items > MAX_CONTEXT_ITEMS {
return Err(too_large());
}
let mut bytes = 0usize;
let mut row = |v: Value| -> Result<Value> {
bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1));
if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) }
};
let active = active_artboard(st);
let mut out = json!({"revision": st.revision});
for s in sections {
let value = match s {
ContextSection::Settings => {
let board = active.and_then(|i| d.artboards.get(i));
row(json!({
"name": st.title(),
"colorMode": match d.color_mode {
ColorMode::Rgb => "rgb",
ColorMode::Cmyk => "cmyk",
},
"units": d.units.label(),
"width": board.map(|a| a.rect.width()),
"height": board.map(|a| a.rect.height()),
"bleed": d.setup.bleed,
"rasterEffectsPpi": d.raster_ppi(),
"activeArtboard": board.map(|a| a.id),
}))?
}
ContextSection::Artboards => {
let rows = d.artboards.iter().enumerate().map(|(i, a)| {
let r = a.rect;
row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Layers => {
let rows = layers.iter().map(|l| {
let n = l.node;
row(json!({
"id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(),
"visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(),
"sublayers": l.sublayers, "current": st.active_layer == Some(n.id),
}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Swatches => {
let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g)));
Value::Array(rows.collect::<Result<_>>()?)
}
};
out[s.name()] = value;
}
Ok(DocumentContext { value: out, items })
}
/// Is `n` a layer or sublayer?
fn is_layer(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { .. })
}
/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the
/// node's own name and flags.
struct LayerRow<'a> {
node: &'a Node,
/// Its parent layer's id; `None` for a top-level layer.
parent: Option<u64>,
/// 0 for a top-level layer, 1 for its sublayers, and so on.
depth: usize,
color: LayerColor,
template: bool,
/// The sublayers it holds directly.
sublayers: usize,
}
/// Every layer and sublayer of `d`, depth first in document order (bottom first within each
/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's.
fn layer_rows(d: &vectorcraft_doc::Document) -> Vec<LayerRow<'_>> {
let mut out = Vec::new();
let mut stack: Vec<(&Node, Option<u64>, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect();
while let Some((node, parent, depth)) = stack.pop() {
let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue };
let sublayers = children.iter().filter(|c| is_layer(c)).count();
stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1)));
out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers });
}
out
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first; `None` with no artboards.
fn active_artboard(st: &DocState) -> Option<usize> {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
}
+5
View File
@@ -472,6 +472,11 @@ impl RecoveryStore for FolderStore {
Self::create_area(dir)?;
Self::own_area(dir)?;
}
// A read refuses a link (`read`), and a write must too: the atomic writer replaces the
// target of a link, which would put the copy over a file outside the store.
if std::fs::symlink_metadata(&f).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(format!("{}: not a plain file", f.display()));
}
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
}
fn remove(&self, name: &str) -> std::result::Result<(), String> {
+17 -7
View File
@@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result<Value> {
Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?],
None => d.swatch_groups.iter().collect(),
};
// The built-in Registration swatch lists after None, as the panel shows it.
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None));
let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name))));
let swatches: Vec<Value> = ungrouped.chain(grouped).collect();
let swatches: Vec<Value> = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect();
let groups: Vec<Value> =
groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
Ok(json!({"swatches": swatches, "groups": groups}))
}
/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is
/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None,
/// as the panel shows it), then those of `groups`.
pub(super) fn listed_swatches<'a>(
d: &'a Document,
ungrouped: bool,
groups: Vec<&'a SwatchGroup>,
) -> impl Iterator<Item = (&'a Swatch, Option<&'a str>)> + 'a {
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None));
let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str()))));
ungrouped.chain(grouped)
}
fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
s.edit("Sort Swatches", |d, _| {
// [None] and other bracketed specials stay first, like the reference app.