mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge pull request #9099 from dotCooCoo/feat/print-per-job-settings
Print: Print as Bitmap prints at advanced.bitmapResolution
This commit is contained in:
39 files changed
+2171
-215
No files matched your search
@@ -124,6 +124,10 @@ pub(super) use colors::of_color as color_data;
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS, REMOVE_ALL_VISITS};
|
||||
#[cfg(test)]
|
||||
pub(crate) use print::postscript_name;
|
||||
#[cfg(test)]
|
||||
pub(crate) use save_open::with_extension;
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//! - `print` with `jobOptions.file` writes a file, a `File` the script may write
|
||||
//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the
|
||||
//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise.
|
||||
//! The PostScript is level 2 when `postScriptLevel` is not assigned, the default it reads as.
|
||||
//! - `print` without a file prepares a job for the printer `printerName` names, or for the
|
||||
//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a
|
||||
//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name
|
||||
@@ -36,6 +37,7 @@
|
||||
//! - A property the help pages list that is not mapped accepts the default its help page gives
|
||||
//! and throws an error that says it is not available yet at any other value.
|
||||
//! - `fitToPage` set to true wins over the scale factors and the tiling mode.
|
||||
//! With no scale or tiling assigned, false clears a base fit mode and preserves other base scaling modes.
|
||||
//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range
|
||||
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
|
||||
//! replaces the range of the settings `print` starts from, which prints when those settings
|
||||
@@ -46,6 +48,9 @@
|
||||
//! with another extension.
|
||||
//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps its value in the
|
||||
//! settings `print` starts from.
|
||||
//! - `bitmapResolution` is `file.print`'s `advanced.bitmapResolution`: 0 prints at the document's
|
||||
//! raster effects resolution, and 1 to 9600 ppi at that resolution; `print` throws, before
|
||||
//! anything is written, for a value between 0 and 1.
|
||||
//! - `print` throws, before anything is written, when an assigned `artboardRange` names an artboard
|
||||
//! the document does not have, also with `printAllArtboards` true; when `printPreset` or
|
||||
//! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is
|
||||
@@ -54,6 +59,7 @@
|
||||
//! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces,
|
||||
//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked
|
||||
//! name goes to `file.print` without the spaces around it. `PPDName` takes only the empty string.
|
||||
//! Paper `width` and `height` take 0 (not assigned) or 72 to 14,400 pt.
|
||||
//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects.
|
||||
//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects,
|
||||
//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no
|
||||
@@ -150,8 +156,8 @@ const PDF_OVERPRINT: &[&str] = &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"];
|
||||
const POSTSCRIPT_IMAGE_COMPRESSION: &[&str] = &["IMAGECOMPRESSIONNONE", "JPEG", "RLE"];
|
||||
const POSTSCRIPT_LEVEL: &[&str] = &["PSLEVEL1", "PSLEVEL2", "PSLEVEL3"];
|
||||
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` comes from
|
||||
/// [`super::save_open::ENUMS`].
|
||||
/// The enumerations these members use, as `dom`'s are made. `PDFOverprint` and `PageMarksTypes`
|
||||
/// come from [`super::save_open::ENUMS`].
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintColorProfile", PRINT_COLOR_PROFILE),
|
||||
("PrintColorIntent", PRINT_COLOR_INTENT),
|
||||
@@ -163,7 +169,6 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("PrintingBounds", PRINTING_BOUNDS),
|
||||
("PrintFontDownloadMode", PRINT_FONT_DOWNLOAD_MODE),
|
||||
("FontSubstitutionPolicy", FONT_SUBSTITUTION_POLICY),
|
||||
("PageMarksTypes", PAGE_MARKS_TYPES),
|
||||
("PostScriptImageCompressionType", POSTSCRIPT_IMAGE_COMPRESSION),
|
||||
("PrinterPostScriptLevelEnum", POSTSCRIPT_LEVEL),
|
||||
];
|
||||
@@ -176,6 +181,8 @@ enum Kind {
|
||||
Number(f64, f64),
|
||||
/// A whole number from the first to the second.
|
||||
Whole(u64, u64),
|
||||
/// A paper side in points: 0 (not assigned) or a custom size from 72 to 14,400.
|
||||
PaperSize,
|
||||
Text,
|
||||
/// A value of the enumeration (its name and members); only the members in the last list are
|
||||
/// available.
|
||||
@@ -209,7 +216,7 @@ impl Start {
|
||||
|
||||
fn matches(self, kind: Kind, d: &Data) -> bool {
|
||||
match (self, d) {
|
||||
(Start::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9,
|
||||
(Start::Num(a), Data::Number(b)) => a == *b,
|
||||
(Start::None, _) => false,
|
||||
_ => self.value(kind) == *d,
|
||||
}
|
||||
@@ -264,7 +271,7 @@ const JOB: Class = Class {
|
||||
name: "PrintJobOptions",
|
||||
fields: &[
|
||||
f("artboardRange", Kind::Text, Start::Text("1-")),
|
||||
kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)),
|
||||
f("bitmapResolution", Kind::Number(0.0, vectorcraft_pdf::MAX_BITMAP_RESOLUTION), Start::Num(0.0)),
|
||||
f("collate", Kind::Bool, Start::Bool(false)),
|
||||
f("copies", Kind::Whole(1, 999), Start::Num(1.0)),
|
||||
f(
|
||||
@@ -355,14 +362,18 @@ const MARKS: Class = Class {
|
||||
const PAPER: Class = Class {
|
||||
name: "PrintPaperOptions",
|
||||
fields: &[
|
||||
f("height", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("height", Kind::PaperSize, Start::Num(0.0)),
|
||||
f("name", Kind::Text, Start::None),
|
||||
kept("offset", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("transverse", Kind::Bool, Start::Bool(false)),
|
||||
f("width", Kind::Number(0.0, 14_400.0), Start::Num(0.0)),
|
||||
f("width", Kind::PaperSize, Start::Num(0.0)),
|
||||
],
|
||||
};
|
||||
|
||||
/// The custom paper sizes `file.print` takes, in points.
|
||||
const MIN_PAPER: f64 = 72.0;
|
||||
const MAX_PAPER: f64 = 14_400.0;
|
||||
|
||||
const POSTSCRIPT: Class = Class {
|
||||
name: "PrintPostScriptOptions",
|
||||
fields: &[
|
||||
@@ -440,6 +451,14 @@ fn checked(h: &Host, class: &Class, field: &Field, d: &Data) -> std::result::Res
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::PaperSize => match d {
|
||||
Data::Number(n) if n.is_finite() => {
|
||||
if *n != 0.0 && !(MIN_PAPER..=MAX_PAPER).contains(n) {
|
||||
return Err(HostError::Range(format!("{what} must be 0 or from {MIN_PAPER} to {MAX_PAPER}")));
|
||||
}
|
||||
}
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
},
|
||||
Kind::Whole(lo, hi) => match d {
|
||||
Data::Number(n) => {
|
||||
if !whole(*n).is_some_and(|n| (lo..=hi).contains(&n)) {
|
||||
@@ -529,6 +548,7 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
|
||||
/// What a `PrintOptions` asks `file.print` for.
|
||||
#[derive(Default)]
|
||||
struct Job {
|
||||
clear_fit: bool,
|
||||
preset: Option<String>,
|
||||
file: Option<Data>,
|
||||
/// The assigned `printerName`.
|
||||
@@ -545,10 +565,12 @@ struct Job {
|
||||
paper_size: bool,
|
||||
/// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says.
|
||||
source: bool,
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` must name the profile.
|
||||
/// `colorProfileMode` is assigned `CUSTOMPROFILE`: `name` or the base settings must name the profile.
|
||||
custom: bool,
|
||||
/// `printArea` is assigned: the artboards print even when the base settings ignore them.
|
||||
print_area: bool,
|
||||
/// `position` is assigned: an untiled job does not use the saved Print Tiling origin.
|
||||
position: bool,
|
||||
/// The groups of `settings`: the top level and each nested object by its key.
|
||||
top: Map<String, Value>,
|
||||
groups: Vec<(&'static str, Map<String, Value>)>,
|
||||
@@ -675,6 +697,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
"printAsBitmap" => {
|
||||
job.group("advanced").insert("printAsBitmap".into(), json!(flag(v)));
|
||||
}
|
||||
"bitmapResolution" => {
|
||||
job.group("advanced").insert("bitmapResolution".into(), json!(number_of(v)));
|
||||
}
|
||||
"file" => job.file = Some(v.clone()),
|
||||
"artboardRange" => {
|
||||
job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty());
|
||||
@@ -683,6 +708,9 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) {
|
||||
if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) {
|
||||
s.insert("range".into(), json!(range));
|
||||
}
|
||||
if job.range.is_none() && value("printAllArtboards").is_none() {
|
||||
s.insert("artboards".into(), json!("all"));
|
||||
}
|
||||
}
|
||||
"printArea" => job.print_area = true,
|
||||
_ => {}
|
||||
@@ -756,11 +784,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
Some(t)
|
||||
} else if scaled {
|
||||
Some("custom")
|
||||
} else if fit.is_some() || tiling.is_some() {
|
||||
} else if tiling.is_some() {
|
||||
Some("none")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
job.clear_fit = fit == Some(false) && scaling.is_none();
|
||||
if let Some(scaling) = scaling {
|
||||
job.top.insert("scaling".into(), json!(scaling));
|
||||
}
|
||||
@@ -809,6 +838,7 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
|
||||
_ => "center",
|
||||
};
|
||||
job.group("placement").insert("origin".into(), json!(origin));
|
||||
job.position = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -874,6 +904,10 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn postscript_name(path: &str, windows: bool) -> bool {
|
||||
super::save_open::filename_for_suffix(path, windows).to_lowercase().ends_with(".ps")
|
||||
}
|
||||
|
||||
/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names,
|
||||
/// with the assigned options over the document's print settings, or without a file the job for a
|
||||
/// printer ([`prepare`]).
|
||||
@@ -890,11 +924,15 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(file) = job.file.take() else { return prepare(h, doc, job) };
|
||||
check_names(h, doc, &mut job)?;
|
||||
let path = file_path(&file, "print")?;
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || postscript_name(path, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
let mut p = print_params(&mut job);
|
||||
// The format follows the name `jobOptions.file` gives, not the real path a link leads to.
|
||||
let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps";
|
||||
p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" }));
|
||||
// PostScript prints at the level the options read as: an unassigned `postScriptLevel` is `PSLEVEL2`.
|
||||
if postscript {
|
||||
p.insert("level".into(), json!(job.level.unwrap_or(2)));
|
||||
}
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?;
|
||||
// What the job lost or how its options apply: one Script Console line each.
|
||||
@@ -997,21 +1035,38 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
|
||||
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
(st.doc.artboards.len(), mode == Some("ignore"))
|
||||
let scaling = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str);
|
||||
let profile = st.doc.print_setup.as_ref().and_then(|v| v.get("color")).and_then(|v| v.get("profile")).and_then(Value::as_str);
|
||||
let tiled = matches!(scaling, Some("tileFull" | "tileImageable"));
|
||||
(st.doc.artboards.len(), mode == Some("ignore"), scaling == Some("fit"), tiled, profile.unwrap_or("").to_string())
|
||||
});
|
||||
if let Some(range) = &job.range {
|
||||
vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut base_ignore = saved_ignore;
|
||||
let mut base_fit = saved_fit;
|
||||
let mut base_tiled = saved_tiled;
|
||||
if let Some(name) = job.preset.take() {
|
||||
let n = plain_name("PrintOptions.printPreset", "print preset", &name)?;
|
||||
let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?;
|
||||
base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore);
|
||||
base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit);
|
||||
base_tiled = preset.scaling.tiles();
|
||||
base_profile.clone_from(&preset.color.profile);
|
||||
job.preset = Some(n.to_string());
|
||||
}
|
||||
if job.clear_fit && base_fit {
|
||||
job.top.insert("scaling".into(), json!("none"));
|
||||
}
|
||||
// A placed Print Tiling origin replaces the placement, so an assigned `position` clears it
|
||||
// for this job when the job does not tile; the saved settings keep it.
|
||||
let tiled = job.top.get("scaling").and_then(Value::as_str).map_or(base_tiled, |s| matches!(s, "tileFull" | "tileImageable"));
|
||||
if job.position && !tiled {
|
||||
job.group("tileOrigin").insert("placed".into(), json!(false));
|
||||
}
|
||||
// An assigned `printArea` prints by artboard when the base settings ignore the artboards: the
|
||||
// assigned `artboardRange` when there is one, otherwise every artboard.
|
||||
if job.print_area && base_ignore && !job.top.contains_key("artboards") {
|
||||
@@ -1025,9 +1080,6 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
}
|
||||
job.group("advanced").insert("flattenerPreset".into(), json!(n));
|
||||
}
|
||||
if job.custom && job.profile.is_none() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.profile.take() {
|
||||
let what = "PrintColorManagementOptions.name";
|
||||
let n = plain_name(what, "color profile", &name)?;
|
||||
@@ -1039,6 +1091,8 @@ fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), Hos
|
||||
if !job.source {
|
||||
job.group("color").insert("profile".into(), json!(profile.name));
|
||||
}
|
||||
} else if job.custom && base_profile.trim().is_empty() {
|
||||
return Err(HostError::Error("PrintColorManagementOptions.name must name a color profile for CUSTOMPROFILE".into()));
|
||||
}
|
||||
if let Some(name) = job.paper.take() {
|
||||
let n = plain_name("PrintPaperOptions.name", "paper", &name)?;
|
||||
@@ -1155,10 +1209,16 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
fn field_info(field: &Field) -> MemberInfo {
|
||||
match field.kind {
|
||||
Kind::Bool => typed("boolean"),
|
||||
// A field with no upper limit, such as `bitmapResolution`, reports no maximum.
|
||||
// A field with no upper limit reports no maximum.
|
||||
Kind::Number(min, max) => MemberInfo { min: Some(min), max: (max < f64::MAX).then_some(max), ..typed("number") },
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
Kind::Whole(min, max) => MemberInfo { min: Some(min as f64), max: Some(max as f64), ..typed("number") },
|
||||
Kind::PaperSize => MemberInfo {
|
||||
min: Some(0.0),
|
||||
max: Some(MAX_PAPER),
|
||||
description: Some(format!("0 (not assigned) or a custom size from {MIN_PAPER} to {MAX_PAPER} pt")),
|
||||
..typed("number")
|
||||
},
|
||||
Kind::Text => typed("string"),
|
||||
Kind::Choice(name, _, _) | Kind::Child(name) => typed(name),
|
||||
Kind::File => typed("File"),
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
|
||||
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
|
||||
//! - Each method sends command warnings to the Script Console with its name as the prefix.
|
||||
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
|
||||
//! commands a script runs never show a dialog, so the level does not change what they do, and it
|
||||
//! never allows a file the script's grants do not.
|
||||
@@ -919,7 +920,7 @@ pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
|
||||
/// a linked image an open could not read. → the command's answer.
|
||||
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
|
||||
let (answer, value) = super::super::command_value(h, id, p)?;
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().take(super::MAX_LISTED).filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
Ok(answer)
|
||||
@@ -963,8 +964,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
let given_options = given(arg(a, 2));
|
||||
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
|
||||
// object of that format's class holds.
|
||||
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c));
|
||||
let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id);
|
||||
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c));
|
||||
if let Some(o) = given_options.or(by_extension.as_ref()) {
|
||||
let name = typename(o);
|
||||
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
|
||||
@@ -982,20 +983,38 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
} else if !q.is_empty() {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
} else {
|
||||
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
|
||||
}
|
||||
// Without options, the format of the file name as the platform reads it (on Windows, without
|
||||
// trailing dots and spaces), else the document's own.
|
||||
if !p.contains_key("format") {
|
||||
let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format));
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.saveAs", "file.saveAs", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `path` with the extension of `kind` added, unless its name already ends with one of them.
|
||||
fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String {
|
||||
let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions };
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase();
|
||||
fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> {
|
||||
let name = filename_for_suffix(path, windows);
|
||||
// A name that is only a dot and an extension, such as `.pdf`, picks its format only for the
|
||||
// `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule.
|
||||
match name.rsplit_once('.') {
|
||||
Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => {
|
||||
crate::cmd::fileio::format_for_name(&format!("x.{extension}"))
|
||||
}
|
||||
_ => crate::cmd::fileio::format_for_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filename_for_suffix(path: &str, windows: bool) -> &str {
|
||||
let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path);
|
||||
if windows { name.trim_end_matches(['.', ' ']) } else { name }
|
||||
}
|
||||
|
||||
pub(crate) fn with_extension(path: &str, extensions: &[&str], windows: bool) -> String {
|
||||
let name = filename_for_suffix(path, windows).to_lowercase();
|
||||
match extensions.first() {
|
||||
Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"),
|
||||
_ => path.to_string(),
|
||||
@@ -1058,10 +1077,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
} else {
|
||||
p.insert("useArtboards".into(), json!(false));
|
||||
}
|
||||
let named = with_extension(path, &kind, svgz);
|
||||
let named = with_extension(path, if svgz { &["svgz"] } else { kind.extensions }, cfg!(windows));
|
||||
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
|
||||
p.insert("path".into(), json!(plain(real)?));
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportFile", "document.export", &Value::Object(p))))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1110,9 +1129,19 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
// The document's size is read before any of it is; a placed image keeps its own limit and message.
|
||||
if std::fs::metadata(&real).is_ok_and(|m| m.len() > super::super::files::MAX_OPEN_BYTES) {
|
||||
return Err(refused(super::super::files::OPEN_TOO_LARGE, path));
|
||||
}
|
||||
plain(real)?;
|
||||
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
|
||||
let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?;
|
||||
let r = crate::cmd::fileio::with_read_limit(super::super::files::MAX_OPEN_BYTES as usize, || {
|
||||
exactly(h, || warned(h, "app.open", "document.open", &Value::Object(p)))
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
HostError::Error(message) if message == crate::cmd::fileio::READ_TOO_LARGE => refused(super::super::files::OPEN_TOO_LARGE, path),
|
||||
e => e,
|
||||
})?;
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
@@ -1283,7 +1312,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = super::with_doc(h, doc, |_, st| st.title());
|
||||
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
|
||||
let p = json!({"path": plain(real)?, "format": format});
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.close", "file.saveAs", &p)))?;
|
||||
}
|
||||
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
|
||||
}
|
||||
@@ -1340,3 +1369,37 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod save_format_tests {
|
||||
use super::save_format_for_name;
|
||||
|
||||
#[test]
|
||||
fn save_as_selects_the_format_from_windows_filename_aliases() {
|
||||
for extension in ["svg", "svgz", "ai", "eps", "pdf"] {
|
||||
for suffix in [".", " ", ". . ", "..."] {
|
||||
for prefix in ["", "/exports/", "C:\\exports\\"] {
|
||||
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
|
||||
assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}");
|
||||
assert!(save_format_for_name(&name, false).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] {
|
||||
assert!(save_format_for_name(name, true).is_none(), "{name}");
|
||||
}
|
||||
// Production passes `cfg!(windows)`; a Windows host still splits this name at the backslash.
|
||||
#[cfg(unix)]
|
||||
assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg"));
|
||||
#[cfg(windows)]
|
||||
assert!(save_format_for_name("proof\\.svg", false).is_none());
|
||||
for windows in [false, true] {
|
||||
assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf"));
|
||||
assert!(save_format_for_name(".svg", windows).is_none());
|
||||
assert!(save_format_for_name("/exports/.png", windows).is_none());
|
||||
assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps"));
|
||||
assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg"));
|
||||
assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -478,7 +478,7 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer {
|
||||
for items in exports {
|
||||
let mut p = base.clone();
|
||||
p.extend(items);
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "Document.exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
|
||||
@@ -108,6 +108,9 @@ pub const MAX_MASK_STEPS: usize = 1 << 24;
|
||||
|
||||
pub(crate) const ACCESS_DENIED: &str = "Script file access denied";
|
||||
pub(crate) const TOO_LARGE: &str = "Script file exceeds 8 MiB";
|
||||
/// The largest document `app.open` reads, checked before the file is read.
|
||||
pub(crate) const MAX_OPEN_BYTES: u64 = 256 << 20;
|
||||
pub(crate) const OPEN_TOO_LARGE: &str = "Script document exceeds 256 MiB";
|
||||
pub(crate) const NOT_OPEN: &str = "Script file is not open";
|
||||
pub(crate) const UNDECODABLE: &str = "Script file cannot be decoded";
|
||||
pub(crate) const NOT_REGULAR: &str = "Script file is not a regular file";
|
||||
@@ -750,7 +753,7 @@ impl Disk {
|
||||
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
|
||||
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
|
||||
};
|
||||
if !real.is_file() {
|
||||
if !std::fs::metadata(&real).map_err(|_| READ_FAILED)?.is_file() {
|
||||
return Err(NOT_REGULAR);
|
||||
}
|
||||
Ok(real)
|
||||
|
||||
Reference in new issue
Block a user