Merge pull request #10153 from dotCooCoo/fix/file-new-rejects-bad-rows

New Document: file.new refuses artboard counts that are not whole numbers
This commit is contained in:
.CooCoo
2026-12-01 09:47:36 -08:00
committed by GitHub
6 changed files with 111 additions and 25 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
+28 -21
View File
@@ -299,7 +299,11 @@ impl DocSettings {
}
/// These settings with `p`'s changes (the params of `file.new`) → validated.
pub fn with_params(mut self, p: &Value, cmd: &str) -> Result<Self> {
pub fn with_params(self, p: &Value, cmd: &str) -> Result<Self> {
self.with_params_inner(p, cmd, false)
}
fn with_params_inner(mut self, p: &Value, cmd: &str, replaying: bool) -> Result<Self> {
if let Some(u) = p.get("units").filter(|v| !v.is_null()) {
let u = u.as_str().unwrap_or("");
self.units = Unit::named(u).ok_or_else(|| bad(cmd, format!("unknown units `{u}`")))?;
@@ -329,11 +333,11 @@ impl DocSettings {
Some(o) => return Err(bad(cmd, format!("orientation must be portrait or landscape, not `{o}`"))),
}
if let Some(n) = p.get("artboards").filter(|v| !v.is_null()) {
let n = n.as_f64().filter(|n| n.is_finite()).ok_or_else(|| bad(cmd, "artboards must be a number"))?;
self.artboards = n.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32;
self.artboards = if replaying { n.as_f64().map(|n| n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32) } else { count(n) }
.ok_or_else(|| bad(cmd, format!("artboards must be a whole number from 1 to {MAX_ARTBOARDS}")))?;
}
if let Some(l) = p.get("artboardLayout").filter(|v| !v.is_null()) {
self.layout_params(l, cmd)?;
self.layout_params(l, cmd, replaying)?;
}
if let Some(b) = p.get("bleed").filter(|v| !v.is_null()) {
self.bleed = super::docsetup::bleed_param(b, self.bleed, cmd)?;
@@ -371,7 +375,7 @@ impl DocSettings {
}
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
if let Some(id) = l.as_str() {
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
@@ -380,25 +384,22 @@ impl DocSettings {
}
return Ok(());
}
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?;
for (k, v) in o {
match k.as_str() {
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
"columns" => {
self.columns = v
.as_f64()
.filter(|c| c.is_finite() && *c >= 1.0)
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
.round()
.min(MAX_ARTBOARDS as f64) as u32
self.columns =
if replaying { v.as_f64().filter(|n| *n >= 1.0).map(|n| n.round().min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) }
.ok_or_else(|| bad(cmd, format!("artboardLayout.columns must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"rows" => {
self.rows = v
.as_f64()
.map(f64::round)
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
.map(|r| r as u32)
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
self.rows = if replaying {
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
} else {
count(v)
}
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))?
}
"spacing" => {
self.spacing = v
@@ -407,7 +408,7 @@ impl DocSettings {
.ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))?
}
"rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?,
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))),
}
}
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
@@ -610,6 +611,12 @@ fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
}
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
/// to [`MAX_ARTBOARDS`]; anything else is `None`.
fn count(v: &Value) -> Option<u32> {
v.as_f64().filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
}
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
@@ -871,7 +878,7 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
let size = str_param(p, "preset").map(|_| sorted(&base));
let mut settings = base.with_params(p, C)?;
let mut settings = base.with_params_inner(p, C, s.replaying())?;
if size != Some(sorted(&settings)) {
settings.name = "Custom".into();
}
@@ -956,7 +963,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
None => s.default_settings(),
};
let mut preset = base.with_params(p, C)?;
let mut preset = base.with_params_inner(p, C, s.replaying())?;
preset.name = name.to_string();
let saved = &mut s.prefs.new_doc_presets;
match saved.iter_mut().find(|q| q.name.eq_ignore_ascii_case(name)) {
+73
View File
@@ -173,6 +173,79 @@ fn ppi_overprint_preview_and_bad_params() {
}
}
/// Artboard counts, columns and rows are whole numbers in range: a fraction or a count outside
/// 1 to 1000 is an error, not rounded or clamped to one.
#[test]
fn counts_that_are_not_whole_or_out_of_range_are_errors() {
for p in [
json!({"artboards": 2.4}),
json!({"artboards": 0}),
json!({"artboards": -0.5}),
json!({"artboards": 1001}),
json!({"artboardLayout": {"columns": 2.4}}),
json!({"artboardLayout": {"columns": 1001}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 2.4}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.6}}),
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1000.4}}),
] {
let mut s = Session::new();
assert!(s.execute("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}: no document on an error");
}
let s = new_doc(json!({"artboards": 6.0, "artboardLayout": {"layout": "gridByColumn", "rows": 2.0}}));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 6, "a whole number written 6.0 is a count");
}
#[test]
fn replaying_a_journal_rounds_an_older_artboard_count() {
let mut recorded = new_doc(json!({"artboards": 2}));
recorded.journal.last_mut().unwrap().1["artboards"] = json!(2.4);
let mut s = Session::new();
for (id, p) in &recorded.journal {
s.replay(id, p).unwrap();
}
assert_eq!(boards(&s), boards(&recorded));
assert_eq!(boards(&s).len(), 2);
assert!(s.execute("file.new", &json!({"artboards": 2.4})).is_err());
}
#[test]
fn replayed_counts_keep_their_rounding_and_range_rules() {
for (key, value, expected) in [
("artboards", 0.0, 1),
("artboards", 1001.0, 1000),
("columns", 2.4, 2),
("columns", 1001.0, 1000),
("rows", 2.4, 2),
("rows", 0.6, 1),
("rows", 1000.4, 1000),
] {
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
if key == "artboards" {
p[key] = json!(value);
} else {
p["artboardLayout"][key] = json!(value);
}
let mut s = Session::new();
s.replay("file.new", &p).unwrap();
assert!(s.execute("file.new", &p).is_err(), "{p}");
if key == "artboards" {
p[key] = json!(expected);
} else {
p["artboardLayout"][key] = json!(expected);
}
assert_eq!(boards(&s), boards(&new_doc(p)));
}
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
let mut p = json!({"artboardLayout": layout});
p["artboardLayout"]["layout"] = json!("gridByColumn");
let mut s = Session::new();
assert!(s.replay("file.new", &p).is_err(), "{p}");
assert!(s.active().is_none(), "{p}");
}
}
#[test]
fn categories_list_generated_presets_with_neutral_names() {
let mut s = Session::new();
+1 -1
View File
@@ -1144,7 +1144,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
assert_eq!(plain.grid_columns(), spaced.grid_columns());
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}");
for layout in ["gridByRow", "row", "column"] {
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
+2 -1
View File
@@ -1317,7 +1317,8 @@ mod tests {
let mut app = app();
open(&mut app);
set(&app, "artboards", json!(5)).unwrap();
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap();
assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err(), "a fraction is refused");
set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap();
assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4));
create(&mut app);
let st = app.session.active().unwrap();
+6 -1
View File
@@ -632,6 +632,11 @@ of `appearance.setItem`, `anchor` of `path.removeAnchor` and `addon.pen.removePo
value such as `"3"`, `2.5`, `-1` or `true` with `` `index` must be a whole number ``, naming the key, and reports a key
left out or null as missing (such as `` missing integer `index` ``). An optional one, such as `subpath`, keeps its default when
left out or null; `appearance.setActiveItem` reads a null `index` as clearing the active item.
`file.new` refuses a number given for `artboards`, `artboardLayout.columns` or `artboardLayout.rows` that is not a
whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the
default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or
played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of
1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000.
A command that leaves out an object selected inside a
selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes
`ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value
@@ -10628,7 +10633,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes
`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height`
(points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns,
rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),