From c664ce630b82faae1a6356c78a09c278252f8108 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:20:07 -0800 Subject: [PATCH 1/2] =?UTF-8?q?Plug-ins:=20importers=20whose=20manifest=20?= =?UTF-8?q?sets=20place=20also=20read=20files=20for=20File=20=E2=80=BA=20P?= =?UTF-8?q?lace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An importer plug-in with "place": true in its manifest now reads its files for File › Place as well as File › Open. file.place, file.place.info and file.place.queue take importer and params; without importer, a file no built-in format reads goes to the first placing importer by id that lists its extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size before it is read) with _context.mode "place", and its objects, guides left out, become one group named after the file, as one undo step, embedded. A decline, invalid output, a trap or Cancel places nothing. - The Place dialog lists placing importers' extensions under "All placeable files" and in a filter named after each importer. - On the web, a placing importer's file dropped on the canvas is placed. - A file placed with a named importer skips the text, PDF, DXF and PSD import options. - document.formats and plugin.list mark placing importers with place: true; place on any other kind is refused at install. Docs: docs/plugins.md, docs/mcp.md, docs/gaps.md, docs/target-app-parity.md. --- apps/vectorcraft-web/src/web.rs | 8 +- apps/vectorcraft/src/host_services.rs | 2 +- crates/engine/src/cmd/fileio.rs | 6 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/formats.rs | 71 ++++- crates/engine/src/cmd/fileio/importer.rs | 211 +++++++++---- crates/engine/src/cmd/place.rs | 37 ++- crates/engine/src/cmd/plugin.rs | 5 +- crates/engine/tests/plugin_place.rs | 282 ++++++++++++++++++ crates/plugins/src/import.rs | 47 ++- crates/plugins/src/manifest.rs | 36 +++ crates/ui-egui/src/dialogs/tests.rs | 1 + .../src/dialogs/tests_plugin_import.rs | 48 +++ crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/place.rs | 15 +- docs/gaps.md | 3 + docs/mcp.md | 8 +- docs/plugins.md | 41 ++- docs/target-app-parity.md | 1 + 43 files changed, 781 insertions(+), 93 deletions(-) create mode 100644 crates/engine/tests/plugin_place.rs diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 6d9e0cadd5..9e23e4044f 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -482,10 +482,12 @@ fn services( let inbox = picked.clone(); let ctx = place_ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let dialog = - fileio::place_filters().fold(rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { + let dialog = fileio::place_dialog_filters().fold( + rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), + |d, (name, exts)| { d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); + }, + ); let Some(files) = dialog.pick_files().await else { return; }; diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 3efdb9f93f..ca9558daa5 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -75,7 +75,7 @@ fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { - return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { + return fileio::place_dialog_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), &open_extensions(exts, CASE_SENSITIVE_FILTERS), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 4fcb2bf4fc..f6ee2beb31 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -37,7 +37,7 @@ mod encode; pub mod eps; mod export; pub(crate) mod imagemap; -mod importer; +pub(crate) mod importer; pub mod jxlread; mod legacy_ai; mod load; @@ -167,8 +167,8 @@ use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable}; pub use formats::{ DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions, - open_filters, opens_as_other, opens_with_importer, place_filters, plugin_formats, read_extensions, readable_format, readable_format_for_name, - titled_for_export, writable_format, + open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions, + readable_format, readable_format_for_name, titled_for_export, writable_format, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a41831b200..0c03b1ea11 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}", always, formats ), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0db990ad4c..0272bab874 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -737,11 +737,26 @@ fn format_filters() -> impl Iterator bool { let ext = extension(name); - !ext.is_empty() && !PLACE_EXTS.contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + !ext.is_empty() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::for_extension(&ext).is_empty() + && !places_with_importer(name) +} + +/// Whether File › Place places a file named `name` with an importer plug-in when no built-in format +/// reads its content: no built-in format reads its extension, and an installed importer whose manifest +/// sets `place` lists it. +pub fn places_with_importer(name: &str) -> bool { + let ext = extension(name); + !ext.is_empty() + && readable_format(&ext).is_none() + && !PLACE_EXTS.contains(&ext.as_str()) + && !vectorcraft_plugins::import::placing(&ext).is_empty() } /// Whether File › Open opens a file of extension `ext` (lower case) as something other than a @@ -871,6 +886,53 @@ pub fn place_filters() -> impl Iterator ImporterPart { + use vectorcraft_plugins::{import, registry}; + static MADE: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + let revision = registry::revision(); + if let Some((r, part)) = made.as_ref() + && *r == revision + { + return part.clone(); + } + let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec(); + let mut filters = Vec::new(); + for p in import::installed().into_iter().filter(|p| p.manifest().place) { + let m = p.manifest(); + let own: Vec<&'static str> = + m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect(); + if own.is_empty() { + continue; + } + for &e in &own { + if !exts.contains(&e) { + exts.push(e); + } + } + let own: &'static [&'static str] = Box::leak(own.into_boxed_slice()); + filters.push((registry::intern(&m.name), own)); + } + let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) }; + let part = (exts, filters); + *made = Some((revision, part.clone())); + part +} + +/// File › Place's own dialog filters: [`place_filters`], with the extensions of the installed +/// importer plug-ins that place their files in "All placeable files" and one filter per such +/// importer after the others, under its name ([`places_with_importer`]). Pickers that relink an +/// image use [`place_filters`]. +pub fn place_dialog_filters() -> impl Iterator { + let (all, importers) = importer_place_part(); + std::iter::once(("All placeable files", all)).chain(place_filters().skip(1)).chain(importers) +} + /// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in /// one, else one a plug-in adds ([`plugin_formats`]), an exporter's before an importer's for an /// extension both list. A built-in format keeps its extension, so an exporter or importer that @@ -1021,6 +1083,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result { let mut v = f.to_json(); if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { v["plugin"] = json!(id); + if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) { + v["place"] = json!(true); + } } v }; diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 3ba6c6fa19..53af9314a4 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -1,58 +1,118 @@ -//! `document.open` of the files importer plug-ins read ([`vectorcraft_plugins::import`]). +//! `document.open` and `file.place` of the files importer plug-ins read +//! ([`vectorcraft_plugins::import`]). //! //! A file opens with an importer when `importer` names one (its format id, `plugin.`), which //! must list the file's extension, or when no built-in format reads the file, by its content or by //! its extension, and an importer lists its extension (the one whose id sorts first, when several //! do). A built-in format that can't read a damaged file reports its own error: the file is not -//! handed to an importer instead. Place reads only the built-in formats. +//! handed to an importer instead. File › Place uses an importer by the same rules, among the +//! importers whose manifests set `place` ([`named_for_place`], [`for_place`]). //! //! The importer is given the file's bytes, at most [`import::MAX_INPUT_BYTES`] of them: a file //! named by `path` that only an importer can read is read no further than that. Its objects become -//! a new document whose artboard is their bounds, and nothing opens when the importer fails, -//! declines, is cancelled or returns objects that don't pass the checks a filter's output does. +//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing +//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't +//! pass the checks a filter's output does. use std::sync::Arc; use serde_json::Value; -use vectorcraft_doc::{Document, MAX_COORD}; +use vectorcraft_doc::{Document, MAX_COORD, NodeId}; use vectorcraft_geom::Rect; -use vectorcraft_plugins::{Plugin, export, import, objects}; +use vectorcraft_plugins::import::Mode; +use vectorcraft_plugins::{Manifest, Plugin, export, import, objects}; use super::super::{Result, bad, str_param}; -use super::load::{Loaded, detect, file_name}; -use super::{err, extension, file_stem, format}; +use super::load::{Loaded, Source, detect, file_name}; +use super::{Format, err, extension, file_stem, format}; use crate::EngineError; const C: &str = "document.open"; -/// The importer `document.open`'s params `p` name (`importer`), if any; a value that isn't a -/// string is an error. -fn named(p: &Value) -> Result> { +/// The importer command `cmd`'s params `p` name (`importer`), if any; a value that isn't a string +/// is an error. +fn named<'a>(p: &'a Value, cmd: &str) -> Result> { match p.get("importer").filter(|v| !v.is_null()) { None => Ok(None), - Some(v) => v.as_str().map(Some).ok_or_else(|| bad(C, "`importer` must be a plug-in format id (see document.formats)")), + Some(v) => v.as_str().map(Some).ok_or_else(|| bad(cmd, "`importer` must be a plug-in format id (see document.formats)")), } } +/// Checks that importer `m` lists the extension of the file `name`: else command `cmd`'s error, +/// which names the extensions it lists. +fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> { + if m.extensions.contains(&extension(name)) { + return Ok(()); + } + let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); + Err(bad(cmd, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))) +} + /// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the /// one `importer` names, which must list the file's extension; else, when no built-in format reads /// the file, the first installed importer that lists its extension; else `None`. pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result>> { - let ext = extension(name); - if let Some(id) = named(p)? { + if let Some(id) = named(p, C)? { let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?; - let m = plugin.manifest(); - if !m.extensions.contains(&ext) { - let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); - let exts: Vec = m.extensions.iter().map(|e| format!(".{e}")).collect(); - return Err(bad(C, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name)))); - } + check_extension(C, plugin.manifest(), name)?; return Ok(Some(plugin)); } if detect(name, bytes).is_some() { return Ok(None); } - Ok(import::for_extension(&ext).into_iter().next()) + Ok(import::for_extension(&extension(name)).into_iter().next()) +} + +/// The importer `file.place`'s params `p` name (`importer`) for the file `name`, which must set +/// `place` in its manifest and list the file's extension (errors of command `cmd`); `None` when `p` +/// names none. +pub(crate) fn named_for_place(name: &str, p: &Value, cmd: &str) -> Result>> { + let Some(id) = named(p, cmd)? else { return Ok(None) }; + let plugin = import::named(id).map_err(|e| bad(cmd, e.to_string()))?; + let m = plugin.manifest(); + if !m.place { + return Err(match import::not_placing(m) { + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => bad(cmd, e.to_string()), + }); + } + check_extension(cmd, m, name)?; + Ok(Some(plugin)) +} + +/// The importer File › Place uses for the file `name` when no built-in format reads it: the first +/// installed importer, by plug-in id, whose manifest sets `place` and that lists its extension. +pub(crate) fn for_place(name: &str) -> Option> { + import::placing(&extension(name)).into_iter().next() +} + +/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no +/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer +/// that reads for `mode` lists it. +fn importer_reads(ext: &str, mode: Mode) -> bool { + super::readable_format(ext).is_none() + && match mode { + Mode::Import => !import::for_extension(ext).is_empty(), + Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(), + } +} + +/// The error of the file `name`, past [`import::MAX_INPUT_BYTES`], which an importer would read +/// for `mode`. +fn too_large(name: &str, mode: Mode) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {}", file_name(name), import::too_large())), + Mode::Place => failed(Mode::Place, name, import::too_large()), + } +} + +/// The error of the file `name`, which importer `e` couldn't read for `mode`. +fn failed(mode: Mode, name: &str, e: impl std::fmt::Display) -> EngineError { + match mode { + Mode::Import => err(format!("can't open `{}`: {e}", file_name(name))), + Mode::Place => err(format!("can't place `{}`: {e}", file_name(name))), + } } /// How much of a file [`detect`] is given: more than its content checks read. @@ -61,14 +121,17 @@ const SNIFF_BYTES: usize = 64 << 10; /// Refuses `document.open`'s `dataBase64` in `p` before it is decoded when it holds a file past /// [`import::MAX_INPUT_BYTES`] that only an importer reads, by the rule of `read_path`. pub(super) fn check_data(p: &Value) -> Result<()> { + check_data_for(p, Mode::Import, C) +} + +/// [`check_data`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { let Some(b64) = str_param(p, "dataBase64") else { return Ok(()); }; let name = str_param(p, "name").unwrap_or("Untitled"); - let ext = extension(name); - let explicit = named(p)?.is_some(); - let built_in = !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()); - if built_in || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { + let explicit = named(p, cmd)?.is_some(); + if (!explicit && !importer_reads(&extension(name), mode)) || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 { return Ok(()); } if !explicit { @@ -78,7 +141,7 @@ pub(super) fn check_data(p: &Value) -> Result<()> { return Ok(()); } } - Err(err(format!("can't open `{}`: {}", file_name(name), import::too_large()))) + Err(too_large(name, mode)) } /// The file at `path` for `document.open`'s params `p`. A file that only an importer reads (one @@ -86,11 +149,15 @@ pub(super) fn check_data(p: &Value) -> Result<()> { /// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a /// built-in format and no importer was named, which is read whole as any other file is. A file past /// the limit that isn't read whole is reported from its size, without reading it. -#[cfg(not(target_arch = "wasm32"))] pub(super) fn read_path(path: &str, p: &Value) -> Result> { - let ext = extension(path); - let explicit = named(p)?.is_some(); - if !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) { + read_path_for(path, p, Mode::Import, C) +} + +/// [`read_path`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result> { + let explicit = named(p, cmd)?.is_some(); + if !explicit && !importer_reads(&extension(path), mode) { return super::read_file(path); } let head = super::read_file_head(path, SNIFF_BYTES)?; @@ -100,57 +167,83 @@ pub(super) fn read_path(path: &str, p: &Value) -> Result> { if !explicit && detect(path, &head).is_some() { return super::read_file(path); } - let too_large = || err(format!("can't open `{}`: {}", file_name(path), import::too_large())); let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); if size > import::MAX_INPUT_BYTES as u64 { - return Err(too_large()); + return Err(too_large(path, mode)); } // The file can grow after the size is read. let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?; if file.len() > import::MAX_INPUT_BYTES { - return Err(too_large()); + return Err(too_large(path, mode)); } Ok(file) } #[cfg(target_arch = "wasm32")] -pub(super) fn read_path(path: &str, _: &Value) -> Result> { +fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { super::read_file(path) } +/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except +/// that a file an importer would place (one `importer` names, or an extension no built-in format +/// reads that an importer which places its files lists) is read, or decoded, only when it is at +/// most [`import::MAX_INPUT_BYTES`] long. +pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result> { + match str_param(p, "path") { + Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }), + None => { + check_data_for(p, Mode::Place, cmd)?; + super::source(p, cmd) + } + } +} + +/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params +/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its +/// objects on its first layer, their ids, and its warnings. +fn read( + name: &str, + bytes: &[u8], + plugin: &Plugin, + p: &Value, + cmd: &str, + mode: Mode, +) -> Result<(&'static Format, Document, Vec, Vec)> { + let m = plugin.manifest(); + let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; + let (ext, stem) = (extension(name), file_stem(name)); + let source = import::Source { extension: &ext, name: &stem }; + let params = p.get("params").cloned().unwrap_or(Value::Null); + let imported = import::run_as(plugin, bytes, ¶ms, source, mode).map_err(|e| match e { + vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, + vectorcraft_plugins::Error::Params(why) => bad(cmd, why), + e => failed(mode, name, e), + })?; + let mut doc = Document::new(1.0, 1.0); + let layer = doc.layers.first().map(|l| l.id); + let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n); + let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?; + Ok((format, doc, ids, imported.warnings)) +} + +/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params +/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its +/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`. +pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec)> { + let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?; + Ok((format, doc, warnings)) +} + /// The file `name` holding `bytes` read by importer `plugin` with `document.open`'s params `p` /// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what /// the importer returned. pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result { - let m = plugin.manifest(); - let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?; - let (ext, stem) = (extension(name), file_stem(name)); - let source = import::Source { extension: &ext, name: &stem }; - let params = p.get("params").cloned().unwrap_or(Value::Null); - let imported = import::run(plugin, bytes, ¶ms, source).map_err(|e| match e { - vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, - vectorcraft_plugins::Error::Params(why) => bad(C, why), - e => err(format!("can't open `{}`: {e}", file_name(name))), - })?; - let mut doc = Document::new(1.0, 1.0); - let layer = doc.layers.first().map(|l| l.id); - let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n); - let ids = - objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?; + let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?; if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) { board.rect = artboard_rect(bounds); } doc.title = file_name(name); - Ok(Loaded { - doc, - format, - warnings: imported.warnings, - restored: false, - converted: false, - preview_only: false, - editing_data: false, - native_pdf_compatible: None, - }) + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) } /// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index fef99cc9c3..d4146b741c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -32,6 +32,9 @@ //! - A VectorCraft document placed from a file with Link (the default) becomes a placed document: //! one locked object showing the artboard `page`, linked to the file and read again when it //! changes ([`document`]); without Link, an editable copy of its art. +//! - A file an importer plug-in whose manifest sets `place` reads (the one `importer` names, else +//! the first by id that lists the extension of a file no built-in format reads) becomes one group +//! of the objects it returned, embedded ([`fileio::importer`]). //! //! The art lands centred on `at`, fitted into `rect`, or (Replace) where the replaced object was, //! with its transform; Template puts it on a new template layer. The images, symbols, patterns and @@ -82,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -190,10 +193,14 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB -/// file's slices go to `slices`. +/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one +/// no built-in format reads) is read by it ([`plugin_art`]). fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::source(p, cmd)?; + let src = fileio::importer::place_source(p, cmd)?; let name = fileio::file_name(src.name); + if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } // An Affinity file is recognised by its signature, whatever its name says. if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) { let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?; @@ -228,8 +235,12 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let format = fileio::detect(src.name, &src.bytes) - .ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?; + let Some(format) = fileio::detect(src.name, &src.bytes) else { + return match fileio::importer::for_place(src.name) { + Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), + None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), + }; + }; let page = match p.get("page") { None => 1, Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(cmd, "page must be a whole number from 1"))? as usize, @@ -385,6 +396,20 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board }) } +/// The file `src` (named `name`) holding `bytes`, read by importer plug-in `plugin` with `p`'s +/// `params`, as art to place: its objects in paint order, guides left out, in a group whose natural +/// box is the bounds of what they draw. It is embedded: an importer reads the file once, so there is +/// nothing to link to. +fn plugin_art(name: String, src: &str, bytes: &[u8], plugin: &vectorcraft_plugins::Plugin, p: &Value, cmd: &str) -> Result { + let (format, mut doc, warnings) = fileio::importer::read_for_place(src, bytes, plugin, p, cmd)?; + let layers = std::mem::take(&mut doc.layers); + let nodes = art_of(layer_art(&layers)); + let natural = shown_bounds(&doc.symbol_boxes(), &nodes) + .filter(|r| r.width() > 0.0 || r.height() > 0.0) + .ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?; + Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip: None }, natural, warnings, link: None, board: None }) +} + /// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an /// image for each layer and a group for each layer group, bottom first, with the layer's name, /// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas, @@ -992,7 +1017,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices", "importer", "params"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..94a0a95c4a 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -92,6 +92,9 @@ pub fn describe(p: &Plugin) -> Value { Kind::Exporter | Kind::Importer => { v["format"] = json!(export::format_id(&m.id)); v["extensions"] = json!(m.extensions); + if m.place { + v["place"] = json!(true); + } } Kind::Filter => {} } @@ -1270,7 +1273,7 @@ pub fn specs() -> Vec { "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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., which runs it), label, params (doc), paramsSchema}] (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.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), 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.., which runs it), label, params (doc), paramsSchema}] (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 ), diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs new file mode 100644 index 0000000000..7908dc86a7 --- /dev/null +++ b/crates/engine/tests/plugin_place.rs @@ -0,0 +1,282 @@ +//! Importer plug-ins whose manifests set `place` (docs/plugins.md › Importers) through `file.place`: +//! which files they are given, the group their objects become in the open document, and what happens +//! when they fail, decline or are canceled. +//! +//! A test binary of its own: installed plug-ins are process-wide, and the unit tests that check the +//! exact list of formats would see these ones. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::{EngineError, Session}; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// An importer's output: a red rectangle "A" from (10, 20) to (110, 70) under a line "B" from +/// (10, 20) to (60, 20), and a warning. +const ART: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"B","path":{"subpaths":[{"closed":false,"anchors":[{"p":[10,20]},{"p":[60,20]}]}]}}],"warnings":["1 layer merged"]}"#; + +/// An importer's output: the rectangle "A" of [`ART`] and a guide "G" from (500, 500) to (900, 500). +const GUIDED: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"G","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[500,500]},{"p":[900,500]}]}]}}]}"#; + +/// The `vc_run` body of an importer that never returns. +const SPINS: &str = "(loop $l (br $l)) (i64.const 0)"; + +/// The manifest of an importer `id` reading `extensions` (a JSON list) that places its files. +fn placing(id: &str, extensions: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","extensions":{extensions},"place":true}}"#) +} + +/// Installs the plug-in written in WAT `src` → its `plugin.list` entry. +fn install(s: &mut Session, src: &str) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap() +} + +/// `file.place` of a file `name` holding `bytes`, with more params `extra`. +fn place(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> Result { + let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("file.place", &p) +} + +/// A session with a new document holding one rectangle, selected. +fn with_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 400.0, "y": 400.0, "width": 20.0, "height": 10.0})).unwrap(); + s +} + +/// The active document's undo and redo steps, layers and content. +fn state(s: &mut Session) -> (usize, usize, usize, Value) { + let content = s.execute("document.inspect", &json!({})).unwrap(); + let d = s.doc().unwrap(); + (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) +} + +/// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. +type Placed = (Option, Vec>, (f64, f64, f64, f64)); + +/// The group `id` of the active document. +fn object(s: &Session, id: u64) -> Placed { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).expect("placed"); + let kids = match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().map(|c| c.name.clone()).collect(), + other => panic!("not a group: {other:?}"), + }; + let b = n.geometric_bounds_with(&d.symbol_boxes()).unwrap(); + (n.name.clone(), kids, (b.x0, b.y0, b.x1, b.y1)) +} + +/// A file only a placing importer reads is placed as one group named after the file, its objects in +/// the order the importer returned them and centered on `at`, embedded (also with `link: true`), as +/// one undo step that undo takes back whole. +#[test] +fn a_placing_importer_places_one_group_as_one_undo_step() { + let mut s = with_document(); + let entry = install(&mut s, &tpl::returning(&placing("test.place.one", r#"["tpo"]"#), ART)); + assert_eq!((&entry["place"], &entry["permissions"]), (&json!(true), &json!(["import.read"]))); + let formats = s.execute("document.formats", &json!({})).unwrap(); + let listed = formats["formats"].as_array().unwrap().iter().find(|f| f["id"] == "plugin.test.place.one").expect("listed"); + assert_eq!(listed["place"], json!(true)); + + let before = state(&mut s); + let r = place(&mut s, "Shapes.tpo", b"?", json!({"at": [300, 400], "link": true})).unwrap(); + assert_eq!( + (&r["format"], &r["linked"], &r["warnings"], &r["name"]), + (&json!("plugin.test.place.one"), &json!(false), &json!(["1 layer merged"]), &json!("Shapes.tpo")) + ); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let id = ids[0].as_u64().unwrap(); + let (name, kids, bounds) = object(&s, id); + assert_eq!((name.as_deref(), kids), (Some("Shapes.tpo"), vec![Some("A".to_string()), Some("B".to_string())])); + assert_eq!(bounds, (250.0, 375.0, 350.0, 425.0)); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(id)]); + let after = state(&mut s); + assert_eq!(after.0, before.0 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = state(&mut s); + assert_eq!((undone.0, undone.1, undone.2), (before.0, 1, before.2)); + assert_eq!((&undone.3["layers"], &undone.3["history"]), (&before.3["layers"], &before.3["history"])); +} + +/// `rect` fits the group in with its aspect, Template puts it on a new template layer, Replace swaps +/// the selected object at its center and stacking place, and `file.place.info` and the place cursor +/// read the file the same way. +#[test] +fn placing_follows_rect_template_and_replace() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.ways", r#"["tpw"]"#), ART)); + let r = place(&mut s, "a.tpw", b"?", json!({"rect": [0, 0, 50, 50]})).unwrap(); + assert_eq!(object(&s, r["ids"][0].as_u64().unwrap()).2, (0.0, 12.5, 50.0, 37.5)); + + let layers = s.doc().unwrap().doc.layers.len(); + let r = place(&mut s, "b.tpw", b"?", json!({"template": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.len(), layers + 1); + let layer = d.layer_of(NodeId(r["ids"][0].as_u64().unwrap())).and_then(|l| d.node(l)).unwrap(); + assert!(matches!(layer.kind, NodeKind::Layer { template: true, .. }) && layer.locked); + + let rect = s.execute("shape.rectangle", &json!({"x": 400.0, "y": 100.0, "width": 20.0, "height": 10.0})).unwrap(); + let old = NodeId(rect["id"].as_u64().unwrap()); + let (parent, index, _) = s.doc().unwrap().doc.position(old).unwrap(); + let r = place(&mut s, "c.tpw", b"?", json!({"replace": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(old).is_none()); + assert_eq!(d.position(id).map(|(p, i, _)| (p, i)), Some((parent, index))); + assert_eq!(object(&s, id.0).2, (360.0, 80.0, 460.0, 130.0)); + + let info = s.execute("file.place.info", &json!({"name": "d.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["format"], &info["width"], &info["height"]), (&json!("plugin.test.place.ways"), &json!(100.0), &json!(50.0))); + let q = s.execute("file.place.queue", &json!({"files": [{"name": "e.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")}]})).unwrap(); + assert_eq!((&q["count"], &q["files"][0]["format"], &q["skipped"]), (&json!(1), &json!("plugin.test.place.ways"), &json!([]))); +} + +/// Guides the importer returns are left out of the placed group, and its box is that of the art +/// left, so a guide beside the art doesn't move it; output of guides alone places nothing. +#[test] +fn guides_are_left_out_of_what_is_placed() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.guided", r#"["tpg"]"#), GUIDED)); + let r = place(&mut s, "a.tpg", b"?", json!({"at": [300, 400]})).unwrap(); + let (_, kids, bounds) = object(&s, r["ids"][0].as_u64().unwrap()); + assert_eq!((kids, bounds), (vec![Some("A".to_string())], (250.0, 375.0, 350.0, 425.0))); + let info = s.execute("file.place.info", &json!({"name": "b.tpg", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["width"], &info["height"]), (&json!(100.0), &json!(50.0))); + + let guides = r#"{"objects":[{"type":"path","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[100,0]}]}]}}]}"#; + install(&mut s, &tpl::returning(&placing("test.place.guides", r#"["tpq"]"#), guides)); + let before = state(&mut s); + let e = place(&mut s, "c.tpq", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("`c.tpq` has no art to place"), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// The importer is told it places the file (`_context.mode`), with the file's extension and name, +/// and is given its parameters. +#[test] +fn the_importer_is_told_it_places() { + let mut s = with_document(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = placing("test.place.mode", r#"["tpm"]"#).replace(r#""place":true"#, &format!(r#""place":true,"params":{params}"#)); + for (i, needle) in [r#""mode":"place""#, r#""extension":"tpm""#, r#""name":"Shapes""#, r#""density":10.0"#].into_iter().enumerate() { + // ART when the parameters hold the needle; the file, which isn't JSON, otherwise. + let wasm = wat::parse_str(tpl::when_given(&manifest, Given::Params, needle, ART)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": i > 0})).unwrap(); + let r = place(&mut s, "Shapes.tpm", b"not json", json!({"params": {"density": 12}})); + assert_eq!(r.map(|r| r["format"].clone()).map_err(|e| e.to_string()), Ok(json!("plugin.test.place.mode")), "{needle}"); + } + let before = state(&mut s); + let e = place(&mut s, "Shapes.tpm", b"", json!({"params": {"density": "lots"}})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// Built-in formats keep their files: an importer that lists `svg` places an `.svg` only when +/// `importer` names it. An importer whose manifest doesn't set `place` opens its files and places +/// none: File › Place doesn't read them, and naming it is an error, as is naming it for a file of an +/// extension it doesn't list. +#[test] +fn built_in_formats_and_open_only_importers_keep_their_files() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.svg", r#"["tps","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.openonly", r#"["tpx"]"#, "{}"), ART)); + let svg = br#""#; + assert_eq!(place(&mut s, "a.svg", svg, json!({})).unwrap()["format"], "svg"); + assert_eq!(place(&mut s, "b.svg", svg, json!({"importer": "plugin.test.place.svg"})).unwrap()["format"], "plugin.test.place.svg"); + assert_eq!(place(&mut s, "c.tps", svg, json!({})).unwrap()["format"], "svg", "an SVG named as the importer's file"); + + let before = state(&mut s); + let e = place(&mut s, "d.tpx", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("not a format VectorCraft reads"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.openonly"})).unwrap_err().to_string(); + assert!(e.contains("doesn't place them") && e.contains("Test test.place.openonly"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.svg"})).unwrap_err().to_string(); + assert!(e.contains(".tps, .svg") && e.contains("d.tpx"), "{e}"); + let e = place(&mut s, "d.tps", b"?", json!({"importer": 3})).unwrap_err().to_string(); + assert!(e.contains("`importer` must be"), "{e}"); + assert_eq!(state(&mut s), before); + // The open-only importer still opens its files. + let r = s.execute("document.open", &json!({"name": "d.tpx", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!(r["format"], "plugin.test.place.openonly"); +} + +/// File › Place's dialog lists a placing importer's extensions, under its name and in "All placeable +/// files", and not an open-only importer's; relinking an image keeps the built-in filters. A file only +/// a placing importer reads is dropped onto the canvas to be placed rather than opened. +#[test] +fn the_place_dialog_lists_placing_importers() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&placing("test.place.list", r#"["tpl","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.listopen", r#"["tpy"]"#, "{}"), ART)); + let filters: Vec<_> = fileio::place_dialog_filters().collect(); + assert!(filters.contains(&("Test test.place.list", &["tpl"][..])), "{filters:?}"); + let all = filters.first().unwrap(); + assert_eq!(all.0, "All placeable files"); + assert!(all.1.contains(&"tpl") && !all.1.contains(&"tpy"), "{all:?}"); + assert_eq!(all.1.iter().filter(|e| **e == "svg").count(), 1); + assert!(!filters.iter().any(|(_, exts)| exts.contains(&"tpy"))); + assert!(!fileio::place_filters().any(|(_, exts)| exts.contains(&"tpl"))); + assert!(fileio::places_with_importer("x.TPL") && !fileio::opens_with_importer("x.tpl")); + assert!(!fileio::places_with_importer("x.tpy") && fileio::opens_with_importer("x.tpy")); + assert!(!fileio::places_with_importer("x.svg")); +} + +/// Nothing is placed, and the document keeps its content and undo steps, when the importer declines, +/// returns output that doesn't pass the checks, traps or is canceled, or when the file is larger +/// than an importer reads: that file is refused from its size, before it is read. +#[test] +fn failures_place_nothing() { + let mut s = with_document(); + let far = r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[9000000,0]}]}]}}]}"#; + let cases = [ + ("test.place.fail.declines", r#"{"error":"Not a drawing."}"#, "Not a drawing."), + ("test.place.fail.notjson", "not json", "JSON"), + ("test.place.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), + ("test.place.fail.key", r#"{"objects":[],"layers":[]}"#, "not `layers`"), + ("test.place.fail.far", far, "4000000"), + ( + "test.place.fail.point", + r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[5,5]}]}]}}]}"#, + "no art to place", + ), + ]; + for (id, output, _) in cases { + install(&mut s, &tpl::returning(&placing(id, r#"["tpf"]"#), output)); + } + install(&mut s, &tpl::module(&placing("test.place.fail.traps", r#"["tpf"]"#), "(unreachable)", "", 1)); + install(&mut s, &tpl::module(&placing("test.place.fail.spins", r#"["tpf"]"#), SPINS, "", 1)); + let before = state(&mut s); + for (id, _, why) in cases { + let e = place(&mut s, "x.tpf", b"?", json!({"importer": format!("plugin.{id}")})).unwrap_err().to_string(); + assert!(e.contains(why) && e.contains("x.tpf"), "{id}: {e}"); + assert_eq!(state(&mut s), before, "{id}"); + } + assert!(place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.traps"})).is_err()); + assert_eq!(state(&mut s), before, "trapped"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.spins"}))); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(state(&mut s), before, "canceled"); + + // A file one byte past the limit, without data in it: the size alone refuses it. + let dir = std::env::temp_dir().join(format!("vc-plugin-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpf"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.fail.declines"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpf`") && e.contains("larger than"), "{e}"); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("larger than"), "by its extension: {e}"); + assert_eq!(state(&mut s), before, "too large"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 599470e0aa..453ed75f41 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -7,6 +7,10 @@ //! sorts first opens it ([`for_extension`]). File › Open With and `document.open {importer}` pick an //! importer by its format id (`plugin.`), also for an extension a built-in format reads. //! +//! An importer whose manifest sets `place` also reads its files for File › Place (`file.place`), +//! by the same rules among the importers that set it ([`placing`]): its objects become one group in +//! the open document, and it is told so in `_context.mode` ([`Mode::Place`]). +//! //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. @@ -61,6 +65,38 @@ pub fn for_extension(ext: &str) -> Vec> { installed().into_iter().filter(|p| p.manifest().extensions.contains(&ext)).collect() } +/// The installed importers whose manifests set `place` and that list extension `ext` (any case, +/// leading dot allowed), by plug-in id: the first is the one File › Place uses. +pub fn placing(ext: &str) -> Vec> { + for_extension(ext).into_iter().filter(|p| p.manifest().place).collect() +} + +/// The error of importer `m`, whose manifest doesn't set `place`, asked to place a file. +pub fn not_placing(m: &crate::Manifest) -> Error { + let shown = crate::permissions::display_text(&m.name, crate::permissions::MAX_SHOWN_NAME); + Error::Params(format!("“{shown}” opens files but doesn't place them: its manifest doesn't set `place`")) +} + +/// What an import is for, which the importer is told as `_context.mode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// File › Open: the objects become a new document (`"import"`). + Import, + /// File › Place: the objects become one group in the open document (`"place"`). Only an + /// importer whose manifest sets `place` runs for it. + Place, +} + +impl Mode { + /// Its name in `_context.mode`. + pub fn name(self) -> &'static str { + match self { + Mode::Import => "import", + Mode::Place => "place", + } + } +} + /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { @@ -93,15 +129,24 @@ pub fn limits(plugin: &Plugin) -> Limits { /// Runs importer `plugin` on `file`, the bytes of the file being opened, with `params` (checked /// against its manifest: missing ones take their defaults) for the file `source`. pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Result { + run_as(plugin, file, params, source, Mode::Import) +} + +/// [`run`] for `mode`. [`Mode::Place`] is refused for an importer whose manifest doesn't set `place` +/// ([`not_placing`]), before it runs. +pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode: Mode) -> Result { let m = plugin.manifest(); if m.kind != Kind::Importer { return Err(not_importer(m)); } + if mode == Mode::Place && !m.place { + return Err(not_placing(m)); + } if file.len() > MAX_INPUT_BYTES { return Err(too_large()); } let mut params = Value::Object(m.resolve_params(params)?); - params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name}); + params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..8c8888a478 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -333,6 +333,11 @@ pub struct Manifest { /// the one an exporter's files get. Only exporters and importers declare them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub extensions: Vec, + /// An importer whose files File › Place also reads (`file.place`), into the open document as one + /// group ([`crate::import::Mode::Place`]): `true` when the manifest has `"place": true`. Only an + /// importer sets it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub place: bool, /// How much a run may compute: only a filter may be [`Budget::Heavy`]. #[serde(default, skip_serializing_if = "Budget::is_light")] pub budget: Budget, @@ -379,6 +384,7 @@ impl Manifest { inputs: Vec::new(), params: Vec::new(), extensions: Vec::new(), + place: false, budget: Budget::Light, paint_output: false, commands: Vec::new(), @@ -426,6 +432,9 @@ impl Manifest { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } self.validate_extensions()?; + if self.place && self.kind != Kind::Importer { + return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into())); + } match (self.budget, self.kind) { (Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {} (Budget::Heavy, Kind::Effect) => { @@ -1050,6 +1059,33 @@ mod tests { } } + /// Only an importer sets `place`, to a boolean, and it asks for no permission beyond + /// `import.read`; false, the default, isn't written back. + #[test] + fn only_an_importer_places_its_files() { + let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":true}"#).unwrap(); + assert!(m.place); + assert_eq!(m.permissions(), [Permission::ImportRead]); + assert_eq!(serde_json::to_value(&m).unwrap()["place"], json!(true)); + for open_only in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":false}"#, + ] { + let m = Manifest::parse(open_only.as_bytes()).unwrap(); + assert!(!m.place && serde_json::to_value(&m).unwrap().get("place").is_none(), "{open_only}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"effect","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":"yes"}"#, "invalid type"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":1}"#, "invalid type"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an /// exporter has an export's budget, so they can't. Light, the default, isn't written back. #[test] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..f5d07b0397 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -716,6 +716,7 @@ impl PluginIntField { inputs: Vec::new(), params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], extensions: Vec::new(), + place: false, budget: Default::default(), paint_output: false, commands: Vec::new(), diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 7dd035c1e1..118e0f62cf 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -225,6 +225,54 @@ fn a_dropped_file_only_an_importer_reads_opens() { app.run("plugin.remove", json!({"id": "test.ui.dropshare"})).unwrap(); } +/// A file only an importer that places its files reads, dropped on the canvas, is placed there as +/// one group by that importer, as one undo step; dropped where the platform gives no position, it +/// opens as its own document, as a vector file does. +#[test] +fn a_dropped_file_a_placing_importer_reads_is_placed_on_the_canvas() { + use crate::place::{DropTarget, drop_files}; + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0))); + let on_canvas = Some(egui::pos2(400.0, 300.0)); + let manifest = tpl::importer("test.ui.dropplace", r#"["tdp"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + assert!(manifest.contains(r#""place":true"#), "{manifest}"); + install(&mut app, &tpl::returning(&manifest, RECT)); + + let target = app.drop_target("Drawing.tdp", on_canvas, false); + assert!(matches!(target, DropTarget::Place(_)), "{target:?}"); + assert_eq!(app.drop_target("Drawing.tdp", None, false), DropTarget::Open); + let steps = app.session.active().unwrap().history.undo.len(); + drop_files(&mut app, vec![(target, ("Drawing.tdp".into(), None, b"?".to_vec()))]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + let [id] = st.selection.objects[..] else { panic!("one placed object: {:?}", st.selection.objects) }; + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) && n.name.as_deref() == Some("Drawing.tdp"), "{n:?}"); + + app.run("plugin.remove", json!({"id": "test.ui.dropplace"})).unwrap(); +} + +/// A text file or DXF drawing placed with the importer `importer` names goes to that importer, +/// without the text or DXF import options File › Place asks for those formats. +#[test] +fn a_named_placing_importer_skips_built_in_import_options() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.namedplace", r#"["txt","dxf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + for name in ["Notes.txt", "Plan.dxf"] { + let steps = app.session.active().unwrap().history.undo.len(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(b"0\nSECTION\n"), "importer": "plugin.test.ui.namedplace"}); + let r = app.run("file.place", p).unwrap(); + assert!(app.ui.dialog.is_none(), "{name}: no import options dialog"); + assert_eq!(r["format"], "plugin.test.ui.namedplace", "{name}: {r}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{name}"); + } + app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..d35c134eeb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7864,6 +7864,8 @@ variable-list-end {0}, {1} {0} i {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` és {_1}; aquest amfitrió admet els nivells d’API de complements de l’1 al {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` només pot ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` només és per a un efecte dinàmic (`kind` "effect") amb `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` només és per a un importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» obre fitxers però no els col·loca: el seu manifest no defineix `place` @msg `grant` must be a list of permission names `grant` ha de ser una llista de noms de permisos @msg `grant` names an unknown permission `{shown}` `grant` esmenta un permís desconegut `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un complement del tipus `{_1}` necessita el permís `{_2}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..5c4fafbb50 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7474,6 +7474,8 @@ axis Y Axis osa Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` je {_1}; tento hostitel podporuje úrovně API zásuvných modulů 1 až {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` může být jen true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` je jen pro živý efekt (`kind` "effect") s `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` je jen pro importér (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ otevírá soubory, ale neumísťuje je: jeho manifest nenastavuje `place` @msg `grant` must be a list of permission names `grant` musí být seznam názvů oprávnění @msg `grant` names an unknown permission `{shown}` `grant` uvádí neznámé oprávnění `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` zásuvný modul druhu `{_1}` potřebuje oprávnění `{_2}` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..55aca3499b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -686,6 +686,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` er {_1}; denne vært implementerer plug-in-API-niveau 1 til {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` må kun være true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` er kun til en live-effekt (`kind` "effect") ved `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` er kun til en importør (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` »{shown}« åbner filer, men placerer dem ikke: dens manifest angiver ikke `place` @msg `grant` must be a list of permission names `grant` skal være en liste med tilladelsesnavne @msg `grant` names an unknown permission `{shown}` `grant` angiver en ukendt tilladelse `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` et plug-in af typen `{_1}` kræver tilladelsen `{_2}` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..ff6b4f7d60 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7057,6 +7057,8 @@ axis Y Axis Y-Achse @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` ist {_1}; dieser Host unterstützt die Plug-in-API-Stufen 1 bis {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` darf nur true sein @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` gilt nur für einen Live-Effekt (`kind` "effect") mit `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` gilt nur für einen Importer (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ öffnet Dateien, platziert sie aber nicht: sein Manifest setzt `place` nicht @msg `grant` must be a list of permission names `grant` muss eine Liste von Berechtigungsnamen sein @msg `grant` names an unknown permission `{shown}` `grant` nennt eine unbekannte Berechtigung `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` ein Plug-in der Art `{_1}` braucht die Berechtigung `{_2}` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..12a0aec632 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7464,6 +7464,8 @@ axis Y Axis Άξονας Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} το `api` είναι {_1}· αυτός ο κεντρικός υπολογιστής υποστηρίζει τα επίπεδα API προσθέτων 1 έως {API_LEVEL} @msg `paintOutput` may only be true Το `paintOutput` μπορεί να είναι μόνο true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 το `paintOutput` ισχύει μόνο για ζωντανό εφέ (`kind` "effect") με `api` 2 +@msg `place` is only for an importer (`kind` "importer") το `place` ισχύει μόνο για εισαγωγέα (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` το «{shown}» ανοίγει αρχεία αλλά δεν τα τοποθετεί: το manifest του δεν ορίζει `place` @msg `grant` must be a list of permission names το `grant` πρέπει να είναι λίστα ονομάτων δικαιωμάτων @msg `grant` names an unknown permission `{shown}` το `grant` αναφέρει άγνωστο δικαίωμα `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` ένα πρόσθετο τύπου `{_1}` χρειάζεται το δικαίωμα `{_2}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..57c30dd117 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7450,6 +7450,8 @@ axis Y Axis Eje Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` es {_1}; este host admite los niveles de API de plugins de 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` solo puede ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` solo es para un efecto dinámico (`kind` "effect") con `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` solo es para un importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» abre archivos pero no los coloca: su manifiesto no establece `place` @msg `grant` must be a list of permission names `grant` debe ser una lista de nombres de permisos @msg `grant` names an unknown permission `{shown}` `grant` nombra un permiso desconocido `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un plugin de tipo `{_1}` necesita el permiso `{_2}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..f704e930ad 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7541,6 +7541,8 @@ axis Y Axis Y-akseli @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` on {_1}; tämä isäntä tukee laajennus-API:n tasoja 1 ja {API_LEVEL} välillä @msg `paintOutput` may only be true `paintOutput` voi olla vain true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` on vain reaaliaikaiselle tehosteelle (`kind` "effect") tasolla `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` on vain tuojalle (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` ”{shown}” avaa tiedostoja mutta ei sijoita niitä: sen manifesti ei aseta `place`-avainta @msg `grant` must be a list of permission names `grant` on oltava luettelo käyttöoikeuksien nimistä @msg `grant` names an unknown permission `{shown}` `grant` nimeää tuntemattoman käyttöoikeuden `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` lajin `{_1}` laajennus tarvitsee käyttöoikeuden `{_2}` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..4ce7261b75 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7470,6 +7470,8 @@ axis Y Axis Axe Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` vaut {_1} ; cet hôte prend en charge les niveaux d’API de module externe 1 à {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` ne peut valoir que true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` est réservé à un effet dynamique (`kind` "effect") avec `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` est réservé à un importateur (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` Le plug-in {shown} ouvre des fichiers mais ne les place pas, car son manifeste ne définit pas `place` @msg `grant` must be a list of permission names `grant` doit être une liste de noms d’autorisations @msg `grant` names an unknown permission `{shown}` `grant` nomme une autorisation inconnue `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un module externe de type `{_1}` a besoin de l’autorisation `{_2}` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..2bfc813007 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6658,6 +6658,8 @@ arrowhead Feather पंख @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` {_1} है; यह होस्ट प्लग-इन API स्तर 1 से {API_LEVEL} तक का समर्थन करता है @msg `paintOutput` may only be true `paintOutput` केवल true हो सकता है @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` केवल `api` 2 पर लाइव इफ़ेक्ट (`kind` "effect") के लिए है +@msg `place` is only for an importer (`kind` "importer") `place` केवल इम्पोर्टर (`kind` "importer") के लिए है +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” फ़ाइलें खोलता है पर उन्हें प्लेस नहीं करता: उसका मैनिफ़ेस्ट `place` सेट नहीं करता @msg `grant` must be a list of permission names `grant` अनुमति नामों की सूची होनी चाहिए @msg `grant` names an unknown permission `{shown}` `grant` एक अज्ञात अनुमति `{shown}` बताता है @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` प्रकार के प्लग-इन को `{_2}` अनुमति चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..5808f8dfd8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7459,6 +7459,8 @@ axis Y Axis Y tengely @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} az `api` értéke {_1}; ez a gazdaprogram az 1 és {API_LEVEL} közötti bővítmény-API-szinteket támogatja @msg `paintOutput` may only be true A `paintOutput` értéke csak true lehet @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 a `paintOutput` csak élő effektushoz (`kind` "effect") használható, `api` 2 mellett +@msg `place` is only for an importer (`kind` "importer") a `place` csak importálóhoz (`kind` "importer") használható +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” megnyitja a fájlokat, de nem helyezi el őket: a jegyzéke nem állítja be a `place` kulcsot @msg `grant` must be a list of permission names a `grant` értékének engedélynevek listájának kell lennie @msg `grant` names an unknown permission `{shown}` a `grant` ismeretlen engedélyt nevez meg: `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` egy `{_1}` fajtájú bővítménynek szüksége van a(z) `{_2}` engedélyre diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..81d99f4312 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -568,6 +568,8 @@ @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` bernilai {_1}; host ini menerapkan API plug-in tingkat 1 sampai {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` hanya boleh true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` hanya untuk efek langsung (`kind` "effect") pada `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` hanya untuk pengimpor (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” membuka berkas tetapi tidak menempatkannya: manifesnya tidak menetapkan `place` @msg `grant` must be a list of permission names `grant` harus berupa daftar nama izin @msg `grant` names an unknown permission `{shown}` `grant` menyebut izin yang tidak dikenal `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` plug-in berjenis `{_1}` memerlukan izin `{_2}` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..2eb0115d39 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7096,6 +7096,8 @@ axis Y Axis Asse Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` è {_1}; questo host supporta i livelli API dei plug-in da 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` può essere solo true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` vale solo per un effetto dinamico (`kind` "effect") con `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` vale solo per un importatore (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» apre file ma non li inserisce: il suo manifest non imposta `place` @msg `grant` must be a list of permission names `grant` deve essere un elenco di nomi di autorizzazioni @msg `grant` names an unknown permission `{shown}` `grant` indica un’autorizzazione sconosciuta `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` un plug-in di tipo `{_1}` richiede l’autorizzazione `{_2}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..7c48013363 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7171,6 +7171,8 @@ axis Y Axis Y 軸 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` は {_1} です。このホストが対応するプラグイン API レベルは 1 から {API_LEVEL} です @msg `paintOutput` may only be true `paintOutput` には true のみ指定できます @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` は `api` 2 のライブ効果 (`kind` "effect") 専用です +@msg `place` is only for an importer (`kind` "importer") `place` はインポーター (`kind` "importer") 専用です +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` 「{shown}」はファイルを開きますが配置はしません: マニフェストで `place` が設定されていません @msg `grant` must be a list of permission names `grant` は権限名のリストにしてください @msg `grant` names an unknown permission `{shown}` `grant` に不明な権限 `{shown}` が含まれています @msg a plug-in of kind `{_1}` needs the permission `{_2}` 種類 `{_1}` のプラグインには権限 `{_2}` が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..da5ad6fffe 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9577,6 +9577,8 @@ axis Y Axis Y ღერძი @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` არის {_1}; ეს ჰოსტი პლაგინის API-ის დონეებს 1-დან {API_LEVEL}-მდე უჭერს მხარს @msg `paintOutput` may only be true `paintOutput` შეიძლება იყოს მხოლოდ true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` მხოლოდ ცოცხალი ეფექტისთვისაა (`kind` "effect") `api` 2-ზე +@msg `place` is only for an importer (`kind` "importer") `place` მხოლოდ იმპორტერისთვისაა (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}“ ხსნის ფაილებს, მაგრამ არ ათავსებს: მის მანიფესტში `place` არ არის მითითებული @msg `grant` must be a list of permission names `grant` ნებართვების სახელების სია უნდა იყოს @msg `grant` names an unknown permission `{shown}` `grant` უცნობ ნებართვას ასახელებს: `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` სახის პლაგინს სჭირდება ნებართვა `{_2}` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..7005da106e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7068,6 +7068,8 @@ axis Y Axis Y축 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api`가 {_1}입니다. 이 호스트는 플러그인 API 수준 1부터 {API_LEVEL}까지 지원합니다 @msg `paintOutput` may only be true `paintOutput`에는 true만 지정할 수 있습니다 @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput`은 `api` 2의 라이브 효과(`kind` "effect")에만 쓸 수 있습니다 +@msg `place` is only for an importer (`kind` "importer") `place`는 임포터(`kind` "importer")에만 쓸 수 있습니다 +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}”은(는) 파일을 열지만 배치하지는 않습니다: 매니페스트에 `place`가 설정되어 있지 않습니다 @msg `grant` must be a list of permission names `grant`는 권한 이름 목록이어야 합니다 @msg `grant` names an unknown permission `{shown}` `grant`에 알 수 없는 권한 `{shown}`이(가) 있습니다 @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` 종류의 플러그인에는 `{_2}` 권한이 필요합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..deeaeb899c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -532,6 +532,8 @@ liquify-list-end {0}, {1} {0} en {1} @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` is {_1}; deze host implementeert plug-in-API-niveaus 1 tot {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` mag alleen true zijn @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` is alleen voor een live-effect (`kind` "effect") bij `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` is alleen voor een importer (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” opent bestanden maar plaatst ze niet: het manifest stelt `place` niet in @msg `grant` must be a list of permission names `grant` moet een lijst met namen van machtigingen zijn @msg `grant` names an unknown permission `{shown}` `grant` noemt een onbekende machtiging `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` een plug-in van het soort `{_1}` heeft de machtiging `{_2}` nodig diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..87e302d111 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7329,6 +7329,8 @@ axis Y Axis Oś Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` ma wartość {_1}; ten host obsługuje poziomy API wtyczek od 1 do {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` może mieć tylko wartość true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` dotyczy tylko efektu na żywo (`kind` "effect") z `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` dotyczy tylko importera (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` „{shown}” otwiera pliki, ale ich nie umieszcza: jego manifest nie ustawia `place` @msg `grant` must be a list of permission names `grant` musi być listą nazw uprawnień @msg `grant` names an unknown permission `{shown}` `grant` wymienia nieznane uprawnienie `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` wtyczka rodzaju `{_1}` potrzebuje uprawnienia `{_2}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..c0ba4962ef 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7373,6 +7373,8 @@ axis Y Axis Eixo Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` é {_1}; este host aceita os níveis de API de plug-in de 1 a {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` só pode ser true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` é só para um efeito dinâmico (`kind` "effect") com `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` é só para um importador (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” abre arquivos, mas não os insere: seu manifesto não define `place` @msg `grant` must be a list of permission names `grant` deve ser uma lista de nomes de permissões @msg `grant` names an unknown permission `{shown}` `grant` cita uma permissão desconhecida `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` um plug-in do tipo `{_1}` precisa da permissão `{_2}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..bda625997c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7096,6 +7096,8 @@ axis Y Axis Ось Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` равно {_1}; этот хост поддерживает уровни API модулей от 1 до {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` может быть только true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` допустим только для динамического эффекта (`kind` "effect") с `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` допустим только для импортёра (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» открывает файлы, но не помещает их: его манифест не задаёт `place` @msg `grant` must be a list of permission names `grant` должен быть списком имён разрешений @msg `grant` names an unknown permission `{shown}` `grant` называет неизвестное разрешение `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` модулю вида `{_1}` нужно разрешение `{_2}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..f5a2cbdd69 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7486,6 +7486,8 @@ axis Y Axis Y-axel @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` är {_1}; den här värden stöder plugin-API-nivå 1 till {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` får bara vara true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` gäller bara en liveeffekt (`kind` "effect") med `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` gäller bara en importör (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` ”{shown}” öppnar filer men placerar dem inte: dess manifest anger inte `place` @msg `grant` must be a list of permission names `grant` måste vara en lista med behörighetsnamn @msg `grant` names an unknown permission `{shown}` `grant` anger en okänd behörighet `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` ett plugin av typen `{_1}` behöver behörigheten `{_2}` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1ac316d616 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7546,6 +7546,8 @@ axis Y Axis Y ekseni @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` değeri {_1}; bu ana bilgisayar 1 ile {API_LEVEL} arasındaki eklenti API düzeylerini destekler @msg `paintOutput` may only be true `paintOutput` yalnızca true olabilir @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` yalnızca `api` 2 düzeyindeki canlı efekt (`kind` "effect") içindir +@msg `place` is only for an importer (`kind` "importer") `place` yalnızca içe aktarıcı (`kind` "importer") içindir +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” dosyaları açar ama yerleştirmez: bildirimi `place` ayarlamaz @msg `grant` must be a list of permission names `grant` izin adlarından oluşan bir liste olmalıdır @msg `grant` names an unknown permission `{shown}` `grant` bilinmeyen bir izin adlandırıyor: `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` türündeki bir eklentinin `{_2}` iznine ihtiyacı vardır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..7c303c5753 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7078,6 +7078,8 @@ axis Y Axis Вісь Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` дорівнює {_1}; цей хост підтримує рівні API модулів від 1 до {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` може бути лише true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` дозволено лише для динамічного ефекту (`kind` "effect") з `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` дозволено лише для імпортера (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` «{shown}» відкриває файли, але не розміщує їх: його маніфест не задає `place` @msg `grant` must be a list of permission names `grant` має бути списком назв дозволів @msg `grant` names an unknown permission `{shown}` `grant` називає невідомий дозвіл `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` модулю виду `{_1}` потрібен дозвіл `{_2}` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..45ab19d693 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7125,6 +7125,8 @@ axis Y Axis Trục Y @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` là {_1}; máy chủ này hỗ trợ các mức API plug-in từ 1 đến {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` chỉ có thể là true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` chỉ dành cho hiệu ứng trực tiếp (`kind` "effect") ở `api` 2 +@msg `place` is only for an importer (`kind` "importer") `place` chỉ dành cho trình nhập (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” mở tệp nhưng không đặt chúng: tệp kê khai của nó không đặt `place` @msg `grant` must be a list of permission names `grant` phải là danh sách tên quyền @msg `grant` names an unknown permission `{shown}` `grant` nêu một quyền không xác định `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` plug-in loại `{_1}` cần quyền `{_2}` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..dd9933c6b8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7306,6 +7306,8 @@ axis Y Axis Y 轴 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` 为 {_1};此主机支持的增效工具 API 级别为 1 到 {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` 只能为 true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` 仅适用于 `api` 2 的实时效果 (`kind` "effect") +@msg `place` is only for an importer (`kind` "importer") `place` 仅适用于导入器 (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` “{shown}” 只打开文件而不置入:其清单未设置 `place` @msg `grant` must be a list of permission names `grant` 必须是权限名称的列表 @msg `grant` names an unknown permission `{shown}` `grant` 包含未知权限 `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` 类型的增效工具需要权限 `{_2}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..654eb171a7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7127,6 +7127,8 @@ axis Y Axis Y 軸 @msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` 為 {_1};此主機支援的增效模組 API 層級為 1 到 {API_LEVEL} @msg `paintOutput` may only be true `paintOutput` 只能為 true @msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` 僅適用於 `api` 2 的即時效果 (`kind` "effect") +@msg `place` is only for an importer (`kind` "importer") `place` 僅適用於匯入器 (`kind` "importer") +@msg “{shown}” opens files but doesn't place them: its manifest doesn't set `place` 「{shown}」只開啟檔案而不置入:其資訊清單未設定 `place` @msg `grant` must be a list of permission names `grant` 必須是權限名稱的清單 @msg `grant` names an unknown permission `{shown}` `grant` 包含未知權限 `{shown}` @msg a plug-in of kind `{_1}` needs the permission `{_2}` `{_1}` 類型的增效模組需要權限 `{_2}` diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index a36d85f8a2..9c724c8b29 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -205,7 +205,10 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result Result Result<(), String> { let paths = if app.services.pick_open_multi.is_some() { crate::picks::open_many(app) } else { - crate::picks::open(app, &crate::FilePick { filters: crate::FilePick::filters(fileio::place_filters()), ..Default::default() }) + crate::picks::open(app, &crate::FilePick { filters: crate::FilePick::filters(fileio::place_dialog_filters()), ..Default::default() }) .into_iter() .collect() }; diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..259a740404 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -905,6 +905,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi It is given at most 128 MiB of the file and returns paths and compound paths, checked as a filter's output is, which become a new document; nothing opens when it fails, declines or is cancelled. Engine, unit and headless Open With regressions. +- **Done:** importer plug-ins that place files (`"place": true`). File › Place lists their files, and `file.place` reads + a file with one when `importer` names it or no built-in format reads the file; its objects are placed as one group, + embedded, as one undo step, and nothing is placed when it fails, declines or is cancelled. Engine regressions. - **Done:** exporter plug-ins (`"kind": "exporter"`). A plug-in adds a write-only file format that File › Export › Export As lists after the built-in ones and `document.export` writes (`plugin.`, or a path ending in one of its extensions). It is given the document as the native file's JSON and its parameters, with a larger budget than a diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..5236cc7e25 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13296,7 +13296,13 @@ with `read: true`, and `openExtensions` holds the extensions File › Open opens extension, with the installed importer that lists the extension (the one whose id sorts first, when several do). `importer` names the importer to use, which must list the file's extension, also one a built-in format reads, such as `svg`. The importer is given at most 128 MiB of the file; its objects become a new document whose artboard is -their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. `plugin.run` of an importer is +their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer whose manifest sets +`place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info` +and `file.place.queue` take `importer?: "plugin."` (one that sets `place` and lists the file's extension) and +`params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its +extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) +and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order +it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. In the app, File › Open With lists the installed importers, and `file.openWith {importer, path?, params?}` opens `path`, or a file picked among the importer's extensions, with one (on the web it opens File › Open's picker) and adds it to Open Recent. With `path` the reply is `document.open`'s result; diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..9a17420c8d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -51,8 +51,26 @@ by its extension, and the importer lists the file's extension; when several do, also one a built-in format reads (an importer that lists `svg` opens an `.svg` only this way). A damaged file of a built-in format reports that format's error, and the file is not handed to an importer. The importer's objects become a new document whose artboard is their bounds (at least 1 pt wide and high, and within ±4,000,000 pt); the document keeps -no path, so Save asks for a name. File › Place reads only the built-in formats, and a file only an importer reads opens -as a new document when it is dropped on the canvas. These rules are VectorCraft's own. +no path, so Save asks for a name. A file only an importer reads opens as a new document when it is dropped on the +canvas, unless an importer that places its files reads it (below). These rules are VectorCraft's own. + +An importer whose manifest has `"place": true` also places its files. `document.formats` and `plugin.list` mark it with +`place: true`. `file.place`, `file.place.info` and `file.place.queue` read a file with it by the rules above, among the +importers that set `place`: when no built-in format reads the file, the first such importer by id that lists its +extension reads it, and `"importer": "plugin."` names one, which must set `place` and list the file's extension, +also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The +importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) and +`_context.mode` `"place"`, and returns its objects as it does for File › Open. They are placed in the open document as +one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`, +`replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the +other objects draw. The file is embedded whatever `link` +says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or +Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used +by File › Place, and naming it is an error. In the app, File › Place lists a placing importer's extensions under "All +placeable files" and a filter of its own, named after the importer, and on the web its files dropped on the canvas are +placed there (the desktop opens a dropped document, as it does an SVG); the importer then runs with its parameters' +defaults. A file placed with `importer` goes to that importer without the import options File › Place shows for a +text file, a DXF drawing, a PDF or a PSD file. These rules are VectorCraft's own. In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with @@ -565,6 +583,11 @@ the module's start function, in a run that isn't a filter's run on a document, o without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and `document.open` reads a file with the importer only when `importer` names it. +- `place` (importers only): `true` lets File › Place read the importer's files too ([using plug-ins](#using-plug-ins)); + `false`, the default, keeps it to File › Open. A value that isn't `true` or `false`, or the key on another kind, is + refused when the plug-in is installed. It asks for no permission beyond `import.read`: the importer is given the file + and its parameters alone, and the host places what it returns. Hosts from before the key ignore it, so there the + importer opens its files and places none. - `commands` (filters and live effects; not heavy filters): up to 32 commands of the plug-in's own ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}}`. An `id` is 1–32 characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with @@ -737,7 +760,7 @@ toward the 64 MiB output cap. "_context": {"mode": "filter", "bounds": [10, 0, 75, 60], "artboard": [0, 0, 612, 792], "documentData": {"pens": 4}}} ``` -`mode` is `"filter"`, `"effect"`, `"export"`, `"import"` or `"command"` (a [command](#commands) run, whose +`mode` is `"filter"`, `"effect"`, `"export"`, `"import"`, `"place"` or `"command"` (a [command](#commands) run, whose `command` is the command's id); `bounds` the selection's geometric bounds (a live effect: the reference box of the effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard under the selection's centre, else the first; `documentData` (filters) what the plug-in last kept with the document (`null` until @@ -747,7 +770,8 @@ it keeps something; see Output). A live effect's `item` says where it sits: `"ob the extension of the file being written (one the exporter lists) and its name without the extension (the document's name when the export is not given a path), which some formats keep in their header. An import's `_context` is `{"mode": "import", "extension": "plt", "name": "Poster"}`: the extension of the file being opened and its name without the -extension. +extension. A place's `_context` is the same with `"mode": "place"`; the importer is given nothing of the document the +file is placed in. ### Output @@ -854,7 +878,9 @@ with the export's own). A decline (`{"error": …}`), a missing `dataBase64` or An **importer** returns `{"objects": [...], "warnings"?: ["…"]}`: new paths and compound paths (no `id`) in the filters' object form, checked as a filter's new objects are, with warnings capped as an exporter's are and shown with the open's own. An output with no objects, with keys other than `objects`, `warnings` and `error`, or with an object -that fails the checks opens nothing, and neither does a decline (`{"error": …}`). +that fails the checks opens nothing, and neither does a decline (`{"error": …}`). An importer that places its files +returns the same output when `_context.mode` is `"place"`; an output that fails, or whose objects other than guides draw +nothing of any width or height, places nothing. ## Writing a plug-in in Rust @@ -885,9 +911,8 @@ per change of their input, parameters or paints (results are cached), not per fr ## Not in v1 -- Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, and - importers that place files (File › Place reads only the built-in formats) or make type, images, layers or - artboards. +- Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, importers + that make type, images, layers or artboards, and placed importer files that stay linked to their file. - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see [`inputs`](#reading-type-images-and-symbols)). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..652019e0fb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,6 +2645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size before it is read) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. From 977e896fd0a67b93fc1f6f3f37135e5c41f78387 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:31:23 -0800 Subject: [PATCH 2/2] =?UTF-8?q?Plug-ins:=20File=20=E2=80=BA=20Place=20keep?= =?UTF-8?q?s=20a=20named=20importer=20and=20its=20params=20for=20every=20f?= =?UTF-8?q?ile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - file.place with `importer` and `params` and `paths`, or with no file, opened the Place dialog with only the files, so its OK read them with the built-in reader. Each dialog entry now carries the importer and its params, from the paths given, the desktop pick and the web pick, and OK passes them to file.place and file.place.queue. - On the web, each picked file carries its own pick's importer and params. Picked files with other ones, or that arrive while a Place dialog is open, wait for the next dialog. - The Place dialog does not read the start of a PDF, .ai, EPS or PostScript file placed with an importer named to tell whether Link would place it as a document. - A path placed or opened with `importer` named is refused from its size before any of it is read. Before, its first 64 KiB were read first. - docs/plugins.md and docs/mcp.md say when the size check runs, that the web's File › Place reads the picked file in the browser, that File › Place's filters leave out extensions a built-in format reads, and that a dropped file a built-in format reads goes to that format. --- apps/vectorcraft-web/src/web.rs | 16 ++-- crates/engine/src/cmd/fileio/importer.rs | 24 +++-- crates/engine/tests/plugin_place.rs | 41 ++++++++ .../src/dialogs/tests_plugin_import.rs | 94 +++++++++++++++++++ crates/ui-egui/src/place.rs | 62 +++++++++--- crates/ui-egui/src/services.rs | 5 +- crates/ui-egui/src/tests/place.rs | 5 +- docs/mcp.md | 3 +- docs/plugins.md | 20 ++-- docs/target-app-parity.md | 2 +- 10 files changed, 233 insertions(+), 39 deletions(-) diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 9e23e4044f..054c9632cc 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -431,9 +431,12 @@ impl eframe::App for WebShell { match f.bytes_async().await { Ok(bytes) => { match target { - DropTarget::Place(d) => { - place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) }) - } + DropTarget::Place(d) => place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { + name, + bytes, + drop: Some(d), + with: serde_json::Value::Null, + }), DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)), } repaint.request_repaint(); @@ -477,8 +480,9 @@ fn services( }); })), script_inbox: Some(script_inbox), - // File → Place…: the picked files go to the Place dialog. - place_async: Some(Box::new(move || { + // File → Place…: the picked files go to the Place dialog, with the importer plug-in and + // parameters `with` names. + place_async: Some(Box::new(move |with: serde_json::Value| { let inbox = picked.clone(); let ctx = place_ctx.clone(); wasm_bindgen_futures::spawn_local(async move { @@ -493,7 +497,7 @@ fn services( }; let mut arrived = vec![]; for f in files { - arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None }); + arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None, with: with.clone() }); } inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(arrived); ctx.request_repaint(); diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 53af9314a4..d89cfa22b7 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -148,7 +148,8 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> { /// `importer` names, or an extension no built-in format reads that an importer lists) is read up /// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a /// built-in format and no importer was named, which is read whole as any other file is. A file past -/// the limit that isn't read whole is reported from its size, without reading it. +/// the limit that isn't read whole is reported from its size: with `importer` named, before any of +/// it is read, and otherwise after the start of it is read to look for a built-in format. pub(super) fn read_path(path: &str, p: &Value) -> Result> { read_path_for(path, p, Mode::Import, C) } @@ -157,21 +158,32 @@ pub(super) fn read_path(path: &str, p: &Value) -> Result> { #[cfg(not(target_arch = "wasm32"))] fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result> { let explicit = named(p, cmd)?.is_some(); - if !explicit && !importer_reads(&extension(path), mode) { + if explicit { + return read_for_importer(path, mode); + } + if !importer_reads(&extension(path), mode) { return super::read_file(path); } let head = super::read_file_head(path, SNIFF_BYTES)?; if head.len() < SNIFF_BYTES { return Ok(head); } - if !explicit && detect(path, &head).is_some() { + if detect(path, &head).is_some() { return super::read_file(path); } - let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len(); - if size > import::MAX_INPUT_BYTES as u64 { + read_for_importer(path, mode) +} + +/// The file at `path` for an importer: refused from its size, before any of it is read, when it is +/// past [`import::MAX_INPUT_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +fn read_for_importer(path: &str, mode: Mode) -> Result> { + super::may_read(path)?; + let meta = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + if meta.is_file() && meta.len() > import::MAX_INPUT_BYTES as u64 { return Err(too_large(path, mode)); } - // The file can grow after the size is read. + // The file can grow after the size is read; anything but a regular file is refused here. let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?; if file.len() > import::MAX_INPUT_BYTES { return Err(too_large(path, mode)); diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs index 7908dc86a7..e5996c7a36 100644 --- a/crates/engine/tests/plugin_place.rs +++ b/crates/engine/tests/plugin_place.rs @@ -280,3 +280,44 @@ fn failures_place_nothing() { assert_eq!(state(&mut s), before, "too large"); let _ = std::fs::remove_dir_all(&dir); } + +/// A file past the limit, placed with `importer` named, is refused from its size before any of it +/// is read: here the file can't be read at all, and the error is still the size. +#[test] +fn a_named_importer_refuses_a_large_file_before_reading_it() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.unread", r#"["tpu"]"#), ART)); + let dir = std::env::temp_dir().join(format!("vc-plugin-place-unread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpu"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + // Unix: no read permission. Windows: another handle that shares nothing. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o000)).unwrap(); + } + #[cfg(windows)] + let _held = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().read(true).share_mode(0).open(&big).unwrap() + }; + // A user that reads the file anyway (root) can't show the order of the checks. + if std::fs::File::open(&big).is_ok() { + let _ = std::fs::remove_dir_all(&dir); + return; + } + let before = state(&mut s); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.unread"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpu`") && e.contains("larger than"), "{e}"); + assert_eq!(state(&mut s), before); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o644)); + } + #[cfg(windows)] + drop(_held); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 118e0f62cf..bd5bfa9971 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -273,6 +273,100 @@ fn a_named_placing_importer_skips_built_in_import_options() { app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); } +/// `file.place` with `paths`, `importer` and `params` opens the Place dialog, and its OK places the +/// files with that importer and those parameters: one file at once, several through the place +/// cursor. The files are SVG files by their extension, which the built-in reader can't read. +#[test] +fn the_place_dialog_places_paths_with_the_importer_and_params_given() { + let dir = tmp_dir("placepaths"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepaths", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let paths: Vec = ["a.svg", "b.svg"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, b"?").unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let given = + |paths: &[String]| json!({"paths": paths, "importer": "plugin.test.ui.placepaths", "params": {"density": 7}, "showImportOptions": false}); + + app.run("file.place", given(&paths[..1])).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::place::KIND)); + let steps = app.session.active().unwrap().history.undo.len(); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(r["format"], "plugin.test.ui.placepaths", "{r} {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + app.run("file.place", given(&paths)).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepaths"})).unwrap(); +} + +/// A PDF file placed with an importer plug-in named is not read to tell whether Link would place it +/// as a document: the Place dialog counts it as a file the importer embeds. The file here doesn't +/// exist, which counts as a document when its start is read. +#[test] +fn the_place_dialog_does_not_read_a_file_a_named_importer_places() { + let dir = tmp_dir("placenamedpdf"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.placepdf", r#"["pdf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + let path = dir.join("missing.pdf").to_string_lossy().into_owned(); + let fields = |app: &mut VectorcraftApp, p: serde_json::Value| { + app.run("file.place", p).unwrap(); + let d = app.ui.dialog.take().expect("the Place dialog"); + (d.fields["__documents"].clone(), d.fields["__others"].clone()) + }; + assert_eq!(fields(&mut app, json!({"paths": [path]})), (json!(true), json!(false))); + assert_eq!(fields(&mut app, json!({"paths": [path], "importer": "plugin.test.ui.placepdf"})), (json!(false), json!(true))); + app.run("plugin.remove", json!({"id": "test.ui.placepdf"})).unwrap(); +} + +/// On the web, `file.place` with `importer` and `params` and no file starts the browser's pick, and +/// the Place dialog's OK places the picked file with that importer and those parameters. Each +/// pick's files keep that pick's importer, also when another pick started before they arrived, and +/// a pick with another importer waits for its own dialog. +#[test] +fn a_web_pick_places_with_the_importer_and_params_given() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.webpick", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let inbox = crate::place::PlaceInbox::default(); + app.services.place_inbox = Some(inbox.clone()); + let started: std::rc::Rc>> = Default::default(); + let starts = started.clone(); + app.services.place_async = Some(Box::new(move |with| starts.borrow_mut().push(with))); + + app.run("file.place", json!({"importer": "plugin.test.ui.webpick", "params": {"density": 7}, "showImportOptions": false})).unwrap(); + app.run("file.place", json!({})).unwrap(); + let arrive = |name: &str, with: serde_json::Value| { + inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: b"?".to_vec(), drop: None, with }) + }; + arrive("a.svg", started.borrow()[0].clone()); + arrive("b.svg", started.borrow()[1].clone()); + crate::place::drain(&mut app); + let files = |app: &VectorcraftApp| app.ui.dialog.as_ref().filter(|d| d.kind == crate::dialogs::place::KIND).map(|d| d.fields["files"].clone()); + assert_eq!(files(&app), Some(json!([{"name": "a.svg", "importer": "plugin.test.ui.webpick", "params": {"density": 7}}]))); + let steps = app.session.active().unwrap().history.undo.len(); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(r["format"], "plugin.test.ui.webpick", "{r} {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + crate::place::drain(&mut app); + assert_eq!(files(&app), Some(json!([{"name": "b.svg"}]))); + + app.run("plugin.remove", json!({"id": "test.ui.webpick"})).unwrap(); +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 9c724c8b29..2ab9cc23e4 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -23,6 +23,9 @@ pub struct PlaceArrival { pub name: String, pub bytes: Vec, pub drop: Option, + /// A picked file's importer plug-in and parameters, from the `file.place` that started the pick + /// (`importer`, `params`; `null` or `{}` without them). + pub with: Value, } pub type PlaceInbox = Arc>>; @@ -223,8 +226,8 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result = match p.get("paths").and_then(Value::as_array) { - Some(a) => a.iter().filter_map(Value::as_str).map(|path| json!({ "path": path })).collect(), - None => return pick(app).map(|_| Value::Null), + Some(a) => a.iter().filter_map(Value::as_str).map(|path| with_importer(json!({ "path": path }), &p)).collect(), + None => return pick(app, &p).map(|_| Value::Null), }; if files.is_empty() { return Err("paths: give at least one file".into()); @@ -280,10 +283,11 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result Result<(), String> { +/// Pick files to place: the Place dialog opens with them (on the web once they arrive), placed with +/// the importer plug-in and parameters `p` names ([`with_importer`]). +fn pick(app: &mut VectorcraftApp, p: &Value) -> Result<(), String> { if let Some(f) = app.services.place_async.as_mut() { - f(); + f(with_importer(json!({}), p)); return Ok(()); } let paths = if app.services.pick_open_multi.is_some() { @@ -296,10 +300,25 @@ fn pick(app: &mut VectorcraftApp) -> Result<(), String> { if paths.is_empty() { return Err("cancelled".into()); } - open_dialog(app, paths.into_iter().map(|path| json!({ "path": path })).collect()); + open_dialog(app, paths.into_iter().map(|path| with_importer(json!({ "path": path }), p)).collect()); Ok(()) } +/// The params of `file.place` that name an importer plug-in and its parameters: a Place dialog file +/// entry carries them, and its file is read and placed with them. +const IMPORTER_KEYS: [&str; 2] = ["importer", "params"]; + +/// Place dialog file entry `file` with the importer plug-in and parameters `p` names +/// ([`IMPORTER_KEYS`]). +fn with_importer(mut file: Value, p: &Value) -> Value { + for k in IMPORTER_KEYS { + if let Some(v) = p.get(k).filter(|v| !v.is_null()) { + file[k] = v.clone(); + } + } + file +} + /// The Place dialog for `files` (`{path}`, or `{name}` with the bytes in [`PlaceState`]). fn open_dialog(app: &mut VectorcraftApp, files: Vec) { let units = app.session.active().map(|d| d.doc.units).unwrap_or_default(); @@ -326,9 +345,13 @@ fn open_dialog(app: &mut VectorcraftApp, files: Vec) { /// object), or a PDF, `.ai`, EPS or PostScript file on disk? A DCS file (an EPS file naming its /// plates) is placed as a linked image instead. Where the platform reads part of a file, only the /// file's start is read; a file longer than that is taken to be at least as long as its binary EPS -/// header says, and one whose header can't be told from it counts as a document. +/// header says, and one whose header can't be told from it counts as a document. A file that names +/// an importer plug-in is none of these, and none of it is read here. fn is_vectorcraft_file(app: &VectorcraftApp, file: &Value) -> bool { use vectorcraft_engine::cmd::place::{DCS_HEAD_BYTES, head_is_dcs}; + if file.get("importer").is_some() { + return false; + } let Some(path) = file.get("path").and_then(Value::as_str) else { return false }; let native = ["vectorcraft", vectorcraft_format::LEGACY_EXTENSION, "vctemplate"]; // The file's start, and the file's length when that is all of it. @@ -357,14 +380,15 @@ fn is_vectorcraft_file(app: &VectorcraftApp, file: &Value) -> bool { } } -/// The engine params naming `file` (a dialog file entry). +/// The engine params naming `file` (a dialog file entry), with the importer plug-in and parameters +/// it carries ([`IMPORTER_KEYS`]). fn source(app: &VectorcraftApp, file: &Value) -> Option { if let Some(path) = file.get("path").and_then(Value::as_str) { - return Some(json!({ "path": path })); + return Some(with_importer(json!({ "path": path }), file)); } let name = file.get("name").and_then(Value::as_str)?; let bytes = app.place.picked.iter().find(|(n, _)| n == name).map(|(_, b)| b)?; - Some(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })) + Some(with_importer(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), file)) } /// The Place dialog's line about each of `files`, read at once, or where the files the user places @@ -481,7 +505,9 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result { let paths: Vec<&Value> = many.iter().filter_map(|s| s.get("path")).collect(); let files: Vec<&Value> = many.iter().filter(|s| s.get("path").is_none()).collect(); - let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template }); + // The files of one dialog come from one `file.place`, with one importer plug-in and its + // parameters, if any. + let mut q = with_importer(json!({ "paths": paths, "files": files, "link": link, "template": template }), &many[0]); if !ask { // Each text file, DXF drawing and embedded PSD file in the cursor takes the options // confirmed last. @@ -770,21 +796,29 @@ pub fn drop_files(app: &mut VectorcraftApp, mut files: Vec<(DropTarget, DropFile } /// Files that arrived to be placed (web): drops go where they were dropped, picked files to the -/// Place dialog. +/// Place dialog. One dialog holds the files of picks with one importer plug-in and its parameters +/// ([`PlaceArrival::with`]); picked files with others, and picked files that arrive while a Place +/// dialog is open, wait in the inbox until it closes. pub fn drain(app: &mut VectorcraftApp) { let arrived: Vec = app.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - let mut picked = vec![]; + let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::place::KIND); + let (mut picked, mut with, mut waiting) = (vec![], None::, vec![]); for a in arrived { match a.drop { Some(d) => drop_files(app, vec![(DropTarget::Place(d), (a.name, None, a.bytes))]), + None if open || with.as_ref().is_some_and(|w| *w != a.with) => waiting.push(a), None => { - picked.push(json!({ "name": a.name })); + picked.push(with_importer(json!({ "name": a.name }), &a.with)); app.place.picked.retain(|(n, _)| *n != a.name); + with = Some(a.with); app.place.picked.push((a.name, a.bytes)); } } } + if let (false, Some(q)) = (waiting.is_empty(), app.services.place_inbox.as_ref()) { + q.lock().unwrap_or_else(|e| e.into_inner()).splice(0..0, waiting); + } if !picked.is_empty() { open_dialog(app, picked); } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 6c38464bd0..4436bfee63 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -131,8 +131,9 @@ pub struct Services { /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. pub pick_open_files: Option, - /// Web: start an async pick of files to place (they arrive via `place_inbox`). - pub place_async: Option>, + /// Web: start an async pick of files to place (they arrive via `place_inbox`), each with the + /// importer plug-in and parameters given ([`place::PlaceArrival::with`]). + pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the /// canvas). pub place_inbox: Option, diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 4681281dd3..8402fa4f26 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -417,8 +417,9 @@ fn a_file_read_after_another_document_became_active_lands_where_it_was_dropped() DropTarget::Place(d) => d, t => panic!("{t:?}"), }; - let arrive = - |name: &str, drop| inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: png(20, 10, 72.0), drop: Some(drop) }); + let arrive = |name: &str, drop| { + inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: png(20, 10, 72.0), drop: Some(drop), with: json!(null) }) + }; // Dropped on A; another document opens while the file is read. let on_a = drop_on_active(&app); let want = Xf::new(rect, app.view().unwrap()).to_doc(pos); diff --git a/docs/mcp.md b/docs/mcp.md index 5236cc7e25..09dcf8594c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13300,7 +13300,8 @@ their bounds, Save then asks for a name, and `warnings` holds the importer's war `place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info` and `file.place.queue` take `importer?: "plugin."` (one that sets `place` and lists the file's extension) and `params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its -extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) +extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, with `importer` +before any of it is read or decoded, and without it after its first 64 KiB are read or decoded) and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is an error that names `document.open`. In the app, File › Open With lists the installed importers, and diff --git a/docs/plugins.md b/docs/plugins.md index 9a17420c8d..1e4ac38059 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -59,18 +59,24 @@ An importer whose manifest has `"place": true` also places its files. `document. importers that set `place`: when no built-in format reads the file, the first such importer by id that lists its extension reads it, and `"importer": "plugin."` names one, which must set `place` and list the file's extension, also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The -importer is given at most 128 MiB of the file (a larger file is refused from its size, before it is read) and -`_context.mode` `"place"`, and returns its objects as it does for File › Open. They are placed in the open document as +importer is given at most 128 MiB of the file and `_context.mode` `"place"`, and returns its objects as it does for +File › Open. They are placed in the open document as one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`, `replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the other objects draw. The file is embedded whatever `link` says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used -by File › Place, and naming it is an error. In the app, File › Place lists a placing importer's extensions under "All -placeable files" and a filter of its own, named after the importer, and on the web its files dropped on the canvas are -placed there (the desktop opens a dropped document, as it does an SVG); the importer then runs with its parameters' -defaults. A file placed with `importer` goes to that importer without the import options File › Place shows for a -text file, a DXF drawing, a PDF or a PSD file. These rules are VectorCraft's own. +by File › Place, and naming it is an error. A larger file is refused from its size. With `importer`, a `path` is refused +before any of it is read and `dataBase64` before any of it is decoded. Without `importer`, the first 64 KiB of the file +are read or decoded first to look for a built-in format. The web's File › Place reads the picked file in the browser +before the 128 MiB limit applies. In the app, File › Place lists a placing importer's extensions under "All placeable +files" and a filter of its own, named after the importer. Extensions that a built-in format reads are left out of both, +and an importer that lists only such extensions gets no filter. On the web, a dropped file that no built-in format +reads, by its extension or its content, is placed on the canvas by the first placing importer by id that lists its +extension (the desktop opens a dropped document, as it does an SVG); a dropped file that a built-in format reads goes +to that format. The importer then runs with its parameters' defaults. A file placed with `importer` goes to that +importer without the import options File › Place shows for a text file, a DXF drawing, a PDF or a PSD file. These rules +are VectorCraft's own. In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 652019e0fb..a836f4d6ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,7 +2645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. -- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size before it is read) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged.