mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 21:29:35 +00:00
Merge main into fix/painted-type-used-as-a-clipping-path-loses-its
This commit is contained in:
@@ -32,7 +32,7 @@ use crate::DocState;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = vec![
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg),
|
||||
cmd!(
|
||||
query "clipboard.importSvg",
|
||||
"Load SVG into Clipboard",
|
||||
@@ -435,14 +435,37 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty).
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name
|
||||
/// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]).
|
||||
pub fn clipboard_svg(&self) -> Option<String> {
|
||||
if self.clipboard_svg_refused() {
|
||||
return None;
|
||||
}
|
||||
self.clipboard.svg()
|
||||
}
|
||||
|
||||
/// Would the internal clipboard's SVG name a linked image's file outside the read roots in
|
||||
/// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative
|
||||
/// path is followed from the document the objects came from while it is open; otherwise it
|
||||
/// counts as outside.
|
||||
pub fn clipboard_svg_refused(&self) -> bool {
|
||||
self.check_clipboard_svg("clipboard.exportSvg").is_err()
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder.
|
||||
fn check_clipboard_svg(&self, cmd: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !self.clipboard.has_art() {
|
||||
return Ok(());
|
||||
}
|
||||
let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc);
|
||||
let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of);
|
||||
super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "svg": s.clipboard_svg() }))
|
||||
s.check_clipboard_svg("clipboard.exportSvg")?;
|
||||
Ok(json!({ "svg": s.clipboard.svg() }))
|
||||
}
|
||||
|
||||
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -125,9 +125,10 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
|
||||
@@ -139,6 +139,49 @@ pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
check_images_in(cmd, format, d, crate::cmd::links::LinkBase::of(st), p)
|
||||
}
|
||||
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -12,8 +12,8 @@ use crate::DocState;
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
|
||||
write_or_return,
|
||||
ARTBOARD_PARAMS, Format, check_images_in, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output,
|
||||
writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
@@ -287,6 +287,8 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = export_doc(st, f, p)?;
|
||||
// The objects written (all, or with selectedOnly the selected ones) are checked.
|
||||
check_images_in(cmd, f.id, &doc, crate::cmd::links::LinkBase::of(st), p)?;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
@@ -372,6 +374,8 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
@@ -891,6 +891,13 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -905,12 +912,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, base, p));
|
||||
let doc = relative.map_or(own, Arc::new);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let mut params = Value::Object(params);
|
||||
let mut params = params;
|
||||
if matches!(plan.format.id, "vectorcraft" | "template") {
|
||||
// Not remembered with the options: the preference decides each time it isn't given.
|
||||
params = with_compression_pref(&s.prefs, ¶ms);
|
||||
@@ -1307,7 +1309,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -1125,6 +1125,13 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
for item in &items {
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! params' top level or from an `svg` object (which wins), and the files an SVG export writes
|
||||
//! (one per artboard, plus the images it links to).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -155,6 +157,18 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>,
|
||||
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
|
||||
}
|
||||
|
||||
/// The art the SVG files of `doc` with options `p` draw, as [`encode`] picks it: with chosen
|
||||
/// artboards, the art over each one; else all of `doc`. `None` when the options don't read.
|
||||
pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Document>>> {
|
||||
let (_, boards, chosen) = plan(doc, p).ok()?;
|
||||
if !chosen {
|
||||
return Some(vec![Cow::Borrowed(doc)]);
|
||||
}
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let rects: Vec<_> = boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect();
|
||||
Some(rects.into_iter().map(|r| Cow::Owned(super::export::art_over(doc, r, &mut renderer))).collect())
|
||||
}
|
||||
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
|
||||
@@ -1298,7 +1298,112 @@ pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is
|
||||
/// always shown as it is.
|
||||
pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url))
|
||||
file_hidden(f, doc_path)
|
||||
}
|
||||
|
||||
/// Is the file `path` (a link of the document saved at `doc_path`) one the caller asking now may
|
||||
/// not be shown? Only a path [`path_shown`] does not allow; a URL is not a file and is shown as it is.
|
||||
pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(path, doc_path) && !matches!(fileio::document_path(path, doc_path), Err(craft_docpath::Refused::Url))
|
||||
}
|
||||
|
||||
/// Does an SVG of `d` (a document whose links are looked for from `base`) written for the caller
|
||||
/// asking now name the file of a linked image that [`file_hidden`] keeps from it? An `<image>`
|
||||
/// names its image's file with SVG Options › Images set to Link (`link`), and with Embed when the
|
||||
/// document holds no pixels for the image. An image with a solid colorize paint whose pixels are
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
n.extras_mut().mask = mask;
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// [`svg_names_hidden_image`] for every image of `d`: in the layers, symbols, graph designs,
|
||||
/// patterns, opacity masks and the art of the stored brushes, used or not.
|
||||
fn names_hidden_image(d: &Document, base: LinkBase, link: bool) -> bool {
|
||||
let d = with_brush_art(d);
|
||||
let mut hidden = false;
|
||||
d.visit_images(|n, im| {
|
||||
if hidden {
|
||||
return;
|
||||
}
|
||||
let shown = d.shown_image(n, im);
|
||||
let Some(l) = &shown.link else { return };
|
||||
let blob = d.image_blob(&shown).filter(|b| !b.bytes.is_empty());
|
||||
// The SVG writes an image with a solid colorize paint as colorized pixels when they are
|
||||
// gray, and leaves it out when the document holds none of them.
|
||||
if matches!(n.extras().colorize.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })) && blob.is_none_or(|b| b.gray_source().is_some()) {
|
||||
return;
|
||||
}
|
||||
let named = link || blob.is_none();
|
||||
hidden = named && file_hidden(&l.path, base.doc);
|
||||
});
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Does the native document an SVG of `d` (a document whose links are looked for from `base`)
|
||||
/// carries with Preserve Editing Capabilities name a file that the caller asking now may not be
|
||||
/// shown: the file of a linked image or placed document ([`file_hidden`]), the relative path kept
|
||||
/// of one, which is followed from the file the document was read from and from the document's own
|
||||
/// folder, or a data set's image? Links in the layers, symbols, graph designs, patterns, the pattern
|
||||
/// being edited as it was before, opacity masks and the art of the stored brushes are all checked,
|
||||
/// as [`with_hidden_paths_named`] checks them. A stored brush library that is not a list, or holds
|
||||
/// an entry that does not read as a brush, counts as naming one: the native document carries it as
|
||||
/// it is, and its links cannot be checked. Always `false` without read roots in force.
|
||||
pub(crate) fn names_hidden_file(d: &Document, base: LinkBase) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let unread = |list: &Vec<Value>| list.iter().any(|raw| vectorcraft_brush::Brush::from_json(raw.clone()).is_err());
|
||||
if d.unknown.get(vectorcraft_brush::DOC_KEY).is_some_and(|v| v.as_array().is_none_or(unread)) {
|
||||
return true;
|
||||
}
|
||||
let relative_hidden = |r: &str| [base.relative, base.doc].into_iter().any(|from| !path_shown(r, from));
|
||||
let hidden = |l: &LinkInfo| file_hidden(&l.path, base.doc) || l.relative.as_deref().is_some_and(relative_hidden);
|
||||
let image_hidden = |v: &DataValue| matches!(v, DataValue::Image(path) if file_hidden(path, base.doc));
|
||||
if d.variables.datasets.iter().any(|set| set.values.values().any(image_hidden)) {
|
||||
return true;
|
||||
}
|
||||
let mut d = with_brush_art(d);
|
||||
if let Some(original) = d.pattern_edit.as_ref().and_then(|e| e.original.clone()) {
|
||||
d.to_mut().patterns.push(original);
|
||||
}
|
||||
let mut found = false;
|
||||
d.visit_images(|_, im| found |= im.link.as_ref().is_some_and(hidden));
|
||||
d.visit_placed(|_, p| found |= hidden(&p.link));
|
||||
found
|
||||
}
|
||||
|
||||
/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now
|
||||
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
|
||||
@@ -1791,3 +1791,350 @@ fn a_recovered_copy_of_an_imported_file_keeps_its_links_folder() {
|
||||
let mut saved: Value = serde_json::from_slice(&std::fs::read(&native).unwrap()).unwrap();
|
||||
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("src/photo.png"));
|
||||
}
|
||||
|
||||
/// Image `id` of the active document without pixels in the document, as a linked file that could
|
||||
/// not be read leaves it.
|
||||
fn without_pixels(s: &mut Session, id: NodeId) {
|
||||
let key = image(s, id).key;
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.remove(&key);
|
||||
}
|
||||
|
||||
/// The text of `document.serialize`'s reply `r` (an SVG, or the SVGZ it holds).
|
||||
fn svg_text(r: &Value) -> String {
|
||||
match r["text"].as_str() {
|
||||
Some(text) => text.to_string(),
|
||||
None => {
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
vectorcraft_svg::text_of(&bytes).unwrap().into_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller confined to read roots: every SVG and SVGZ output that would name a linked image's file
|
||||
/// outside them (Images: Link, Preserve Editing Capabilities, or Embed for an image without pixels
|
||||
/// in the document) is refused before a file or folder is written, with an error that names no
|
||||
/// file or folder, and the document keeps the link. Embed with the pixels names no file.
|
||||
#[test]
|
||||
fn confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-away");
|
||||
let home = Folder::new("svg-image-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [a.0]})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()];
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let out = home.file("out");
|
||||
// Every SVG output, with the options `o` given flat.
|
||||
let every = |s: &mut Session, o: &Value| {
|
||||
for format in ["svg", "svgz"] {
|
||||
let file = |name: &str| home.file(&format!("{name}.{format}"));
|
||||
let with = |p: Value| {
|
||||
let mut p = p;
|
||||
if let (Some(m), Some(o)) = (p.as_object_mut(), o.as_object()) {
|
||||
m.extend(o.clone());
|
||||
}
|
||||
p
|
||||
};
|
||||
refused(s, "document.serialize", with(json!({"format": format})));
|
||||
refused(s, "document.export", with(json!({"format": format})));
|
||||
refused(s, "document.export", with(json!({"format": format, "path": file("export")})));
|
||||
refused(s, "document.export", with(json!({"format": format, "selectedOnly": true})));
|
||||
refused(s, "document.exportSelection", with(json!({"format": format, "path": file("selection")})));
|
||||
refused(s, "document.save", with(json!({"path": file("save")})));
|
||||
refused(s, "file.saveAs", with(json!({"format": format, "path": file("save-as")})));
|
||||
refused(s, "file.saveCopy", with(json!({"format": format, "path": file("copy")})));
|
||||
let row = with(json!({"format": format}));
|
||||
refused(s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, row]}));
|
||||
refused(s, "document.exportForScreens", json!({"zip": true, "formats": [row]}));
|
||||
refused(s, "assets.export", json!({"folder": out, "formats": [row]}));
|
||||
}
|
||||
};
|
||||
every(&mut s, &json!({"images": "link"}));
|
||||
every(&mut s, &json!({"preserveEditing": true}));
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "svg": {"images": "link"}}));
|
||||
// Embedded pixels name no file.
|
||||
for format in ["svg", "svgz"] {
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": format}))).unwrap();
|
||||
let text = svg_text(&r);
|
||||
assert!(text.contains("data:image/png;base64,") && !text.contains(&hidden[0]), "{format}: {text}");
|
||||
}
|
||||
// Without its pixels, an embedded image names its file.
|
||||
without_pixels(&mut s, a);
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
assert!(svg_text(&r).contains(&format!("xlink:href=\"{photo}\"")), "{r}");
|
||||
every(&mut s, &json!({}));
|
||||
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert!(written.is_empty(), "{written:?}");
|
||||
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG leaves out hidden layers and objects, unless hidden layers are kept (as
|
||||
/// a save keeps them by default), and template layers always: a linked image file outside the read
|
||||
/// roots in art the file leaves out does not refuse it, and in art the file writes does.
|
||||
#[test]
|
||||
fn confined_svg_output_checks_only_the_linked_images_it_writes() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-unwritten-away");
|
||||
let home = Folder::new("svg-image-unwritten-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
// A visible rectangle, and the linked image in a layer of its own.
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let layer = NodeId(s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": layer.0})).unwrap();
|
||||
let a = place(&mut s, &photo);
|
||||
assert!(s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == a), "the image is in the new layer");
|
||||
(s, layer, a)
|
||||
};
|
||||
let written = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
if cmd == "document.serialize" {
|
||||
let text = svg_text(&r);
|
||||
assert!(!text.contains(&photo) && !text.contains("photo.png"), "{cmd} {p}: {text}");
|
||||
}
|
||||
};
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
};
|
||||
// Exports leave hidden art out; hidden layers kept, and a save, write it.
|
||||
let hidden_art = |s: &mut Session, name: &str| {
|
||||
for format in ["svg", "svgz"] {
|
||||
written(s, "document.serialize", json!({"format": format, "images": "link"}));
|
||||
written(s, "document.export", json!({"format": format, "images": "link", "path": home.file(&format!("{name}.{format}"))}));
|
||||
written(s, "document.export", json!({"format": format, "images": "link", "svg": {"hiddenLayers": false}}));
|
||||
refused(s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
refused(s, "document.export", json!({"format": format, "svg": {"images": "link", "hiddenLayers": true}}));
|
||||
refused(s, "document.save", json!({"path": home.file(&format!("{name}-save.{format}")), "images": "link"}));
|
||||
refused(s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("{name}-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
// A save told to leave hidden layers out leaves the image out too.
|
||||
let copy = home.file(&format!("{name}-copy.svg"));
|
||||
written(s, "file.saveCopy", json!({"format": "svg", "path": copy, "images": "link", "hiddenLayers": false}));
|
||||
};
|
||||
let (mut s, layer, _) = setup();
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
|
||||
hidden_art(&mut s, "hidden-layer");
|
||||
let (mut s, _, a) = setup();
|
||||
s.execute("object.hide", &json!({"ids": [a.0]})).unwrap();
|
||||
hidden_art(&mut s, "hidden-object");
|
||||
// A template layer is never written, not even with hidden layers kept.
|
||||
let (mut s, layer, _) = setup();
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": true})).unwrap();
|
||||
for format in ["svg", "svgz"] {
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link"}));
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("template-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
// Back to an ordinary layer, the image is written and refuses the file.
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": false})).unwrap();
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
|
||||
// The layer of symbol editing mode is never written: editing a symbol no art uses leaves its
|
||||
// image out of the file.
|
||||
let (mut s, _, a) = setup();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
|
||||
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("symbol.edit", &json!({"name": "Away"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "in symbol editing mode");
|
||||
for format in ["svg", "svgz"] {
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("symbol-edit-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
s.execute("symbol.place", &json!({"name": "Away"})).unwrap();
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a grayscale linked image outside the read roots that a solid fill
|
||||
/// colorizes: the file gets the colorized pixels, or leaves the image out without pixels, and names
|
||||
/// no file with Link or Embed. With Preserve Editing Capabilities the document the SVG carries
|
||||
/// keeps the link, and the SVG is refused.
|
||||
#[test]
|
||||
fn confined_svg_output_writes_a_colorized_gray_image_without_its_file() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-colorized-away");
|
||||
let home = Folder::new("svg-image-colorized-home");
|
||||
let photo = away.file("gray.png");
|
||||
let mut bytes = vec![];
|
||||
image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
write(&photo, &bytes);
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
|
||||
let colorized = s.doc().unwrap().doc.node(a).unwrap().extras().colorize.clone();
|
||||
assert!(matches!(colorized.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })), "{colorized:?}");
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let written = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
if cmd == "document.serialize" {
|
||||
let text = svg_text(&r);
|
||||
assert!(!text.contains(&away.0.to_string_lossy().into_owned()) && !text.contains("href=\"gray.png"), "{cmd} {p}: {text}");
|
||||
}
|
||||
};
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &p)).expect_err("preserveEditing").to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{p}: {e}");
|
||||
};
|
||||
let every = |s: &mut Session, name: &str| {
|
||||
for format in ["svg", "svgz"] {
|
||||
for images in ["link", "embed"] {
|
||||
written(s, "document.serialize", json!({"format": format, "images": images}));
|
||||
written(s, "document.export", json!({"format": format, "images": images, "path": home.file(&format!("{name}-{images}.{format}"))}));
|
||||
let copy = home.file(&format!("{name}-{images}-copy.{format}"));
|
||||
written(s, "file.saveCopy", json!({"format": format, "images": images, "path": copy}));
|
||||
}
|
||||
refused(s, json!({"format": format, "preserveEditing": true}));
|
||||
}
|
||||
};
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap());
|
||||
assert!(text.contains("data:image/png;base64,"), "{text}");
|
||||
every(&mut s, "pixels");
|
||||
without_pixels(&mut s, a);
|
||||
every(&mut s, "missing");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let svg = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string();
|
||||
assert!(!svg.contains(&photo), "{svg}");
|
||||
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG names each linked image file it may read, as stored: a file inside the
|
||||
/// read roots, a path relative to the document's folder that leads inside them, and a URL. The
|
||||
/// selected objects alone are exported when the image outside them is not selected, and a caller
|
||||
/// without roots gets a file outside them named too.
|
||||
#[test]
|
||||
fn svg_output_names_linked_image_files_a_caller_may_read() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-kept-away");
|
||||
let home = Folder::new("svg-image-kept-home");
|
||||
let inside = home.file("photo.png");
|
||||
let (nested, web) = (home.file("lib/photo.png"), home.file("web.png"));
|
||||
for f in [&inside, &nested, &web] {
|
||||
write(f, &png(60, 30, RED));
|
||||
}
|
||||
let url = "https://example.com/images/photo.png";
|
||||
let mut s = session();
|
||||
place(&mut s, &inside);
|
||||
place(&mut s, &nested);
|
||||
place(&mut s, &web);
|
||||
save(&mut s, &home.file("doc.vectorcraft"));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.update_links_where(|l| l.path == nested, |l| l.path = "lib/photo.png".into());
|
||||
doc.update_links_where(|l| l.path == web, |l| l.path = url.into());
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let link = json!({"format": "svg", "images": "link"});
|
||||
for format in ["svg", "svgz"] {
|
||||
let p = json!({"format": format, "images": "link"});
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
for file in [inside.as_str(), "lib/photo.png", url] {
|
||||
assert!(text.contains(&format!("xlink:href=\"{file}\"")), "{format} {file}: {text}");
|
||||
}
|
||||
}
|
||||
// An image outside them in a symbol no art uses is not written.
|
||||
let unused = away.file("unused.png");
|
||||
write(&unused, &png(60, 30, BLUE));
|
||||
let u = place(&mut s, &unused);
|
||||
s.execute("select.set", &json!({"ids": [u.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
|
||||
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), 1);
|
||||
for format in ["svg", "svgz"] {
|
||||
let p = json!({"format": format, "images": "link"});
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
assert!(!text.contains(&unused), "{format}: {text}");
|
||||
}
|
||||
let outside = away.file("photo.png");
|
||||
write(&outside, &png(60, 30, BLUE));
|
||||
place(&mut s, &outside);
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r["id"].clone()]})).unwrap();
|
||||
let p = json!({"format": "svg", "images": "link"});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.exportSelection", &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{r}");
|
||||
let p = json!({"format": "svg", "images": "link", "selectedOnly": true});
|
||||
for cmd in ["document.serialize", "document.export"] {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{cmd}: {r}");
|
||||
}
|
||||
// The file of an artboard the image is not over.
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
let p = json!({"format": "svg", "images": "link", "range": "2"});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{r}");
|
||||
let p = json!({"folder": home.file("screens"), "formats": [{"format": "svg", "images": "link"}], "range": "2"});
|
||||
confine(roots.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap();
|
||||
// Without roots, a file outside them is named as stored.
|
||||
let text = svg_text(&s.execute("document.serialize", &link).unwrap());
|
||||
assert!(text.contains(&format!("xlink:href=\"{outside}\"")), "{text}");
|
||||
}
|
||||
|
||||
/// The clipboard's SVG for a confined caller: embedded pixels name no file; an image whose pixels
|
||||
/// the clipboard doesn't hold makes `clipboard.exportSvg` refuse with an error that names no file
|
||||
/// or folder, and the system clipboard gets no SVG. A caller without roots gets the file named.
|
||||
#[test]
|
||||
fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("clip-image-away");
|
||||
let home = Folder::new("clip-image-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let r = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap();
|
||||
let svg = r["svg"].as_str().unwrap();
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains(&photo), "{svg}");
|
||||
|
||||
without_pixels(&mut s, a);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let e = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{e}");
|
||||
assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_none());
|
||||
let svg = s.execute("clipboard.exportSvg", &json!({})).unwrap()["svg"].as_str().unwrap().to_string();
|
||||
assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}");
|
||||
}
|
||||
|
||||
/// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush
|
||||
/// library holds an entry that does not read as a brush, or is not a list: the native document
|
||||
/// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written.
|
||||
#[test]
|
||||
fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let home = Folder::new("svg-brush-entry-home");
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let preserve = json!({"format": "svg", "preserveEditing": true});
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap();
|
||||
for stored in [json!(["not a brush"]), json!({"link": "/away/photo.png"})] {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), stored.clone());
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{stored}: {e}");
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1366,7 +1366,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
|
||||
@@ -84,6 +84,24 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
offer(app, &name, &bytes, path, Some(p))
|
||||
}
|
||||
|
||||
/// The `dxf` options a drawing `file.place` params `p` name is placed with when Show Import Options
|
||||
/// is off: the choices confirmed last (fit, lineweights, centring, layers), the drawing at 1:1 in
|
||||
/// its own unit. `None` when `p` names no `.dxf` drawing or already gives `dxf` options.
|
||||
pub fn last_options(app: &VectorcraftApp, p: &Value) -> Option<Value> {
|
||||
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
|
||||
if p.get("dxf").is_some() || named.as_deref() != Some("dxf") {
|
||||
return None;
|
||||
}
|
||||
Some(remembered(app))
|
||||
}
|
||||
|
||||
/// The `dxf` options of the choices confirmed last (fit, lineweights, centring, layers; `{}` when
|
||||
/// none was).
|
||||
pub fn remembered(app: &VectorcraftApp) -> Value {
|
||||
let last = app.ui.dxf_import.as_object();
|
||||
Value::Object(REMEMBERED.iter().filter_map(|k| last?.get(*k).filter(|v| v.is_boolean()).map(|v| (k.to_string(), v.clone()))).collect())
|
||||
}
|
||||
|
||||
/// The `dxf` options of `document.open` and `file.place` the fields set.
|
||||
fn options(d: &Dialog) -> Value {
|
||||
let fit = d.bool("fit");
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the
|
||||
//! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for
|
||||
//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set
|
||||
//! until the password is accepted: OK then unlocks the file. `__place` keeps the other `file.place`
|
||||
//! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with
|
||||
//! Show Import Options off) places its first page at once. `__place` keeps the other `file.place`
|
||||
//! params (Link, Template, `at`…). The file's bytes stay out of the fields, in
|
||||
//! [`crate::state::UiState::dialog_file`].
|
||||
|
||||
@@ -168,6 +169,33 @@ pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
offer(app, &name, &bytes, path, Some(p))
|
||||
}
|
||||
|
||||
/// [`offer_place`] when Show Import Options is off: asks (true) only for the password of an
|
||||
/// encrypted PDF given no `password`, which nothing else opens, and places its first page (or
|
||||
/// `page`) and crop box once it is unlocked; any other PDF is placed that way without asking.
|
||||
pub fn offer_place_password(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
// A `page` that isn't a page number is left for `file.place` to refuse.
|
||||
if p.get("password").is_some() || p.get("page").is_some_and(|v| v.as_u64().is_none_or(|n| n == 0)) {
|
||||
return false;
|
||||
}
|
||||
let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "pdf" | "ai" | "ait")) else { return false };
|
||||
if !matches!(vectorcraft_pdf::open_pdf(&bytes, None).map(|_| ()), Err(PdfError::NeedsPassword)) {
|
||||
return false;
|
||||
}
|
||||
let offered = offer(app, &name, &bytes, path, Some(p));
|
||||
if let (true, Some(d)) = (offered, app.ui.dialog.as_mut()) {
|
||||
d.fields.insert("__passwordOnly".into(), json!(true));
|
||||
// A `page` and `crop` given are placed as given, for `file.place` to check.
|
||||
if let Some(place) = d.fields.get_mut("__place").and_then(Value::as_object_mut) {
|
||||
for k in ["page", "crop"] {
|
||||
if let Some(v) = p.get(k) {
|
||||
place.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offered
|
||||
}
|
||||
|
||||
fn page_count(d: &Dialog) -> usize {
|
||||
d.fields.get("pageCount").and_then(Value::as_u64).unwrap_or(0) as usize
|
||||
}
|
||||
@@ -204,7 +232,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let info = vectorcraft_pdf::info(&file.bytes, password(&d).as_deref()).map_err(|e| e.to_string())?;
|
||||
d.fields.insert("__locked".into(), json!(false));
|
||||
d.fields.insert("pageCount".into(), json!(info.pages.len()));
|
||||
if info.pages.len() > 1 {
|
||||
if info.pages.len() > 1 && !d.bool("__passwordOnly") {
|
||||
// Unlocked: now pick the pages.
|
||||
app.ui.dialog = Some(d);
|
||||
return Ok(Value::Null);
|
||||
@@ -214,8 +242,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string);
|
||||
let r = if d.str("mode") == "place" {
|
||||
let mut p = with_file(d.fields.get("__place"), &d, &file);
|
||||
p["page"] = json!(page(&d));
|
||||
p["crop"] = json!(crop(&d).id());
|
||||
// Asked only for the password: a `page` and `crop` given with the file stand.
|
||||
let [page_given, crop_given] = ["page", "crop"].map(|k| d.bool("__passwordOnly") && p.get(k).is_some());
|
||||
if !page_given {
|
||||
p["page"] = json!(page(&d));
|
||||
}
|
||||
if !crop_given {
|
||||
p["crop"] = json!(crop(&d).id());
|
||||
}
|
||||
if let Some(pw) = password(&d) {
|
||||
p["password"] = json!(pw);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! File → Place: the files picked, one line each about what they are, and the Place options row
|
||||
//! (Link, Template, Replace). OK places one file centred in the view (or in place of the selected
|
||||
//! object) or loads the place cursor with several ([`crate::place::confirm`]).
|
||||
//! (Link, Template, Replace, Show Import Options). OK places one file centred in the view (or in
|
||||
//! place of the selected object) or loads the place cursor with several ([`crate::place::confirm`]).
|
||||
//!
|
||||
//! Fields: `files` (`[{path} | {name}]`), `link`, `template`, `replace`, and `__replace` (one file
|
||||
//! Fields: `files` (`[{path} | {name}]`), `link`, `template`, `replace`, `showImportOptions` (each
|
||||
//! PDF, DXF or text file asks for its import options before it is placed), and `__replace` (one file
|
||||
//! and one selected object: Replace applies), `__documents` and `__others` (VectorCraft documents
|
||||
//! from files are picked, other files are: what Link's tooltip explains), `__info` (a line per
|
||||
//! file; on the desktop the lines are read off the UI thread and are empty until they are read,
|
||||
@@ -29,10 +30,15 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
};
|
||||
|
||||
/// The options row: (field, label, tooltip).
|
||||
const OPTIONS: [(&str, &str, &str); 3] = [
|
||||
const OPTIONS: [(&str, &str, &str); 4] = [
|
||||
("link", "Link", "Keep a link to an image file instead of only embedding it"),
|
||||
("template", "Template", "Place onto a new locked, dimmed template layer below the current layer"),
|
||||
("replace", "Replace", "Swap the selected object for the file, keeping its place and transform"),
|
||||
(
|
||||
"showImportOptions",
|
||||
"Show Import Options",
|
||||
"Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last",
|
||||
),
|
||||
];
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
@@ -73,7 +79,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
// The options row.
|
||||
ui.horizontal(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 18.0;
|
||||
for (key, label, tip) in OPTIONS {
|
||||
let on = d.bool(key);
|
||||
|
||||
@@ -299,14 +299,17 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) {
|
||||
Some((_, c)) => c,
|
||||
None => {
|
||||
const MAX: usize = 200_000;
|
||||
let params = json!({ "svg": opts });
|
||||
let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st).and_then(|()| {
|
||||
let params = json!({ "svg": opts });
|
||||
if selection {
|
||||
let (doc, _) = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?;
|
||||
vectorcraft_engine::cmd::fileio::encode_all(&doc, "svg", ¶ms)
|
||||
let selected;
|
||||
let doc = if selection {
|
||||
selected = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?.0;
|
||||
&selected
|
||||
} else {
|
||||
vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", ¶ms)
|
||||
}
|
||||
&st.doc
|
||||
};
|
||||
vectorcraft_engine::cmd::fileio::check_linked_images("document.export", "svg", st, doc, ¶ms)?;
|
||||
vectorcraft_engine::cmd::fileio::encode_all(doc, "svg", ¶ms)
|
||||
});
|
||||
let mut text = match encoded {
|
||||
// Shown as text whatever the file's encoding.
|
||||
@@ -446,6 +449,52 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
/// Show Code under read roots draws no SVG that would name a linked image's file outside them
|
||||
/// (Images: Link): it shows the error, which names no file or folder. Embedded pixels are
|
||||
/// shown, and without roots the link is shown.
|
||||
#[test]
|
||||
fn show_code_leaves_out_a_linked_image_file_outside_the_read_roots() {
|
||||
let tmp = std::env::temp_dir();
|
||||
let root = tmp.join(format!("vc-svg-image-root-{}", std::process::id()));
|
||||
let away = tmp.join(format!("vc-svg-image-away-{}", std::process::id()));
|
||||
for dir in [&root, &away] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let photo = away.join("photo.png").to_string_lossy().into_owned();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
std::fs::write(&photo, png).unwrap();
|
||||
let (mut app, _) = app("/tmp/code.svg");
|
||||
app.run("file.place", json!({"path": photo, "link": true, "at": [50, 50]})).unwrap();
|
||||
app.run("file.export.svg", Value::Null).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("showCode".into(), json!(true));
|
||||
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap().unwrap();
|
||||
// The text the code view shows after two frames in one context, with `roots` in force.
|
||||
let code = |app: &mut VectorcraftApp, roots: Option<&Arc<vectorcraft_engine::file_access::AutomationRoots>>| {
|
||||
let ctx = egui::Context::default();
|
||||
theme::install_fonts(&ctx);
|
||||
for _ in 0..2 {
|
||||
let mut out =
|
||||
vectorcraft_engine::file_access::confine(roots, || ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
ctx.data(|m| m.get_temp::<(u64, Arc<String>)>(egui::Id::unique("svg-code"))).map(|(_, c)| c.to_string()).unwrap_or_default()
|
||||
};
|
||||
let embedded = code(&mut app, Some(&roots));
|
||||
assert!(embedded.contains("data:image/png;base64,") && !embedded.contains(&photo), "{embedded}");
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("images".into(), json!("link"));
|
||||
let confined = code(&mut app, Some(&roots));
|
||||
assert!(confined.contains("a linked image file is outside the read roots"), "{confined}");
|
||||
assert!(!confined.contains("photo.png") && !confined.contains("vc-svg-image"), "{confined}");
|
||||
let shown = code(&mut app, None);
|
||||
assert!(shown.contains(&format!("xlink:href=\"{photo}\"")), "{shown}");
|
||||
for dir in [root, away] {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show Code under Export Selection shows the SVG that OK writes: the selection alone, cropped
|
||||
/// to it with what its effects draw, not the whole document.
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Text Import Options: placing a text file asks how to read it (platform and character set) and
|
||||
//! what to clean up (line breaks inside paragraphs, blank lines between them, runs of spaces). OK
|
||||
//! places it as area type (`file.place` with `text`).
|
||||
//! places it as area type (`file.place` with `text`) and remembers the options: the next text file
|
||||
//! starts from them, and is placed with them when Show Import Options is off.
|
||||
//!
|
||||
//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`),
|
||||
//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many
|
||||
@@ -27,9 +28,10 @@ pub fn is_text(p: &Value) -> bool {
|
||||
vectorcraft_engine::cmd::fileio::TEXT_EXTS.contains(&vectorcraft_engine::cmd::fileio::extension(name).as_str())
|
||||
}
|
||||
|
||||
/// Ask how to place the text file `params` (`file.place` params) names.
|
||||
/// Ask how to place the text file `params` (`file.place` params) names, starting from the options
|
||||
/// confirmed last.
|
||||
pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
|
||||
let fields = json!({
|
||||
let mut fields = json!({
|
||||
"platform": if cfg!(target_os = "macos") { "mac" } else { "windows" },
|
||||
"characterSet": "unicode",
|
||||
"removeLineReturns": false,
|
||||
@@ -38,10 +40,31 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
|
||||
"spaces": 3,
|
||||
"__params": params,
|
||||
});
|
||||
let last = &app.ui.text_import;
|
||||
for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] {
|
||||
if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) {
|
||||
fields[k] = json!(v);
|
||||
}
|
||||
}
|
||||
for k in ["removeLineReturns", "removeParagraphReturns"] {
|
||||
if let Some(v) = last.get(k).and_then(Value::as_bool) {
|
||||
fields[k] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(n) = last.get("replaceSpaces").and_then(Value::as_u64).filter(|n| (2..=100).contains(n)) {
|
||||
fields["replaceSpaces"] = json!(true);
|
||||
fields["spaces"] = json!(n);
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
json!({ "dialog": KIND })
|
||||
}
|
||||
|
||||
/// The `text` options a text file is placed with when Show Import Options is off: those confirmed
|
||||
/// last, else `file.place`'s defaults.
|
||||
pub fn last_options(app: &VectorcraftApp) -> Value {
|
||||
if app.ui.text_import.is_object() { app.ui.text_import.clone() } else { json!({}) }
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::subheader(ui, tl!("Encoding"));
|
||||
form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]);
|
||||
@@ -87,10 +110,12 @@ fn options(d: &Dialog) -> Value {
|
||||
o
|
||||
}
|
||||
|
||||
/// Places the file with the options; closes first, so an error shows in the status bar.
|
||||
/// Places the file with the options and remembers them for the next text file; closes first, so an
|
||||
/// error shows in the status bar.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut params = d.fields.get("__params").cloned().unwrap_or_else(|| json!({}));
|
||||
params["text"] = options(d);
|
||||
app.ui.text_import = params["text"].clone();
|
||||
app.ui.dialog = None;
|
||||
crate::place::run_for_user(app, ¶ms)
|
||||
}
|
||||
|
||||
@@ -3520,6 +3520,8 @@ digits Malayalam Малаялам
|
||||
Swap Fill and Stroke (Shift+X) Размяна на запълването и щриха (Shift+X)
|
||||
Swap start and end arrowheads Размяна на началната и крайната стрелка
|
||||
Swap the selected object for the file, keeping its place and transform Замяна на избрания обект с файла, като се запазват мястото и трансформациите му
|
||||
Show Import Options Показване на опциите за импортиране
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Питане за опциите за импортиране на всеки PDF, DXF или текстов файл преди поставянето му; изключено: използват се последно избраните опции
|
||||
Stylistic Alternates Стилистични алтернативи
|
||||
Set {n} Набор {n}
|
||||
Swash Декоративен елемент
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2757,6 +2757,8 @@ digits Malayalam Malajalam
|
||||
Keep a link to an image file instead of only embedding it Zadrži vezu na slikovnu datoteku umjesto samo ugrađivanja
|
||||
Place onto a new locked, dimmed template layer below the current layer Postavi na novi zaključani, zatamnjeni sloj predloška ispod trenutnog sloja
|
||||
Swap the selected object for the file, keeping its place and transform Zamijeni odabrani objekat datotekom, zadržavajući njegovo mjesto i transformaciju
|
||||
Show Import Options Prikaži opcije uvoza
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Pitaj za opcije uvoza svake PDF, DXF ili tekstualne datoteke prije postavljanja; isključeno: koriste se posljednje odabrane opcije
|
||||
On: one locked object showing the document, updated when it changes. Uključeno: jedan zaključani objekat koji prikazuje dokument, ažuriran kad se on promijeni.
|
||||
Off: an editable copy of its art, embedded in this document. Isključeno: kopija njegovog crteža koja se može uređivati, ugrađena u ovaj dokument.
|
||||
Images: link to the file instead of only embedding it. Slike: poveži s datotekom umjesto samo ugrađivanja.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4604,6 +4604,8 @@ digits Malayalam Malaiàlam
|
||||
Swap Fill and Stroke (Shift+X) Intercanvia el farciment i el traç (Maj+X)
|
||||
Swap start and end arrowheads Intercanvia les puntes de fletxa inicial i final
|
||||
Swap the selected object for the file, keeping its place and transform Substitueix l’objecte seleccionat pel fitxer, mantenint-ne la posició i la transformació
|
||||
Show Import Options Mostra les opcions d’importació
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demana les opcions d’importació de cada fitxer PDF, DXF o de text abans de col·locar-lo; desactivat: s’usen les últimes opcions triades
|
||||
Stylistic Alternates Alternatives estilístiques
|
||||
Swash Volada
|
||||
Swatch Conflict Conflicte de mostres
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2792,6 +2792,8 @@ digits Malayalam Malajálamské
|
||||
Keep a link to an image file instead of only embedding it Ponechat propojení na soubor obrázku, ne jen ho vložit
|
||||
Place onto a new locked, dimmed template layer below the current layer Umístit do nové zamčené, ztlumené vrstvy šablony pod aktuální vrstvou
|
||||
Swap the selected object for the file, keeping its place and transform Nahradit vybraný objekt souborem se zachováním jeho polohy a transformace
|
||||
Show Import Options Zobrazit možnosti importu
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Před umístěním se zeptat na možnosti importu každého souboru PDF, DXF nebo textového souboru; vypnuto: použijí se naposledy zvolené možnosti
|
||||
On: one locked object showing the document, updated when it changes. Zapnuto: jeden zamčený objekt zobrazující dokument, aktualizovaný při jeho změně.
|
||||
Off: an editable copy of its art, embedded in this document. Vypnuto: upravitelná kopie jeho kresby vložená do tohoto dokumentu.
|
||||
Images: link to the file instead of only embedding it. Obrázky: propojit se souborem místo pouhého vložení.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3183,6 +3183,8 @@ digits Malayalam Malayalam
|
||||
Keep a link to an image file instead of only embedding it Behold et link til en billedfil i stedet for kun at indlejre den
|
||||
Place onto a new locked, dimmed template layer below the current layer Placér på et nyt låst, nedtonet skabelonlag under det aktuelle lag
|
||||
Swap the selected object for the file, keeping its place and transform Udskift det markerede objekt med filen, mens placering og transformering bevares
|
||||
Show Import Options Vis importindstillinger
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Spørg om importindstillinger for hver PDF-, DXF- eller tekstfil, før den placeres; fra: brug de senest valgte indstillinger
|
||||
On: one locked object showing the document, updated when it changes. Til: ét låst objekt, der viser dokumentet, og som opdateres, når det ændres.
|
||||
Off: an editable copy of its art, embedded in this document. Fra: en redigerbar kopi af dens grafik, indlejret i dette dokument.
|
||||
Images: link to the file instead of only embedding it. Billeder: link til filen i stedet for kun at indlejre den.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3583,6 +3583,8 @@ effect Points Punkte
|
||||
Swap Fill and Stroke (Shift+X) Fläche und Kontur vertauschen (Shift+X)
|
||||
Swap start and end arrowheads Pfeilspitzen an Anfang und Ende vertauschen
|
||||
Swap the selected object for the file, keeping its place and transform Das ausgewählte Objekt durch die Datei ersetzen; Position und Transformation bleiben erhalten
|
||||
Show Import Options Importoptionen anzeigen
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Vor dem Platzieren nach den Importoptionen jeder PDF-, DXF- oder Textdatei fragen; aus: die zuletzt gewählten Optionen verwenden
|
||||
Stylistic Alternates Stilistische Varianten
|
||||
Swash Schwungschrift
|
||||
Swatch Conflict Farbfeldkonflikt
|
||||
@@ -8996,6 +8998,7 @@ breakText Glyphs Glyphen
|
||||
@msg a line can't run from a point to itself eine Linie kann nicht von einem Punkt zu sich selbst verlaufen
|
||||
@msg a line needs at least two points eine Linie braucht mindestens zwei Punkte
|
||||
@msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner
|
||||
@msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner
|
||||
@msg a number cannot be read eine Zahl kann nicht gelesen werden
|
||||
@msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang
|
||||
@msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4108,6 +4108,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
Swap Fill and Stroke (Shift+X) Εναλλαγή γεμίσματος και περιγράμματος (Shift+X)
|
||||
Swap start and end arrowheads Εναλλαγή αρχικής και τελικής αιχμής βέλους
|
||||
Swap the selected object for the file, keeping its place and transform Αντικατάσταση επιλεγμένου αντικειμένου με το αρχείο, διατηρώντας θέση και μετασχηματισμό
|
||||
Show Import Options Εμφάνιση επιλογών εισαγωγής
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Ερώτηση για τις επιλογές εισαγωγής κάθε αρχείου PDF, DXF ή κειμένου πριν από την τοποθέτηση· απενεργοποιημένο: χρήση των τελευταίων επιλογών
|
||||
Swatch Conflict Διένεξη δείγματος χρώματος
|
||||
Swatch Conflicts Διενέξεις δειγμάτων χρωμάτων
|
||||
Swatch exchange files keep solid colors only. Τα αρχεία ανταλλαγής δειγμάτων διατηρούν μόνο συμπαγή χρώματα.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3612,6 +3612,8 @@ digits Malayalam Malayálam
|
||||
Swap Fill and Stroke (Shift+X) Intercambiar relleno y trazo (Shift+X)
|
||||
Swap start and end arrowheads Intercambiar puntas de flecha inicial y final
|
||||
Swap the selected object for the file, keeping its place and transform Sustituir el objeto seleccionado por el archivo, conservando su posición y transformación
|
||||
Show Import Options Mostrar opciones de importación
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Preguntar las opciones de importación de cada archivo PDF, DXF o de texto antes de colocarlo; desactivado: usar las últimas opciones elegidas
|
||||
Stylistic Alternates Alternativas estilísticas
|
||||
Swash Decorativa
|
||||
Swatch Conflict Conflicto de muestras
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2736,6 +2736,8 @@ digits Malayalam Malajalam
|
||||
Keep a link to an image file instead of only embedding it Säilytä linkki kuvatiedostoon sen sijaan, että kuva vain upotetaan
|
||||
Place onto a new locked, dimmed template layer below the current layer Sijoita uudelle lukitulle, himmennetylle mallitasolle nykyisen tason alapuolelle
|
||||
Swap the selected object for the file, keeping its place and transform Korvaa valittu objekti tiedostolla säilyttäen sen paikan ja muunnoksen
|
||||
Show Import Options Näytä tuontiasetukset
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Kysy kunkin PDF-, DXF- tai tekstitiedoston tuontiasetukset ennen sijoittamista; pois: käytä viimeksi valittuja asetuksia
|
||||
On: one locked object showing the document, updated when it changes. Päällä: yksi lukittu objekti, joka näyttää asiakirjan ja päivittyy sen muuttuessa.
|
||||
Off: an editable copy of its art, embedded in this document. Pois: muokattava kopio sen kuvituksesta upotettuna tähän asiakirjaan.
|
||||
Images: link to the file instead of only embedding it. Kuvat: linkitä tiedostoon sen sijaan, että se vain upotetaan.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3604,6 +3604,8 @@ digits Malayalam Malayalam
|
||||
Swap Fill and Stroke (Shift+X) Permuter le fond et le contour (Maj+X)
|
||||
Swap start and end arrowheads Permuter les pointes de flèche de début et de fin
|
||||
Swap the selected object for the file, keeping its place and transform Remplacer l’objet sélectionné par le fichier, en conservant sa position et sa transformation
|
||||
Show Import Options Afficher les options d’importation
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demander les options d’importation de chaque fichier PDF, DXF ou texte avant de le placer, sinon utiliser les dernières options choisies
|
||||
Stylistic Alternates Variantes stylistiques
|
||||
Swash Lettres ornées
|
||||
Swatch Conflict Conflit de nuances
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4985,6 +4985,8 @@ antiAlias Sharp शार्प
|
||||
Swap Objects and Sizes स्वैप ऑब्जेक्ट्स और साइज
|
||||
Swap start and end arrowheads स्वैप शुरू और अंत तीरहेड्स
|
||||
Swap the selected object for the file, keeping its place and transform फ़ाइल के लिए सिलेक्टेड ऑब्जेक्ट को स्वैप करें, अपनी जगह को बनाए रखें और परिवर्तित करें
|
||||
Show Import Options आयात विकल्प दिखाएँ
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last रखने से पहले हर PDF, DXF या टेक्स्ट फ़ाइल के आयात विकल्प पूछें; बंद होने पर पिछली बार चुने गए विकल्प इस्तेमाल करें
|
||||
Swash स्वॉश
|
||||
Swatch Conflict स्वॉच विरोध
|
||||
Swatch Conflicts स्वॉच विरोध
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4300,6 +4300,8 @@ mark-style Japanese Japán
|
||||
Swap Fill and Stroke (Shift+X) Kitöltés és körvonal cseréje (Shift+X)
|
||||
Swap start and end arrowheads Kezdő és záró nyílhegy cseréje
|
||||
Swap the selected object for the file, keeping its place and transform A kijelölt objektum cseréje a fájlra, a helye és az átalakítása megtartásával
|
||||
Show Import Options Importálási beállítások megjelenítése
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Elhelyezés előtt rákérdez minden PDF-, DXF- vagy szövegfájl importálási beállításaira; kikapcsolva a legutóbb választott beállításokat használja
|
||||
Stylistic Alternates Stilisztikai változatok
|
||||
Swash Cifra változatok
|
||||
Swatch Conflict Színminta-ütközés
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2574,6 +2574,8 @@ digits Malayalam Malayalam
|
||||
Keep a link to an image file instead of only embedding it Pertahankan tautan ke file gambar alih-alih hanya menyematkannya
|
||||
Place onto a new locked, dimmed template layer below the current layer Tempatkan pada lapisan templat baru yang terkunci dan diredupkan di bawah lapisan saat ini
|
||||
Swap the selected object for the file, keeping its place and transform Tukar objek terpilih dengan file, mempertahankan tempat dan transformasinya
|
||||
Show Import Options Tampilkan Opsi Impor
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Tanyakan opsi impor setiap file PDF, DXF, atau teks sebelum menempatkannya; nonaktif: gunakan opsi yang terakhir dipilih
|
||||
On: one locked object showing the document, updated when it changes. Aktif: satu objek terkunci yang menampilkan dokumen, diperbarui saat dokumen berubah.
|
||||
Off: an editable copy of its art, embedded in this document. Nonaktif: salinan karya seninya yang dapat diedit, tersemat dalam dokumen ini.
|
||||
Images: link to the file instead of only embedding it. Gambar: tautkan ke file alih-alih hanya menyematkannya.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2458 and column 5.
|
@@ -3658,6 +3658,8 @@ digits Malayalam Malayalam
|
||||
Swap Fill and Stroke (Shift+X) Inverti riempimento e traccia (Shift+X)
|
||||
Swap start and end arrowheads Inverti punte di freccia iniziale e finale
|
||||
Swap the selected object for the file, keeping its place and transform Sostituisci l'oggetto selezionato con il file, mantenendone posizione e trasformazione
|
||||
Show Import Options Mostra opzioni di importazione
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Chiedi le opzioni di importazione di ogni file PDF, DXF o di testo prima di inserirlo; disattivato: usa le ultime opzioni scelte
|
||||
Stylistic Alternates Alternative stilistiche
|
||||
Swash Ornamentale
|
||||
Swatch Conflict Conflitto campioni
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4058,6 +4058,8 @@ file-filter Templates テンプレート
|
||||
Superscript 上付き文字
|
||||
Swap Fill and Stroke (Shift+X) 塗りと線を入れ替え (Shift+X)
|
||||
Swap the selected object for the file, keeping its place and transform 選択したオブジェクトを、位置と変形を保ったままファイルに置き換え
|
||||
Show Import Options 読み込みオプションを表示
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 配置する前に PDF、DXF、テキストファイルごとの読み込みオプションを確認。オフのときは前回選んだオプションを使用
|
||||
Swatch Libraries Menu スウォッチライブラリメニュー
|
||||
System Layout システムレイアウト
|
||||
Tabular Lining 等幅ライニング
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2496,6 +2496,8 @@ digits Malayalam მალაიალამური
|
||||
Keep a link to an image file instead of only embedding it გამოსახულების ფაილის ბმულის შენარჩუნება მხოლოდ ჩაშენების ნაცვლად
|
||||
Place onto a new locked, dimmed template layer below the current layer ახალ ჩაკეტილ, ჩამქრალ შაბლონის შრეზე განთავსება მიმდინარე შრის ქვემოთ
|
||||
Swap the selected object for the file, keeping its place and transform მონიშნული ობიექტის ფაილით ჩანაცვლება მისი ადგილისა და გარდაქმნის შენარჩუნებით
|
||||
Show Import Options იმპორტის პარამეტრების ჩვენება
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last განთავსებამდე თითოეული PDF, DXF ან ტექსტური ფაილის იმპორტის პარამეტრების მოთხოვნა; გამორთულისას ბოლოს არჩეული პარამეტრები გამოიყენება
|
||||
On: one locked object showing the document, updated when it changes. ჩართული: ერთი ჩაკეტილი ობიექტი, რომელიც დოკუმენტს აჩვენებს და მისი ცვლილებისას ახლდება.
|
||||
Off: an editable copy of its art, embedded in this document. გამორთული: მისი ნახატის რედაქტირებადი ასლი, ჩაშენებული ამ დოკუმენტში.
|
||||
Images: link to the file instead of only embedding it. გამოსახულებები: ფაილის ბმული მხოლოდ ჩაშენების ნაცვლად.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4046,6 +4046,8 @@ file-filter Templates 템플릿
|
||||
Superscript 위 첨자
|
||||
Swap Fill and Stroke (Shift+X) 칠과 선 바꾸기 (Shift+X)
|
||||
Swap the selected object for the file, keeping its place and transform 선택한 개체를 파일로 바꾸되 위치와 변형은 유지합니다
|
||||
Show Import Options 가져오기 옵션 표시
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 배치하기 전에 각 PDF, DXF 또는 텍스트 파일의 가져오기 옵션을 묻습니다. 끄면 마지막으로 선택한 옵션을 사용합니다
|
||||
Swatch Libraries Menu 견본 라이브러리 메뉴
|
||||
System Layout 시스템 레이아웃
|
||||
Tabular Lining 고정폭 라이닝
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3092,6 +3092,8 @@ digits Malayalam Malayalam
|
||||
Keep a link to an image file instead of only embedding it Een koppeling met een afbeeldingsbestand behouden in plaats van het alleen in te sluiten
|
||||
Place onto a new locked, dimmed template layer below the current layer Plaatsen op een nieuwe, vergrendelde, gedimde sjabloonlaag onder de huidige laag
|
||||
Swap the selected object for the file, keeping its place and transform Het geselecteerde object vervangen door het bestand, met behoud van positie en transformatie
|
||||
Show Import Options Importopties tonen
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Vóór het plaatsen naar de importopties van elk PDF-, DXF- of tekstbestand vragen; uit: de laatst gekozen opties gebruiken
|
||||
On: one locked object showing the document, updated when it changes. Aan: één vergrendeld object dat het document weergeeft, bijgewerkt wanneer het verandert.
|
||||
Off: an editable copy of its art, embedded in this document. Uit: een bewerkbare kopie van de artwork, ingesloten in dit document.
|
||||
Images: link to the file instead of only embedding it. Afbeeldingen: koppel aan het bestand in plaats van het alleen in te sluiten.
|
||||
@@ -6027,6 +6029,7 @@ imageTrace Outline Contour
|
||||
@msg a layer's form has no dictionary het formulier van een laag heeft geen woordenboek
|
||||
@msg a legend draws at most {MAX_CHIPS} swatches een legenda tekent maximaal {MAX_CHIPS} stalen
|
||||
@msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots
|
||||
@msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots
|
||||
@msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object
|
||||
@msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI
|
||||
@msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2705,6 +2705,8 @@ digits Malayalam Malajalam
|
||||
Keep a link to an image file instead of only embedding it Zachowaj łącze do pliku obrazu zamiast tylko go osadzać
|
||||
Place onto a new locked, dimmed template layer below the current layer Umieść na nowej zablokowanej, przyciemnionej warstwie szablonu pod bieżącą warstwą
|
||||
Swap the selected object for the file, keeping its place and transform Zamień zaznaczony obiekt na plik, zachowując jego miejsce i przekształcenie
|
||||
Show Import Options Pokaż opcje importu
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Pytaj o opcje importu każdego pliku PDF, DXF lub tekstowego przed umieszczeniem; wył.: używaj ostatnio wybranych opcji
|
||||
On: one locked object showing the document, updated when it changes. Wł.: jeden zablokowany obiekt pokazujący dokument, aktualizowany przy jego zmianie.
|
||||
Off: an editable copy of its art, embedded in this document. Wył.: edytowalna kopia jego kompozycji, osadzona w tym dokumencie.
|
||||
Images: link to the file instead of only embedding it. Obrazy: połącz z plikiem zamiast tylko go osadzać.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5242,6 +5242,8 @@ axis Both Ambos
|
||||
Summary Resumo
|
||||
Superscript Sobrescrito
|
||||
Swap the selected object for the file, keeping its place and transform Troca o objeto selecionado pelo arquivo, mantendo sua posição e transformação
|
||||
Show Import Options Mostrar Opções de Importação
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Pergunta as opções de importação de cada arquivo PDF, DXF ou de texto antes de colocá-lo; desligado: usa as últimas opções escolhidas
|
||||
Swatch Libraries Menu Menu de Bibliotecas de Amostras
|
||||
Create New Library… Criar Nova Biblioteca…
|
||||
Rename Library… Renomear Biblioteca…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3644,6 +3644,8 @@ digits Malayalam Малаялам
|
||||
Swap Fill and Stroke (Shift+X) Поменять заливку и обводку (Shift+X)
|
||||
Swap start and end arrowheads Поменять начальную и конечную стрелки
|
||||
Swap the selected object for the file, keeping its place and transform Заменить выделенный объект файлом, сохранив его положение и преобразование
|
||||
Show Import Options Показывать параметры импорта
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запрашивать параметры импорта каждого файла PDF, DXF или текстового файла перед помещением; если выключено, используются последние выбранные параметры
|
||||
Stylistic Alternates Стилистические альтернативы
|
||||
Swash Росчерк
|
||||
Swatch Conflict Конфликт образцов
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3534,6 +3534,8 @@ digits Malayalam Malayalam
|
||||
Swap Fill and Stroke (Shift+X) Byt plats på fyllning och kontur (Shift+X)
|
||||
Swap start and end arrowheads Byt plats på start- och slutpilspets
|
||||
Swap the selected object for the file, keeping its place and transform Ersätt det markerade objektet med filen och behåll dess placering och transformering
|
||||
Show Import Options Visa importalternativ
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Fråga efter importalternativ för varje PDF-, DXF- eller textfil innan den placeras; av: använd de senast valda alternativen
|
||||
Stylistic Alternates Stilistiska alternativ
|
||||
Swash Swash
|
||||
Swatch Conflict Färgrutekonflikt
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -332,6 +332,28 @@ fn languages_resolve_from_their_tags_and_name_themselves() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turkish `Draw` labels use the drawing verb of the catalog's other drawing modes, and the
|
||||
/// accepted control names in its messages keep the spelling the command reads. The dimension
|
||||
/// scale rows keep the `drawing:real` form and say that the ratio labels a page unit.
|
||||
#[test]
|
||||
fn turkish_draw_labels_use_the_drawing_verb() {
|
||||
let tr_lang = Lang::from_code("tr").expect("tr registered");
|
||||
assert_eq!(tr(tr_lang, "Draw"), "Çiz");
|
||||
assert_eq!(tr(tr_lang, "Draw:"), "Çiz:");
|
||||
assert_eq!(tr(tr_lang, "Draw Behind"), "Arkaya Çiz");
|
||||
let (entries, _) = parse_entries(tr_lang.0.source);
|
||||
let tie: Vec<_> =
|
||||
entries.iter().filter(|(_, _, t)| t.to_lowercase().contains("beraber")).map(|(_, src, t)| format!("{src:?} -> {t:?}")).collect();
|
||||
assert!(tie.is_empty(), "Turkish rows read as a tied game:\n{}", tie.join("\n"));
|
||||
let unknown = message(tr_lang, "unknown control `x`: fillStroke, coloring, drawMode or screenMode");
|
||||
assert!(unknown.contains("fillStroke, coloring, drawMode veya screenMode"), "{unknown}");
|
||||
assert_eq!(
|
||||
tr(tr_lang, "Drawing : real size — 1:10 labels 1 unit on the page as 10."),
|
||||
"Çizim : gerçek boyut — 1:10, sayfadaki 1 birimi 10 olarak etiketler."
|
||||
);
|
||||
assert_eq!(message(tr_lang, "Scale must be drawing:real, for example 1:10"), "Ölçek çizim:gerçek biçiminde olmalıdır, örneğin 1:10");
|
||||
}
|
||||
|
||||
/// The Catalan catalog registers under `ca`, claims complete menus and messages, and passes
|
||||
/// locale resolution, vocabulary and count formatting checks.
|
||||
#[test]
|
||||
|
||||
@@ -910,12 +910,12 @@ font-technology Variable Değişken
|
||||
Drag art here, or select it and click +. Hold Alt for one asset of several objects. Resmi buraya sürükleyin veya seçip + işaretine tıklayın. Birkaç nesneden oluşan bir varlık için Alt tuşunu basılı tutun.
|
||||
Drag onto art to apply this appearance Bu görünümü uygulamak için resmin üzerine sürükleyin
|
||||
Drag the art to move it on the paper Resmi kağıt üzerinde taşımak için sürükleyin
|
||||
Draw Beraberlik
|
||||
Draw Çiz
|
||||
Draw Behind Arkaya Çiz
|
||||
Draw in Perspective Perspektifte Çiz
|
||||
Draw Inside İçini Çiz
|
||||
Draw Normal Normal Çiz
|
||||
Draw: Beraberlik:
|
||||
Draw: Çiz:
|
||||
Drawing Mode Çizim Modu
|
||||
Drop Shadow Alt Gölge
|
||||
Drop Shadow… Alt Gölge…
|
||||
@@ -3398,6 +3398,8 @@ digits Malayalam Malayalam
|
||||
Swap Fill and Stroke (Shift+X) Dolgu ve Konturu Değiştir (Shift+X)
|
||||
Swap start and end arrowheads Başlangıç ve bitiş ok uçlarını değiştirin
|
||||
Swap the selected object for the file, keeping its place and transform Seçilen nesneyi, yerini koruyarak dosyayla değiştirin ve dönüştürün
|
||||
Show Import Options İçe Aktarma Seçeneklerini Göster
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Her PDF, DXF veya metin dosyasını yerleştirmeden önce içe aktarma seçeneklerini sor; kapalıyken son seçilen seçenekleri kullan
|
||||
Stylistic Alternates Stilistik Alternatifler
|
||||
Swash çalkalama
|
||||
Swatch Conflict Renk Örneği Çatışması
|
||||
@@ -5868,7 +5870,7 @@ theme Appearance Görünüm
|
||||
Drawer menu Çekmece menüsü
|
||||
Toolbar: Show Controls Araç Çubuğu: Kontrolleri Göster
|
||||
@msg control must be fillStroke, coloring, drawMode or screenMode control fillStroke, coloring, drawMode veya screenMode olmalıdır
|
||||
@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode bilinmeyen kontrol `{name}`: fillStroke, colouring,drawMode veya screenMode
|
||||
@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode bilinmeyen kontrol `{name}`: fillStroke, coloring, drawMode veya screenMode
|
||||
@msg give a fraction `t` from 0 to 1 0'dan 1'e kadar bir `t` kesri verin
|
||||
@msg give the path `id` `id` yolunu ver
|
||||
@msg invalid stroke widths geçersiz kontur genişlikleri
|
||||
@@ -5891,7 +5893,7 @@ theme Appearance Görünüm
|
||||
Below Object Nesnenin altında
|
||||
Registration: Kayıt:
|
||||
Dimension Boyut
|
||||
Drawing : real size — 1:10 labels 1 unit on the page as 10. Çizim : Gerçek boyut — 1:10 etiketler sayfada 10 adet olarak 1 adettir.
|
||||
Drawing : real size — 1:10 labels 1 unit on the page as 10. Çizim : gerçek boyut — 1:10, sayfadaki 1 birimi 10 olarak etiketler.
|
||||
Preview (1 inch on the page) Önizleme (sayfada 1 inç)
|
||||
Set as Default Varsayılan Olarak Ayarla
|
||||
out from a highlighted edge to place its dimension | boyutunu yerleştirmek için vurgulanan kenardan dışarı |
|
||||
@@ -5929,7 +5931,7 @@ theme Appearance Görünüm
|
||||
@msg Measured segment no longer exists Ölçülen segment artık mevcut değil
|
||||
@msg Non-finite dimension Sonlu olmayan boyut
|
||||
@msg Only linear dimensions are horizontal or vertical Yalnızca doğrusal boyutlar yatay veya dikey olabilir
|
||||
@msg Scale must be drawing:real, for example 1:10 Ölçek çizim olmalıdır:gerçek, örneğin 1:10
|
||||
@msg Scale must be drawing:real, for example 1:10 Ölçek çizim:gerçek biçiminde olmalıdır, örneğin 1:10
|
||||
@msg Scale ratio must be between 1:1000000 and 1000000:1 Ölçek oranı 1:1000000 ile 1000000:1 arasında olmalıdır
|
||||
@msg Second measured segment no longer exists Ölçülen ikinci segment artık mevcut değil
|
||||
@msg Unknown dimension mode Bilinmeyen boyut modu
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3651,6 +3651,8 @@ effect Points Точки
|
||||
Swap Fill and Stroke (Shift+X) Змінити заливку та обведення (Shift+X)
|
||||
Swap start and end arrowheads Поміняти початкову та кінцеву стрілки
|
||||
Swap the selected object for the file, keeping its place and transform Замінити виділений об’єкт файлом, зберігши його положення та перетворення
|
||||
Show Import Options Показувати параметри імпорту
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запитувати параметри імпорту кожного файлу PDF, DXF чи текстового файлу перед розміщенням; якщо вимкнено, використовуються останні вибрані параметри
|
||||
Stylistic Alternates Стилістичні альтернативи
|
||||
Swash Розчерк
|
||||
Swatch Conflict Конфлікт зразків
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4025,6 +4025,8 @@ mark-style Japanese Kiểu Nhật
|
||||
Swap Fill and Stroke (Shift+X) Đổi màu tô và nét (Shift+X)
|
||||
Swap start and end arrowheads Đổi đầu mũi tên bắt đầu và kết thúc
|
||||
Swap the selected object for the file, keeping its place and transform Thay đối tượng đã chọn bằng tệp, giữ nguyên vị trí và biến đổi
|
||||
Show Import Options Hiện tùy chọn nhập
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Hỏi tùy chọn nhập của từng tệp PDF, DXF hoặc văn bản trước khi đặt; khi tắt, dùng các tùy chọn đã chọn gần nhất
|
||||
Stylistic Alternates Ký tự thay thế theo phong cách
|
||||
Swash Swash
|
||||
Swatch Conflict Xung đột mẫu màu
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 204 and column 5.
|
@@ -3472,6 +3472,8 @@ digits Malayalam 马拉雅拉姆数字
|
||||
Swap Fill and Stroke (Shift+X) 切换填色和描边 (Shift+X)
|
||||
Swap start and end arrowheads 对调起点与终点箭头
|
||||
Swap the selected object for the file, keeping its place and transform 以文件替换选择的对象,并保留其位置与变形
|
||||
Show Import Options 显示导入选项
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前询问每个 PDF、DXF 或文本文件的导入选项;关闭时使用上次选择的选项
|
||||
Stylistic Alternates 风格替代字
|
||||
Swash 花饰字
|
||||
Swatch Conflict 色板冲突
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4733,6 +4733,8 @@ digits Malayalam 馬來亞拉姆數字
|
||||
Swap Fill and Stroke (Shift+X) 對調填色與筆畫 (Shift+X)
|
||||
Swap start and end arrowheads 對調起點與終點箭頭
|
||||
Swap the selected object for the file, keeping its place and transform 以檔案取代選取的物件,並保留其位置與變形
|
||||
Show Import Options 顯示讀入選項
|
||||
Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前詢問每個 PDF、DXF 或文字檔案的讀入選項;關閉時使用上次選擇的選項
|
||||
Stylistic Alternates 風格替代字
|
||||
Swash 花體字
|
||||
Swatch Conflict 色票衝突
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -82,6 +82,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin
|
||||
std::borrow::Cow::Owned(d) => std::sync::Arc::new(d),
|
||||
}
|
||||
};
|
||||
fileio::check_linked_images("file.exportAs", f.id, st, &doc, params).map_err(|e| e.to_string())?;
|
||||
// A PDF shows its title in the viewer's title bar only when it is the document's own, not the
|
||||
// file name it was titled after, as `document.export` writes it.
|
||||
let own_title = fileio::has_own_title(&doc);
|
||||
|
||||
@@ -1367,7 +1367,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
|
||||
+99
-20
@@ -69,6 +69,11 @@ pub struct PlaceState {
|
||||
/// The Place dialog's lines about its files while they are read off the UI thread: the
|
||||
/// dialog's files, and the lines once they are read.
|
||||
reading_lines: Option<(Value, std::sync::mpsc::Receiver<Vec<String>>)>,
|
||||
/// The files of the loaded place cursor ask for their import options when clicked or dragged
|
||||
/// (the Place dialog loaded it with Show Import Options on).
|
||||
queue_asks: bool,
|
||||
/// The loaded cursor's files by name, with the size a click places them at.
|
||||
queue_sizes: Vec<(String, f64, f64)>,
|
||||
}
|
||||
|
||||
/// A place cursor thumbnail: decoded when the cursor is loaded, uploaded when first drawn (and
|
||||
@@ -107,9 +112,11 @@ fn engine(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result<Value, String
|
||||
// ---------- File → Place… ----------
|
||||
|
||||
/// File → Place… (`file.place`): with a file (`path` or `name` + `dataBase64`), place it, centred
|
||||
/// in the view unless `at`, `rect` or `replace` say otherwise (a text file without `text` options
|
||||
/// asks for them first); with `paths`, the Place dialog for them; with neither, pick the files
|
||||
/// first. The file is read and placed at once (MCP, scripts).
|
||||
/// in the view unless `at`, `rect` or `replace` say otherwise (a text file without `text` options,
|
||||
/// a DXF drawing without `dxf` options and a PDF with several pages or a password and no `page`
|
||||
/// ask for them first, unless `showImportOptions: false` places them with the options confirmed
|
||||
/// last); with `paths`, the Place dialog for them; with neither, pick the files first. The file is
|
||||
/// read and placed at once (MCP, scripts).
|
||||
pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
place_file(app, p, Read::AtOnce)
|
||||
}
|
||||
@@ -130,8 +137,27 @@ enum Read {
|
||||
}
|
||||
|
||||
fn place_file(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Value, String> {
|
||||
if p.get("text").is_none() && crate::dialogs::text_import::is_text(p) {
|
||||
return Ok(crate::dialogs::text_import::open(app, p));
|
||||
let show = match p.get("showImportOptions") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Bool(b)) => Some(*b),
|
||||
Some(_) => return Err("`showImportOptions` must be true or false".into()),
|
||||
};
|
||||
let ask = show.unwrap_or(true);
|
||||
let mut p = p.clone();
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.remove("showImportOptions");
|
||||
}
|
||||
if !ask {
|
||||
// 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);
|
||||
}
|
||||
if let Some(dxf) = crate::dialogs::dxf_import::last_options(app, &p) {
|
||||
p["dxf"] = dxf;
|
||||
}
|
||||
}
|
||||
if 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) {
|
||||
@@ -142,17 +168,21 @@ fn place_file(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Value,
|
||||
return Err("paths: give at least one file".into());
|
||||
}
|
||||
open_dialog(app, files);
|
||||
if let (Some(show), Some(d)) = (show, app.ui.dialog.as_mut()) {
|
||||
d.fields.insert("showImportOptions".into(), json!(show));
|
||||
}
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
// A PDF with several pages or a password asks for the page, box and password first.
|
||||
if crate::dialogs::import_pdf::offer_place(app, p) {
|
||||
// A PDF with several pages or a password asks for the page, box and password first; with
|
||||
// Show Import Options off, only an encrypted one asks, for its password.
|
||||
let offered = if ask { crate::dialogs::import_pdf::offer_place(app, &p) } else { crate::dialogs::import_pdf::offer_place_password(app, &p) };
|
||||
if offered {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
// A DXF drawing asks for its import options.
|
||||
if crate::dialogs::dxf_import::offer_place(app, p) {
|
||||
if ask && crate::dialogs::dxf_import::offer_place(app, &p) {
|
||||
return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND }));
|
||||
}
|
||||
let mut p = p.clone();
|
||||
if ["at", "rect", "replace"].iter().all(|k| p.get(k).is_none())
|
||||
&& let Some(v) = app.view()
|
||||
{
|
||||
@@ -203,6 +233,7 @@ fn open_dialog(app: &mut VectorcraftApp, files: Vec<Value>) {
|
||||
"link": app.ui.place_link,
|
||||
"template": false,
|
||||
"replace": false,
|
||||
"showImportOptions": app.ui.place_import_options,
|
||||
"__replace": files.len() == 1 && one_object,
|
||||
"__documents": linked.contains(&true),
|
||||
"__others": linked.contains(&false),
|
||||
@@ -319,15 +350,18 @@ fn fmt_ppi(v: f64) -> String {
|
||||
}
|
||||
|
||||
/// Place (the dialog's OK): one file is placed centred in the view (or replaces the selection);
|
||||
/// several load the place cursor.
|
||||
/// several load the place cursor. With Show Import Options on, each file that has import options
|
||||
/// asks for them before it is placed (the cursor's files when clicked or dragged); off, each is
|
||||
/// placed with the options confirmed last for its format.
|
||||
pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Value, String> {
|
||||
let files: Vec<Value> = d.fields.get("files").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let sources: Vec<Value> = files.iter().filter_map(|f| source(app, f)).collect();
|
||||
if sources.is_empty() {
|
||||
return Err("no files to place".into());
|
||||
}
|
||||
let (link, template) = (d.bool("link"), d.bool("template"));
|
||||
let (link, template, ask) = (d.bool("link"), d.bool("template"), d.bool("showImportOptions"));
|
||||
app.ui.place_link = link;
|
||||
app.ui.place_import_options = ask;
|
||||
app.ui.dialog = None;
|
||||
app.place.reading_lines = None;
|
||||
let r = match &sources[..] {
|
||||
@@ -335,6 +369,7 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
|
||||
let mut p = one.clone();
|
||||
p["link"] = json!(link);
|
||||
p["template"] = json!(template);
|
||||
p["showImportOptions"] = json!(ask);
|
||||
if d.bool("replace") && d.bool("__replace") {
|
||||
p["replace"] = json!(true);
|
||||
}
|
||||
@@ -343,7 +378,13 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
|
||||
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();
|
||||
queue_files(app, &json!({ "paths": paths, "files": files, "link": link, "template": template }), Read::ForUser { dropped: false })
|
||||
let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template });
|
||||
if !ask {
|
||||
// Each text file and DXF drawing in the cursor takes the options confirmed last.
|
||||
q["text"] = crate::dialogs::text_import::last_options(app);
|
||||
q["dxf"] = crate::dialogs::dxf_import::remembered(app);
|
||||
}
|
||||
queue_files(app, &q, Read::ForUser { dropped: false }, ask)
|
||||
}
|
||||
};
|
||||
app.place.picked.clear();
|
||||
@@ -355,35 +396,41 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
|
||||
/// `file.place.queue` with thumbnails for the cursor (unless `thumbnail` is given), the files read
|
||||
/// at once (MCP, scripts).
|
||||
pub fn queue(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
queue_files(app, p, Read::AtOnce)
|
||||
queue_files(app, p, Read::AtOnce, false)
|
||||
}
|
||||
|
||||
fn queue_files(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Value, String> {
|
||||
/// `file.place.queue` with `p`; `asks`: the cursor's files ask for their import options when placed.
|
||||
fn queue_files(app: &mut VectorcraftApp, p: &Value, read: Read, asks: bool) -> Result<Value, String> {
|
||||
let mut p = p.clone();
|
||||
if p.get("thumbnail").is_none() {
|
||||
p["thumbnail"] = json!(THUMB);
|
||||
}
|
||||
if matches!(read, Read::ForUser { .. }) && crate::placing::available(app) {
|
||||
let r = crate::placing::start_queue(app, &p);
|
||||
let r = crate::placing::start_queue(app, &p, asks);
|
||||
if let Err(e) = &r {
|
||||
app.status(e.clone());
|
||||
}
|
||||
return r;
|
||||
}
|
||||
let r = engine(app, "file.place.queue", &p)?;
|
||||
show_thumbnails(app, &r);
|
||||
show_thumbnails(app, &r, asks);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The file a click or drag of the place cursor places (`file.place` with `p`, its `rect` set):
|
||||
/// read off the UI thread where the files the user places are ([`crate::placing::start`]), else at
|
||||
/// once. An error shows in the status bar.
|
||||
/// once. When the Place dialog loaded the cursor with Show Import Options on, a file that has
|
||||
/// import options asks for them first (Cancel leaves it unplaced). An error shows in the status bar.
|
||||
pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) {
|
||||
// Read within the automation roots of whoever loaded the cursor, even on a click of the person
|
||||
// at the keyboard: an agent's queue reaches no file it wasn't given.
|
||||
let roots = app.session.place_queue_roots();
|
||||
vectorcraft_engine::file_access::confine(roots.as_ref(), || {
|
||||
if crate::placing::available(app) {
|
||||
if app.place.queue_asks {
|
||||
// Placing shows its own errors in the status bar.
|
||||
let p = clicked_at_full_size(app, p);
|
||||
let _ = place_file(app, &p, Read::ForUser { dropped: false });
|
||||
} else if crate::placing::available(app) {
|
||||
if let Err(e) = crate::placing::start(app, p, false) {
|
||||
app.status(e);
|
||||
}
|
||||
@@ -393,8 +440,40 @@ pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The cursor's thumbnails from `file.place.queue`'s reply `r`.
|
||||
pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value) {
|
||||
/// The params of a cursor click (`rect` at the file's queued size) on a PDF or DXF file, whose
|
||||
/// import options may change its size (another page, another scale): placed as its options place
|
||||
/// it at the click (`at`, the center of the box the click gave), as File › Place of that one file
|
||||
/// places it, instead of fitted into the box of the first page or the default scale. A drag keeps
|
||||
/// its `rect`; one to exactly the queued size gives the same `rect` as a click, and is taken as one.
|
||||
fn clicked_at_full_size(app: &VectorcraftApp, p: &Value) -> Value {
|
||||
let mut p = p.clone();
|
||||
let Some(name) = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::file_name) else { return p };
|
||||
if !matches!(fileio::extension(&name).as_str(), "pdf" | "ai" | "ait" | "dxf") {
|
||||
return p;
|
||||
}
|
||||
let r: Vec<f64> = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
|
||||
let [x, y, w, h] = r[..] else { return p };
|
||||
// Files of the same name in the cursor must all have that size: the place tool's request names
|
||||
// the file, not its place in the cursor.
|
||||
let mut same_name = app.place.queue_sizes.iter().filter(|(n, ..)| *n == name).peekable();
|
||||
let queued = same_name.peek().is_some() && same_name.all(|(_, qw, qh)| (qw - w).abs() < 1e-6 && (qh - h).abs() < 1e-6);
|
||||
if queued && let Some(o) = p.as_object_mut() {
|
||||
o.remove("rect");
|
||||
o.insert("at".into(), json!([x + w / 2.0, y + h / 2.0]));
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// The cursor's thumbnails and its files' sizes from `file.place.queue`'s reply `r` once the cursor
|
||||
/// is loaded; `asks`: its files ask for their import options when placed.
|
||||
pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) {
|
||||
app.place.queue_asks = asks;
|
||||
app.place.queue_sizes = r["files"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|f| Some((f["name"].as_str()?.to_string(), f["width"].as_f64()?, f["height"].as_f64()?)))
|
||||
.collect();
|
||||
app.place.thumbs = r["files"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
|
||||
@@ -21,10 +21,11 @@ use vectorcraft_engine::file_access::ScopeHandle;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// What was read: one file to place, the files to load the place cursor with, or a bitmap to paste.
|
||||
/// What was read: one file to place, the files to load the place cursor with (and whether they ask
|
||||
/// for their import options when placed), or a bitmap to paste.
|
||||
enum Read {
|
||||
Place(Box<PlaceRead>),
|
||||
Queue(QueueRead),
|
||||
Queue(QueueRead, bool),
|
||||
Paste(Box<Paste>),
|
||||
}
|
||||
|
||||
@@ -236,17 +237,18 @@ pub fn start(app: &mut VectorcraftApp, p: &Value, dropped: bool) -> Result<Value
|
||||
|
||||
/// `file.place.queue` with `p` for the active document, its files read and their thumbnails made off
|
||||
/// the UI thread → `{background: true, status}`; the place cursor is loaded once they are ready. When no thread could start, the cursor is loaded at once → `file.place.queue`'s reply.
|
||||
pub fn start_queue(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
/// `asks`: the cursor's files ask for their import options when placed ([`crate::place::show_thumbnails`]).
|
||||
pub fn start_queue(app: &mut VectorcraftApp, p: &Value, asks: bool) -> Result<Value, String> {
|
||||
let job = app.session.prepare_place_queue(p).map_err(|e| e.to_string())?;
|
||||
let names = job.names().join(", ");
|
||||
let started = spawn(app, names.clone(), names, false, move || job.read().map(Read::Queue).map_err(|e| e.to_string()))?;
|
||||
let started = spawn(app, names.clone(), names, false, move || job.read().map(|r| Read::Queue(r, asks)).map_err(|e| e.to_string()))?;
|
||||
match started {
|
||||
Some(r) => Ok(r),
|
||||
None => {
|
||||
let r = app.session.execute("file.place.queue", p).map_err(|e| e.to_string());
|
||||
app.sync_views();
|
||||
let r = r?;
|
||||
crate::place::show_thumbnails(app, &r);
|
||||
crate::place::show_thumbnails(app, &r, asks);
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
@@ -485,7 +487,9 @@ fn finish(app: &mut VectorcraftApp, p: &Pending, r: Result<Read, String>) {
|
||||
app.session.set_active(i);
|
||||
let r = match r {
|
||||
Ok(Read::Place(read)) => app.session.place_read(*read).map(|_| ()).map_err(|e| e.to_string()),
|
||||
Ok(Read::Queue(read)) => app.session.place_queue_read(read).map(|r| crate::place::show_thumbnails(app, &r)).map_err(|e| e.to_string()),
|
||||
Ok(Read::Queue(read, asks)) => {
|
||||
app.session.place_queue_read(read).map(|r| crate::place::show_thumbnails(app, &r, asks)).map_err(|e| e.to_string())
|
||||
}
|
||||
Ok(Read::Paste(paste)) => return finish_paste(app, *paste),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
@@ -1173,7 +1173,7 @@ fn a_file_whose_document_was_reverted_meanwhile_is_not_placed() {
|
||||
for kind in ["place", "drop", "queue"] {
|
||||
let (mut app, _) = saved_and_changed(app(true), &format!("reverted-{kind}"));
|
||||
let read = |app: &mut VectorcraftApp| match kind {
|
||||
"queue" => start_queue(app, &json!({"paths": [tif]})),
|
||||
"queue" => start_queue(app, &json!({"paths": [tif]}), false),
|
||||
_ => start(app, &json!({"path": tif}), kind == "drop"),
|
||||
};
|
||||
read(&mut app).unwrap();
|
||||
|
||||
@@ -749,6 +749,14 @@ pub struct UiState {
|
||||
/// File → Place: Link is on (the Place dialog remembers it).
|
||||
#[serde(default = "yes")]
|
||||
pub place_link: bool,
|
||||
/// File → Place: Show Import Options is on (the Place dialog remembers it). Each placed file
|
||||
/// with import options (a PDF's page and box, a DXF drawing, a text file) asks for them first;
|
||||
/// off, it is placed with the options last confirmed for its format.
|
||||
#[serde(default = "yes")]
|
||||
pub place_import_options: bool,
|
||||
/// The Text Import Options confirmed last (`file.place`'s `text` options; null: never used).
|
||||
#[serde(default)]
|
||||
pub text_import: Value,
|
||||
/// The file the open dialog reads, kept out of its JSON fields (Import PDF); dropped when no
|
||||
/// dialog is open.
|
||||
#[serde(skip)]
|
||||
@@ -1227,6 +1235,8 @@ impl Default for UiState {
|
||||
swatches_show_recent_colors: true,
|
||||
svg_options: Value::Null,
|
||||
place_link: true,
|
||||
place_import_options: true,
|
||||
text_import: Value::Null,
|
||||
dialog_file: None,
|
||||
made_text_style: vec![],
|
||||
pending_fonts: vec![],
|
||||
|
||||
@@ -189,7 +189,10 @@ impl VectorcraftApp {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (clip, svg, pdf) = (self.session.clipboard.clone(), self.session.prefs.copy_as_svg, self.session.prefs.copy_as_pdf);
|
||||
// An SVG that would name a linked image's file outside the read roots of the automation
|
||||
// that asked for the Copy is left out (decided now: the formats are made later).
|
||||
let svg = self.session.prefs.copy_as_svg && !self.session.clipboard_svg_refused();
|
||||
let (clip, pdf) = (self.session.clipboard.clone(), self.session.prefs.copy_as_pdf);
|
||||
let latest = self.clipboard_publishing.latest.clone();
|
||||
let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1);
|
||||
self.clipboard_publishing.pending = true;
|
||||
|
||||
@@ -272,6 +272,46 @@ fn control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `app.export`, and `file.exportAs` run as a command, write no SVG that would name a linked
|
||||
/// image's file outside the read root (Images: Link, Preserve Editing Capabilities), and the error
|
||||
/// names no file or folder. Embedded pixels are written; the person at the keyboard exports the
|
||||
/// link as stored.
|
||||
#[test]
|
||||
fn control_svg_export_refuses_a_linked_image_file_outside_the_read_root() {
|
||||
let (mut app, tx, base) = confined("svg-image");
|
||||
app.run("file.new", json!({"width": 100, "height": 50})).unwrap();
|
||||
let photo = s(base.join("outside/photo.png"));
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
std::fs::write(&photo, png).unwrap();
|
||||
app.run("file.place", json!({"path": photo, "link": true, "at": [50, 25]})).unwrap();
|
||||
let path = s(base.join("out/a.svg"));
|
||||
for (method, params) in [
|
||||
("app.export", json!({"path": path, "format": "svg", "images": "link", "wait": true})),
|
||||
("app.export", json!({"path": s(base.join("out/a.svgz")), "images": "link", "wait": true})),
|
||||
("app.export", json!({"format": "svg", "images": "link"})),
|
||||
("app.export", json!({"format": "svg", "preserveEditing": true})),
|
||||
("engine.execute", json!({"command": "file.exportAs", "params": {"path": path, "format": "svg", "images": "link"}})),
|
||||
] {
|
||||
let r = request(&mut app, &tx, method, params.clone());
|
||||
let e = r["error"].as_str().unwrap_or_default();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{method} {params}: {r}");
|
||||
assert!(!e.contains("photo.png") && !e.contains(&s(base.clone())), "{method} {params}: {r}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 0, "nothing written");
|
||||
let r = request(&mut app, &tx, "app.export", json!({"path": path, "format": "svg", "wait": true}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
let svg = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains(&photo), "{svg}");
|
||||
// The person at the keyboard isn't confined.
|
||||
app.run("file.exportAs", json!({"path": path, "format": "svg", "images": "link"})).unwrap();
|
||||
let svg = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `app.export` with a path writes the file when given an option only another format reads, and
|
||||
/// its warnings name that option, as `document.export`'s do without a path. `file.exportAs` run
|
||||
/// as a command does the same; an export that automation did not ask for gets no such note.
|
||||
|
||||
@@ -7,6 +7,7 @@ use egui::{Pos2, Shape, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::canvas::Xf;
|
||||
@@ -897,6 +898,179 @@ fn idle(app: &mut VectorcraftApp, ctx: &egui::Context, time: &mut f64, secs: f64
|
||||
/// while the window sits idle in the background, follows Update Links: Automatically: the app
|
||||
/// wakes itself to see the new link before the change, so the change isn't taken for the file as
|
||||
/// first seen.
|
||||
/// The text of the one selected type object.
|
||||
fn selected_text(app: &VectorcraftApp) -> String {
|
||||
let st = app.session.active().unwrap();
|
||||
let NodeKind::Text(t) = &st.doc.node(st.selection.objects[0]).unwrap().kind else { panic!("not type") };
|
||||
t.plain_text()
|
||||
}
|
||||
|
||||
/// The kind of the open dialog, if any.
|
||||
fn dialog_kind(app: &VectorcraftApp) -> Option<&str> {
|
||||
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
|
||||
}
|
||||
|
||||
const NOTES: &[u8] = b"one\r\ntwo\r\n\r\nthree\r\n";
|
||||
|
||||
/// A DXF drawing of one 100 × 50 line.
|
||||
const LINE_DXF: &[u8] = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n100\n21\n50\n0\nENDSEC\n0\nEOF\n";
|
||||
|
||||
#[test]
|
||||
fn show_import_options_is_a_place_option_saved_with_the_preferences() {
|
||||
let mut app = app();
|
||||
let dir = Folder::new("ui-place-show-import-options");
|
||||
let notes = dir.file("notes.txt", NOTES);
|
||||
app.run("file.place", json!({"paths": [notes]})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().expect("the Place dialog");
|
||||
assert!(d.bool("showImportOptions"), "on by default");
|
||||
let text = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert!(text.contains("Show Import Options"), "{text}");
|
||||
// On: the text file asks for its import options first.
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(dialog_kind(&app), Some(crate::dialogs::text_import::KIND));
|
||||
app.ui.dialog = None;
|
||||
// Off: it is placed at once, and the next Place dialog starts off.
|
||||
app.run("file.place", json!({"paths": [notes]})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("showImportOptions".into(), json!(false));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
assert!(selected_text(&app).contains("three"));
|
||||
assert!(!app.ui.place_import_options);
|
||||
app.run("file.place", json!({"paths": [notes]})).unwrap();
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().bool("showImportOptions"), "remembered");
|
||||
// `showImportOptions` given with `paths` sets the dialog's checkbox.
|
||||
app.run("file.place", json!({"paths": [notes], "showImportOptions": true})).unwrap();
|
||||
assert!(app.ui.dialog.as_ref().unwrap().bool("showImportOptions"));
|
||||
// Saved with the preferences; older preferences without it start on.
|
||||
let saved = serde_json::to_value(&app.ui).unwrap();
|
||||
assert_eq!(saved["place_import_options"], false);
|
||||
let old: crate::UiState = serde_json::from_value(json!({"place_link": false})).unwrap();
|
||||
assert!(old.place_import_options && old.text_import.is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_show_import_options_off_a_file_takes_the_options_confirmed_last() {
|
||||
let mut app = app();
|
||||
let b64 = vectorcraft_format::base64_encode;
|
||||
// Nothing confirmed yet: file.place's defaults.
|
||||
app.run("file.place", json!({"name": "a.txt", "dataBase64": b64(NOTES), "showImportOptions": false})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
let plain = selected_text(&app);
|
||||
// Text Import Options remembers what it confirmed, and the next text file starts from it.
|
||||
app.run("file.place", json!({"name": "b.txt", "dataBase64": b64(NOTES)})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), Some(crate::dialogs::text_import::KIND));
|
||||
for k in ["removeLineReturns", "removeParagraphReturns", "replaceSpaces"] {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), json!(true));
|
||||
}
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("spaces".into(), json!(4));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(selected_text(&app), "one two\nthree");
|
||||
assert_ne!(plain, "one two\nthree");
|
||||
app.run("file.place", json!({"name": "c.txt", "dataBase64": b64(NOTES)})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert!(d.bool("removeLineReturns") && d.bool("replaceSpaces"));
|
||||
assert_eq!(d.f64("spaces", 0.0), 4.0);
|
||||
app.ui.dialog = None;
|
||||
app.run("file.place", json!({"name": "d.txt", "dataBase64": b64(NOTES), "showImportOptions": false})).unwrap();
|
||||
assert_eq!((dialog_kind(&app), selected_text(&app).as_str()), (None, "one two\nthree"));
|
||||
// A DXF drawing: placed without asking, with the fit chosen last.
|
||||
let width = |app: &VectorcraftApp| {
|
||||
let st = app.session.active().unwrap();
|
||||
st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap().width()
|
||||
};
|
||||
app.run("file.place", json!({"name": "line.dxf", "dataBase64": b64(LINE_DXF), "showImportOptions": false})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
let unfitted = width(&app);
|
||||
app.ui.dxf_import = json!({"fit": true});
|
||||
app.run("file.place", json!({"name": "line.dxf", "dataBase64": b64(LINE_DXF), "showImportOptions": false})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
assert!(width(&app) > unfitted + 1.0, "fitted: {} vs {unfitted}", width(&app));
|
||||
app.run("file.place", json!({"name": "line.dxf", "dataBase64": b64(LINE_DXF)})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), Some(crate::dialogs::dxf_import::KIND), "on: it asks");
|
||||
app.ui.dialog = None;
|
||||
// A PDF with several pages: its first page, without asking.
|
||||
let pages = [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), PdfPage::new(300.0, 100.0, "1 0 0 rg 0 0 30 30 re f")];
|
||||
let two = pdf(&pages, None);
|
||||
app.run("file.place", json!({"name": "two.pdf", "dataBase64": b64(&two), "showImportOptions": false})).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
assert!((width(&app) - 100.0).abs() < 0.01, "page 1: {}", width(&app));
|
||||
// An encrypted PDF still asks for its password, and then places its first page.
|
||||
let locked = pdf(&pages, Some("pw"));
|
||||
app.run("file.place", json!({"name": "locked.pdf", "dataBase64": b64(&locked), "showImportOptions": false})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.bool("__locked")), Some(true));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("password".into(), json!("pw"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(dialog_kind(&app), None, "no page to pick");
|
||||
assert!((width(&app) - 100.0).abs() < 0.01, "page 1: {}", width(&app));
|
||||
// Given `page`, it asks for the password and places that page.
|
||||
app.run("file.place", json!({"name": "locked.pdf", "dataBase64": b64(&locked), "page": 2, "showImportOptions": false})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("password".into(), json!("pw"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!((width(&app) - 300.0).abs() < 0.01, "page 2: {}", width(&app));
|
||||
// A page past the last one is refused once the file is unlocked, not placed as another page.
|
||||
app.run("file.place", json!({"name": "locked.pdf", "dataBase64": b64(&locked), "page": 9, "showImportOptions": false})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("password".into(), json!("pw"));
|
||||
assert!(crate::dialogs::confirm(&mut app).is_err());
|
||||
app.ui.dialog = None;
|
||||
// A value that is not true or false is refused, and nothing is placed.
|
||||
let before = app.session.active().unwrap().history.undo.len();
|
||||
for bad in [json!("no"), json!(0)] {
|
||||
let e = app.run("file.place", json!({"name": "e.txt", "dataBase64": b64(NOTES), "showImportOptions": bad})).unwrap_err();
|
||||
assert!(e.contains("`showImportOptions` must be true or false"), "{e}");
|
||||
}
|
||||
assert_eq!((dialog_kind(&app), app.session.active().unwrap().history.undo.len()), (None, before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_place_cursors_files_ask_for_their_import_options_when_show_import_options_is_on() {
|
||||
let mut app = app();
|
||||
let dir = Folder::new("ui-place-cursor-import-options");
|
||||
let a = dir.file("a.png", &png(10, 10, 72.0));
|
||||
let notes = dir.file("notes.txt", NOTES);
|
||||
let click = json!({"path": notes, "rect": [10, 10, 200, 100]});
|
||||
// On: a click on the text file asks for its import options, and OK places it in the rect.
|
||||
app.run("file.place", json!({"paths": [a, notes]})).unwrap();
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.tool_options()["count"], 2);
|
||||
crate::place::place_from_cursor(&mut app, &click);
|
||||
assert_eq!(dialog_kind(&app), Some(crate::dialogs::text_import::KIND));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__params"]["rect"], json!([10, 10, 200, 100]));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert!(selected_text(&app).contains("three"));
|
||||
// A click on a PDF places the page chosen at its own size, centered where the click put the
|
||||
// first page; a drag keeps its box.
|
||||
let pages = [PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), PdfPage::new(300.0, 100.0, "1 0 0 rg 0 0 30 30 re f")];
|
||||
let two = dir.file("two.pdf", &pdf(&pages, None));
|
||||
app.run("file.place", json!({"paths": [a, two]})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("link".into(), json!(false));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
crate::place::place_from_cursor(&mut app, &json!({"path": two, "link": false, "rect": [10, 10, 100, 100]}));
|
||||
assert_eq!(dialog_kind(&app), Some("importPdf"));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__place"], json!({"link": false, "at": [60.0, 60.0]}));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!(2));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let b = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap();
|
||||
assert_eq!((b.width().round(), b.center()), (300.0, vectorcraft_geom::Point::new(60.0, 60.0)));
|
||||
crate::place::place_from_cursor(&mut app, &json!({"path": two, "link": false, "rect": [10, 10, 50, 50]}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__place"]["rect"], json!([10, 10, 50, 50]));
|
||||
app.ui.dialog = None;
|
||||
// Off: the cursor's files are placed at once, with the options confirmed last.
|
||||
app.run("file.place", json!({"paths": [a, notes]})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("showImportOptions".into(), json!(false));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.tool_options()["count"], 2);
|
||||
crate::place::place_from_cursor(&mut app, &click);
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
assert!(selected_text(&app).contains("three"));
|
||||
// A cursor loaded by file.place.queue places at once, as before.
|
||||
app.run("file.place", json!({"paths": [a, notes]})).unwrap();
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
app.run("file.place.queue", json!({"paths": [a, notes]})).unwrap();
|
||||
crate::place::place_from_cursor(&mut app, &click);
|
||||
assert_eq!(dialog_kind(&app), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_placed_while_idle_follows_its_changes() {
|
||||
let mut app = app();
|
||||
|
||||
+32
@@ -246,6 +246,21 @@ the suite) keep the agent to the folders you give it:
|
||||
without a path of a document whose own format is SVG or SVGZ), `file.exportAs`, and the SVG Options dialog's
|
||||
Show Code. A file given as another URL (`https://…`) is not checked. The document keeps the link, and the
|
||||
person at the keyboard exports it as stored.
|
||||
- The same SVG and SVGZ outputs are refused with "a linked image file is outside the read roots", which names no
|
||||
file or folder, when the file would name a linked image's file outside the read roots (a path, a `file:` URL,
|
||||
or a relative path taken from the document's folder). An `<image>` names the file with `images: "link"`, and
|
||||
with `embed` when the document holds no pixels for the image. An image colorized with a solid fill names
|
||||
no file when its pixels are gray (the file gets the colorized pixels) or missing (the file leaves it out).
|
||||
With `preserveEditing`, the document the SVG carries names every linked image and placed file, the relative
|
||||
paths kept of them and each data set's image, in every symbol, pattern, graph design and brush, used or not,
|
||||
colorized or not, and a stored brush entry that does not read as a brush is refused too, since its links
|
||||
cannot be checked. Otherwise the images of the art the file writes,
|
||||
in opacity masks and in the symbols, patterns and brushes that art uses, are checked: hidden layers and
|
||||
objects only with `hiddenLayers` (a save keeps them unless it is `false`), and template layers and the
|
||||
layer of opacity-mask or symbol editing mode never. `selectedOnly` and `document.exportSelection` check the
|
||||
selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from
|
||||
the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the
|
||||
system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked.
|
||||
- `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths
|
||||
outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in
|
||||
folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source`
|
||||
@@ -7007,6 +7022,23 @@ with `pointer_gesture` (a click places at 100% with the top-left corner there, a
|
||||
`file.place.info` refuse, of the keys each one takes, a `link`, `replace` or `template` that is not true or false and a `thumbnail` that is not a
|
||||
number, naming the key, and place nothing; null is the same as leaving the key out.
|
||||
|
||||
In the app, `file.place` asks for a file's import options before placing it: a text file without `text` (Text Import
|
||||
Options), a DXF drawing without `dxf` (DXF Import Options), and a PDF, `.ai` or `.ait` file with several pages or a
|
||||
password and no `page` (Place PDF). `showImportOptions: false` places such a file without asking, with the options
|
||||
last confirmed in its dialog: the text options, and the DXF fit, lineweight, centering and layer choices with the
|
||||
drawing at 1:1 in its own unit. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no
|
||||
`password` still asks for the password. A `showImportOptions` that is not true or false is refused, and nothing is placed. The
|
||||
Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and
|
||||
Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)).
|
||||
It is on by default and saved with the preferences. On, each file that has import options asks for them before it is
|
||||
placed, also each file of the place cursor when it is clicked or dragged (Cancel leaves that file unplaced). A click on
|
||||
a PDF or DXF file places it as its options place it with `at` at the center of the box the click gave (a PDF's page at
|
||||
its own size, a DXF drawing at its scale, or on the artboard there when fitted or not centered), and a drag to any other
|
||||
size fits it into the dragged box (a drag to exactly the file's queued size gives the place tool the same box as a click and
|
||||
is placed as one). Off, each
|
||||
file is placed with the options last confirmed for its format. The default, and the options a file is placed with
|
||||
when the checkbox is off, are VectorCraft's own choices.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/photo.jpg","at":[300,200]}}}
|
||||
{"name":"run_command","arguments":{"command":"file.place","params":{"name":"logo.svg","dataBase64":"PHN2Zy…","rect":[0,0,100,100]}}}
|
||||
|
||||
@@ -856,6 +856,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`).
|
||||
- Document replies under `--automation-read-root`: `document.inspect` gives `path` as null for a document file outside the read roots, and `document.json` names a linked image or placed file outside them by its file name alone, without its relative path, size or date, brush art included, leaves out a relative path that leads outside them and a stored brush entry that does not read as a brush, names a data set's image value outside them by its file name, and leaves an Export for Screens folder outside them out of `export_settings`; the document is not changed. `crates/engine/src/tests/placed_document.rs` (`document_replies_leave_out_paths_outside_the_read_roots`, `document_json_checks_brush_art_and_relative_paths_against_the_read_roots`).
|
||||
- SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`).
|
||||
- Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`).
|
||||
- Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`.
|
||||
- Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/<file name>` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/<file name> (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`.
|
||||
- Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`.
|
||||
@@ -1862,6 +1863,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`).
|
||||
- Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`).
|
||||
- File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`).
|
||||
- The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`).
|
||||
- Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged.
|
||||
- Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged.
|
||||
- A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626).
|
||||
|
||||
Reference in New Issue
Block a user