Merge pull request #9110 from dotCooCoo/feat/plugin-api-importers-place

Plug-ins: importers whose manifest sets place also read files for File › Place
This commit is contained in:
BFlat
2026-11-26 08:49:00 +07:00
committed by GitHub
41 changed files with 1008 additions and 108 deletions
+3 -3
View File
@@ -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)]
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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.<plug-in id>; 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.<plug-in id>; 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
),
+68 -3
View File
@@ -737,11 +737,26 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
}
/// Whether a file named `name` can only be read by an importer plug-in: an installed importer lists
/// its extension and File › Place does not read that extension.
/// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists
/// its extension, File › Place does not read that extension, and no installed importer that places
/// its files lists it ([`places_with_importer`]).
pub fn opens_with_importer(name: &str) -> 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<Item = (&'static str, &'static [&'static
.chain(std::iter::once(("Word", WORD_EXTS)))
}
/// File › Place's part for the installed importer plug-ins whose manifests set `place`: the
/// extensions of "All placeable files" ([`PLACE_EXTS`], then theirs in plug-in id order) and one
/// filter per such importer that has extensions left, under its name. An importer's extensions leave
/// out those a built-in format reads, which File › Place reads with that format. Made once for each
/// set of installed plug-ins, so it lives as long as the dialogs that hold it.
fn importer_place_part() -> ImporterPart {
use vectorcraft_plugins::{import, registry};
static MADE: std::sync::Mutex<Option<(u64, ImporterPart)>> = 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<Item = (&'static str, &'static [&'static str])> {
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<Value> {
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
};
+169 -64
View File
@@ -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.<id>`), 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<Option<&str>> {
/// 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<Option<&'a str>> {
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<String> = 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<Option<Arc<Plugin>>> {
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<String> = 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<Option<Arc<Plugin>>> {
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<Arc<Plugin>> {
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,79 +141,121 @@ 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
/// `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.
#[cfg(not(target_arch = "wasm32"))]
/// 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<Vec<u8>> {
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<Vec<u8>> {
let explicit = named(p, cmd)?.is_some();
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 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());
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<Vec<u8>> {
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());
return Err(too_large(path, mode));
}
Ok(file)
}
#[cfg(target_arch = "wasm32")]
pub(super) fn read_path(path: &str, _: &Value) -> Result<Vec<u8>> {
fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> {
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<Source<'a>> {
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<NodeId>, Vec<String>)> {
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, &params, 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<String>)> {
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<Loaded> {
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, &params, 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
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -101,6 +101,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 => {}
}
@@ -1857,7 +1860,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), 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), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
+323
View File
@@ -0,0 +1,323 @@
//! 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<Value, EngineError> {
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<String>, Vec<Option<String>>, (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#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40"><rect width="10" height="10"/></svg>"#;
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);
}
/// 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);
}
+46 -1
View File
@@ -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.<id>`), 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<Arc<Plugin>> {
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<Arc<Plugin>> {
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<Imported> {
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<Imported> {
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(&params).map_err(|e| Error::Params(e.to_string()))?;
decode(&plugin.run_limited(file, &params, &limits(plugin))?)
}
+36
View File
@@ -469,6 +469,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<String>,
/// 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,
@@ -517,6 +522,7 @@ impl Manifest {
context: Vec::new(),
params: Vec::new(),
extensions: Vec::new(),
place: false,
budget: Budget::Light,
paint_output: false,
commands: Vec::new(),
@@ -590,6 +596,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) => {
@@ -1258,6 +1267,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]
@@ -8,7 +8,7 @@ use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_plugins::wat::{self as tpl, Given};
use super::tests_export::{fields, frame, kind, set, try_confirm};
use super::tests_export::{cancel, fields, frame, kind, set, try_confirm};
use super::*;
use crate::Services;
use crate::VectorcraftApp;
@@ -237,6 +237,180 @@ 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::{DropSpot, DropTarget, drop_files};
let mut app = app();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0));
let on_canvas = DropSpot::Canvas(vectorcraft_geom::Point::new(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", DropSpot::Unknown, 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!(kind(&app).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();
}
/// `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<String> = ["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!(kind(&app).as_deref(), Some(crate::dialogs::place::KIND));
let steps = app.session.active().unwrap().history.undo.len();
try_confirm(&mut app).unwrap();
assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
app.run("file.place", given(&paths)).unwrap();
try_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 counted = |app: &mut VectorcraftApp, p: serde_json::Value| {
app.run("file.place", p).unwrap();
assert_eq!(kind(app).as_deref(), Some(crate::dialogs::place::KIND));
let f = fields(app);
cancel(app);
(f["__documents"].clone(), f["__others"].clone())
};
assert_eq!(counted(&mut app, json!({"paths": [path]})), (json!(true), json!(false)));
assert_eq!(counted(&mut app, json!({"paths": [path], "importer": "plugin.test.ui.placepdf"})), (json!(false), json!(true)));
app.run("plugin.remove", json!({"id": "test.ui.placepdf"})).unwrap();
}
/// `file.place` with `importer` and `params` and no file asks for the files, and the Place dialog's
/// OK places the picked files with that importer and those parameters: files the picker gives by
/// their contents (the web) and by their paths. A pick without them places with neither, also while
/// a pick with them is open.
#[test]
fn a_pick_places_with_the_importer_and_params_given() {
let dir = tmp_dir("placepick");
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.placepick", 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 picker = scripted(&mut app);
let ctx = crate::testing::ui_context();
let with = json!({"importer": "plugin.test.ui.placepick", "params": {"density": 7}, "showImportOptions": false});
// The web: the picker answers with the files' contents.
app.run("file.place", with.clone()).unwrap();
picker.answer_contents(&[("a.svg", b"?")]);
poll(&mut app, &ctx);
assert_eq!(fields(&app)["files"], json!([{"name": "a.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}]));
let steps = app.session.active().unwrap().history.undo.len();
try_confirm(&mut app).unwrap();
assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
// The desktop: the picker answers with paths.
let path = dir.join("b.svg");
std::fs::write(&path, b"?").unwrap();
let path = path.to_string_lossy().into_owned();
app.run("file.place", with.clone()).unwrap();
picker.answer(&[&path]);
poll(&mut app, &ctx);
assert_eq!(fields(&app)["files"], json!([{"path": path, "importer": "plugin.test.ui.placepick", "params": {"density": 7}}]));
try_confirm(&mut app).unwrap();
assert_eq!(placed_group(&app).as_deref(), Some("b.svg"), "{}", app.ui.status);
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("c.svg", b"?")]);
poll(&mut app, &ctx);
assert_eq!(fields(&app)["files"], json!([{"name": "c.svg"}]));
cancel(&mut app);
// Two picks open at once: each one's files keep that pick's importer and parameters, also when
// the later pick is answered first.
app.run("file.place", with).unwrap();
app.run("file.place", json!({})).unwrap();
picker.answer_contents(&[("e.svg", b"?")]);
poll(&mut app, &ctx);
assert_eq!(fields(&app)["files"], json!([{"name": "e.svg"}]));
cancel(&mut app);
picker.answer_contents(&[("d.svg", b"?")]);
poll(&mut app, &ctx);
assert_eq!(fields(&app)["files"], json!([{"name": "d.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}]));
try_confirm(&mut app).unwrap();
assert_eq!(placed_group(&app).as_deref(), Some("d.svg"), "{}", app.ui.status);
app.run("plugin.remove", json!({"id": "test.ui.placepick"})).unwrap();
}
/// The name of the one selected object when it is a group: what an importer places.
fn placed_group(app: &VectorcraftApp) -> Option<String> {
let st = app.session.active()?;
let [id] = st.selection.objects[..] else { return None };
let n = st.doc.node(id)?;
matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }).then(|| n.name.clone()).flatten()
}
/// 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]
+2
View File
@@ -7899,6 +7899,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}`
Can't render this file because it is too large.
+2
View File
@@ -7512,6 +7512,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}`
Can't render this file because it is too large.
+2
View File
@@ -709,6 +709,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}`
Can't render this file because it is too large.
+2
View File
@@ -7095,6 +7095,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}`
Can't render this file because it is too large.
+2
View File
@@ -7502,6 +7502,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}`
Can't render this file because it is too large.
+2
View File
@@ -7488,6 +7488,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}`
Can't render this file because it is too large.
+2
View File
@@ -7579,6 +7579,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}`
Can't render this file because it is too large.
+2
View File
@@ -7508,6 +7508,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}`
Can't render this file because it is too large.
+2
View File
@@ -6678,6 +6678,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}` अनुमति चाहिए
Can't render this file because it is too large.
+2
View File
@@ -7497,6 +7497,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
Can't render this file because it is too large.
+2
View File
@@ -591,6 +591,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}`
Can't render this file because it is too large.
+2
View File
@@ -7134,6 +7134,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}`
Can't render this file because it is too large.
+2
View File
@@ -7209,6 +7209,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}` が必要です
Can't render this file because it is too large.
+2
View File
@@ -9617,6 +9617,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}`
Can't render this file because it is too large.
+2
View File
@@ -7106,6 +7106,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}` 권한이 필요합니다
Can't render this file because it is too large.
+2
View File
@@ -554,6 +554,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
Can't render this file because it is too large.
+2
View File
@@ -7367,6 +7367,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}`
Can't render this file because it is too large.
+2
View File
@@ -7411,6 +7411,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}`
Can't render this file because it is too large.
+2
View File
@@ -7134,6 +7134,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}`
Can't render this file because it is too large.
+2
View File
@@ -7512,6 +7512,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}`
Can't render this file because it is too large.
+2
View File
@@ -7584,6 +7584,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
Can't render this file because it is too large.
+2
View File
@@ -7116,6 +7116,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}`
Can't render this file because it is too large.
+2
View File
@@ -7163,6 +7163,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}`
Can't render this file because it is too large.
+2
View File
@@ -7344,6 +7344,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}`
Can't render this file because it is too large.
+2
View File
@@ -7165,6 +7165,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}`
Can't render this file because it is too large.
+47 -19
View File
@@ -247,7 +247,10 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
o.remove("showImportOptions");
set_aside = o.remove(SET_ASIDE);
}
if !ask {
// A file placed with an importer plug-in `importer` names goes to that importer, without the
// import options of a built-in format that reads its extension.
let builtin = p.get("importer").is_none_or(Value::is_null);
if !ask && builtin {
// Placed with the options confirmed last for the format.
if p.get("text").is_none() && crate::dialogs::text_import::is_text(&p) {
p["text"] = crate::dialogs::text_import::last_options(app);
@@ -257,13 +260,13 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
}
crate::dialogs::psd_import::last_options(app, &mut p);
}
if p.get("text").is_none() && crate::dialogs::text_import::is_text(&p) {
if builtin && p.get("text").is_none() && crate::dialogs::text_import::is_text(&p) {
return Ok(crate::dialogs::text_import::open(app, &p));
}
if p.get("path").is_none() && p.get("dataBase64").is_none() {
let files: Vec<Value> = 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 Ok(pick(app)),
Some(a) => a.iter().filter_map(Value::as_str).map(|path| with_importer(json!({ "path": path }), &p)).collect(),
None => return Ok(pick(app, &p)),
};
if files.is_empty() {
return Err("paths: give at least one file".into());
@@ -273,18 +276,18 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
}
// A PDF with several pages or a password asks for the page, box and password first; with
// Show Import Options off, or with a `page` given, only an encrypted one asks, for its password.
let offered = (ask && crate::dialogs::import_pdf::offer_place(app, &p)) || crate::dialogs::import_pdf::offer_place_password(app, &p);
let offered = builtin && ((ask && crate::dialogs::import_pdf::offer_place(app, &p)) || crate::dialogs::import_pdf::offer_place_password(app, &p));
if offered {
return Ok(Value::Null);
}
// A DXF drawing asks for its import options.
if ask && crate::dialogs::dxf_import::offer_place(app, &p) {
if builtin && ask && crate::dialogs::dxf_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND }));
}
// A PSD file with several layers or with slices that the user embeds asks for its import
// options. A place run as a command (MCP, scripts) places at once and takes `layers` and
// `importSlices` itself.
if ask && matches!(read, Read::ForUser { .. }) && crate::dialogs::psd_import::offer_place(app, &p) {
if builtin && ask && matches!(read, Read::ForUser { .. }) && crate::dialogs::psd_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::psd_import::KIND }));
}
if let (Some(Value::Object(kept)), Some(o)) = (set_aside, p.as_object_mut()) {
@@ -316,19 +319,22 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
}
}
/// Pick files to place: the Place dialog opens with them (on the web once they arrive). Returns
/// what [`crate::file_asks::ask`] returns.
fn pick(app: &mut VectorcraftApp) -> Value {
let request = fileio::place_filters().fold(PickRequest::open_many("place"), |request, (name, extensions)| request.filter(name, extensions));
/// 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`]). Returns what
/// [`crate::file_asks::ask`] returns.
fn pick(app: &mut VectorcraftApp, p: &Value) -> Value {
let request =
fileio::place_dialog_filters().fold(PickRequest::open_many("place"), |request, (name, extensions)| request.filter(name, extensions));
let with = with_importer(json!({}), p);
// The web answers with the files' contents instead of paths.
crate::file_asks::ask(app, request, Owner::Document, |app, picked| {
crate::file_asks::ask(app, request, Owner::Document, move |app, picked| {
let files = match picked {
Picked::Paths(paths) => paths.into_iter().map(|path| json!({ "path": path.to_string_lossy() })).collect(),
Picked::Paths(paths) => paths.into_iter().map(|path| with_importer(json!({ "path": path.to_string_lossy() }), &with)).collect(),
Picked::Contents(files) => files
.into_iter()
.map(|(name, bytes)| {
app.place.picked.retain(|(n, _)| *n != name);
let entry = json!({ "name": name });
let entry = with_importer(json!({ "name": name }), &with);
app.place.picked.push((name, bytes));
entry
})
@@ -341,6 +347,21 @@ fn pick(app: &mut VectorcraftApp) -> Value {
})
}
/// 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`]), with Show
/// Import Options set to `show` when given, else as last chosen.
fn open_dialog(app: &mut VectorcraftApp, files: Vec<Value>, show: Option<bool>) {
@@ -385,9 +406,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// 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.
@@ -416,14 +441,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<Value> {
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
@@ -538,7 +564,9 @@ pub fn confirm(app: &mut VectorcraftApp, files: Vec<Value>, options: PlaceOption
many => {
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.
+4
View File
@@ -37,6 +37,10 @@ impl Picker {
pub(crate) fn answer(&self, paths: &[&str]) {
self.files.answer(Picked::Paths(paths.iter().map(PathBuf::from).collect()));
}
/// The newest open pick answers `files` by name and contents, as the web's picker does.
pub(crate) fn answer_contents(&self, files: &[(&str, &[u8])]) {
self.files.answer(Picked::Contents(files.iter().map(|(name, bytes)| ((*name).to_string(), bytes.to_vec())).collect()));
}
/// The newest open Save pick answers `path`, with the index of the file type picked in the panel.
pub(crate) fn answer_saved(&self, path: &str, file_type: Option<usize>) {
self.files.answer(Picked::Saved { path: PathBuf::from(path), file_type });
+3
View File
@@ -909,6 +909,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.<id>`, 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
+8 -1
View File
@@ -13707,7 +13707,14 @@ 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.<id>"` (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, 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
`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;
+39 -8
View File
@@ -52,8 +52,32 @@ 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.<id>"` 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 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. 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
@@ -652,6 +676,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"?: {…}, "menu"?: {…}}`. 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;
@@ -870,7 +899,7 @@ counts toward the half of the memory cap that the input and the parameters share
"_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
@@ -881,7 +910,8 @@ information](#document-information) asked for. A live effect's `item` says where
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
@@ -1016,7 +1046,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
@@ -1052,9 +1084,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)).
+1
View File
@@ -2694,6 +2694,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.<id>`, 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 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.