From 5e30728f4dfa2c595f18b29eb319f14d5a0404ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:04:51 -0800 Subject: [PATCH] Save PDF: a settings object set by ui.dialog.set keeps the options it leaves out `ui.dialog.set` replaced a Save PDF settings object (`bleed`, `marks`, `compression` and the others) with the value given. Options left out then showed the default settings in the dialog, while Save PDF took them from the chosen preset. With the bleed, the link copied the default top value to the other sides while the file kept the preset's top: from a preset with `[3, 5, 3, 3]`, `{"useDocument": false}` followed by linking wrote `[3, 0, 0, 0]`. - A settings object set there now sets only the options it holds; the ones it leaves out keep the dialog's values. A null option is still set as given. - A value that is not an object is refused, and the request leaves the dialog as it was. - A test sends a request that sets `bleed` and then an invalid `__bleedLinked` through the control handler and checks the dialog is unchanged. --- crates/ui-egui/src/dialogs.rs | 7 +- crates/ui-egui/src/dialogs/save_pdf.rs | 34 ++++++++- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 80 ++++++++++++++++++++ docs/control-protocol.md | 2 +- 4 files changed, 117 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..ed805635bc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -734,8 +734,9 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor /// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save -/// PDF's bleed link links the bleed as its button does. A value Composite Fonts' Show Sample or -/// Save PDF's bleed link can't take is refused. +/// PDF's bleed link links the bleed as its button does, and a Save PDF settings object sets only the +/// options it holds. A value Composite Fonts' Show Sample, Save PDF's bleed link or a Save PDF +/// settings object can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); @@ -748,7 +749,7 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu return composite_fonts::field_set(d, field); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { - return save_pdf::field_set(d, field); + return save_pdf::field_set(d, field, old); } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { eps_options::field_set(d, field); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index a8db555bfb..75f9c7179f 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -801,8 +801,13 @@ fn edit_bleed(d: &mut Dialog, side: usize, value: f64) { /// `ui.dialog.set` set `field` of Save PDF or the PDF preset editor: `__bleedLinked` links or /// unlinks the bleed as its button does, and must be true or false; every write of `bleed`, the /// same values included, drops the link's state, so the link follows the values set. A flattener -/// preset set there drops the Custom… options, as choosing it in the dropdown does. -pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { +/// preset set there drops the Custom… options, as choosing it in the dropdown does. A settings +/// object (`bleed`, `marks`, `compression`…) set there must be an object and sets only the options +/// it holds: the ones it leaves out keep the values the dialog had (`old`). +pub(super) fn field_set(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { + if DEFAULTS.get(field).is_some_and(Value::is_object) { + keep_unset_options(d, field, old)?; + } match field { BLEED_LINKED => match d.fields.get(BLEED_LINKED).cloned() { Some(Value::Bool(on)) => { @@ -823,6 +828,31 @@ pub(super) fn field_set(d: &mut Dialog, field: &str) -> Result<(), String> { } } +/// The settings object `field` that `ui.dialog.set` set, with the options it leaves out taken from +/// `old` (the default settings' when the dialog had none). A null is kept as it was set. +fn keep_unset_options(d: &mut Dialog, field: &str, old: Option<&Value>) -> Result<(), String> { + let Some(new) = d.fields.get_mut(field).filter(|v| !v.is_null()) else { return Ok(()) }; + if !new.is_object() { + return Err(format!("{field} must be an object of options, not {new}")); + } + let mut merged = old.filter(|o| o.is_object()).or_else(|| DEFAULTS.get(field)).cloned().unwrap_or_default(); + merge_options(&mut merged, new); + *new = merged; + Ok(()) +} + +/// Set the options `over` holds on `base`, object by object. +fn merge_options(base: &mut Value, over: &Value) { + match (base, over) { + (Value::Object(b), Value::Object(o)) => { + for (k, v) in o { + merge_options(b.entry(k.as_str()).or_insert(Value::Null), v); + } + } + (b, o) => *b = o.clone(), + } +} + /// A dropdown of names such as colour profiles or flattener presets (`names`, the first one /// standing for "" at `path`), showing the name at `path` (one that isn't among them too). The /// first `builtins` entries are ours (translated); the others (profiles, saved presets) are names. diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 501aed4ed0..d59c2eea4b 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1011,6 +1011,86 @@ fn ui_dialog_set_links_the_bleed() { assert!(!bleed_linked(d) && bleed_of(d) == [1.0; 4], "a later __bleedLinked unlinks them"); } +/// `ui.dialog.set` with `fields`, as a control request. +fn dialog_set(app: &mut VectorcraftApp, fields: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({ "fields": fields })); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { panic!("not done") }; + r +} + +/// The open dialog as JSON, to compare it before and after a request. +fn dialog_json(app: &VectorcraftApp) -> Value { + serde_json::to_value(app.ui.dialog.as_ref()).unwrap() +} + +/// A settings object `ui.dialog.set` sets with some of its options changes only those: the +/// others keep the dialog's values, so the dialog shows what Save PDF writes and the bleed link +/// gives every side the top value Save PDF writes. +#[test] +fn ui_dialog_set_keeps_the_options_a_settings_object_leaves_out() { + let (mut app, _, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": {"useDocument": false}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(bleed_of(d) == [3.0, 5.0, 3.0, 3.0] && !bleed_linked(d), "the sides left out keep their values"); + let r = dialog_set(&mut app, json!([{"field": BLEED_LINKED, "value": true}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(bleed_of(d), [3.0; 4], "linking gives every side the top value"); + assert_eq!(params(d)["bleed"], json!({"useDocument": false, "top": 3.0, "bottom": 3.0, "left": 3.0, "right": 3.0})); + + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": {"bottom": 5}}])); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(bleed_of(app.ui.dialog.as_ref().unwrap()), [3.0, 5.0, 3.0, 3.0], "only the side set changes"); + + // A null option is set as it is: a null `output.profiles` still leaves the profiles unset. + let r = dialog_set(&mut app, json!([{"field": "output", "value": {"profiles": "all"}}])); + assert_eq!(r["ok"], true, "{r}"); + let r = dialog_set(&mut app, json!([{"field": "output", "value": {"profiles": null}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(get(d, "output.profiles").is_null() && get(d, "output.conversion") == &json!("none"), "{:?}", d.fields.get("output")); + + // Every settings object, not only the bleed. + app.run("ui.savePdfDialog", json!({"preset": "Marked"})).unwrap(); + let r = dialog_set(&mut app, json!([{"field": "marks", "value": {"weight": 0.5}}])); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((get(d, "marks.trim"), get(d, "marks.offset"), get(d, "marks.weight")), (&json!(true), &json!(9.0), &json!(0.5))); + + // A value that isn't an object is refused, and the dialog stays as it was. + let before = dialog_json(&app); + for bad in [json!(5), json!("3 mm"), json!([3, 3, 3, 3])] { + let r = dialog_set(&mut app, json!([{"field": "bleed", "value": bad}])); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("bleed must be an object of options")), "{bad}: {r}"); + assert_eq!(dialog_json(&app), before, "{bad}"); + } +} + +/// A `ui.dialog.set` request whose later field is refused leaves the whole dialog as it was +/// before the request, the bleed values an earlier field set included. +#[test] +fn a_refused_bleed_link_leaves_the_whole_request_unset() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"bleed": {"top": 3, "bottom": 3, "left": 3, "right": 3}})).unwrap(); + let before = dialog_json(&app); + let r = dialog_set( + &mut app, + json!([ + {"field": "bleed", "value": {"top": 1, "bottom": 2, "left": 3, "right": 4}}, + {"field": BLEED_LINKED, "value": "yes"}, + ]), + ); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("__bleedLinked must be true or false")), "{r}"); + assert_eq!(dialog_json(&app), before, "the dialog is unchanged"); +} + /// An unlinked edit that makes the four sides equal leaves the link off, so the next edit /// changes one side only. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..4df97a70b7 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -110,7 +110,7 @@ the two can still win that race. | `app.open` / `app.save` / `app.export` / `app.quit` | `{path, importer?, params?}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`) and returns its result (`{index, title, format, warnings, …}`; `warnings` say what didn't come in as it was, such as an EPS shown as its preview image and why its PostScript couldn't be read), or null when a dialog asks first or a library loads. The status bar (`ui.inspect` → `ui.status`), after a line about the document's linked files when there is one (Missing linked files below), counts the `warnings` and names the first that says reading the file left something out (the notes that make Save ask before writing over it), else the first; with several, hovering it lists them in that order, as many as fit in the window (at most 30), then how many more. After `app.save`, and `app.export` with a `path`, the status bar counts the reply's `warnings` and names the first, and with several, hovering it lists them in the reply's order (a save's notes start with what the format loses). With `importer` (an importer plug-in's format id, `plugin.`) it runs `file.openWith`: the file opens with that importer, also when a built-in format reads its extension, with the importer's parameters `params` (their defaults when omitted; no dialog asks for them). Without `importer`, `params` go to the importer that opens the file, and a built-in format does not read them. `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. It refuses a key that no format takes, and an unknown key inside a PDF or EPS option object, before it writes anything (`docs/mcp.md`, Parameter keys). It accepts a key that only another format takes and does not use it: the reply's `warnings` and the status bar name the key ("`quality` was not used: PDF files don't read it"). `app.save` refuses a key that no save format takes, beside the path or in `options`, the same way. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit | | `app.export` with `useArtboards` | `{path, useArtboards: true, range? \| artboards?, …}` | Export As: PNG, JPEG and WebP write one file per chosen artboard (default all; SVG does so for a `range`), `-.`, and return `{path, files: [path…]}`; a PDF keeps them as pages of `path`. `useArtboards: false` covers the bounds of the visible art. The menu's Export As… is `file.exportAs`: the `exportAs` dialog (`format`, `useArtboards`, `all`, `range`), then a save dialog and the format's options: `pngOptions` / `jpgOptions` / `webpOptions`, `svgOptions`, or `savePdf` for a PDF | | `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on | -| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a whole section with `{field: "compression", value: {…}}`, the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | +| `engine.execute` `ui.savePdfDialog` | `{path?, preset?, range?, …document.exportPdf options}` | opens the Save PDF dialog (`file.export.pdf` with no params opens it too). Its fields are the `document.exportPdf` options: set `compatibility` with `ui.dialog.set {field: "compatibility", value: "1.5"}`, a section with `{field: "compression", value: {…}}` (the options it leaves out keep the dialog's values; a value that isn't an object is an error), the artboards with `__allArtboards: false` and `range`, the visible section with `__section` (General, Compression, Marks and Bleeds, Output, Advanced, Security, Summary), and the bleed link with `__bleedLinked` (true gives every side the top value; any value other than true or false is an error; setting `bleed` turns the link on when its four sides are equal and off when they differ). In Advanced, Custom… beside Flattener preset (enabled when the file is flattened: PDF 1.3, PDF/X-1a, PDF/X-3) opens the `pdfFlattenerOptions` dialog over Save PDF on the flattener options the save would use; its fields are those options, with `clipComplexRegions`, `preserveAlpha` and `preserveOverprints` set by the writer and Overprint. Its `ui.dialog.confirm` sets `flattener` (the preset then shows [Custom]; options equal to the preset's leave it unset) and goes back to Save PDF, and `ui.dialog.cancel` goes back unchanged. Setting `flattenerPreset` drops `flattener`. `useArtboards: false` opens it for one page of the visible art's bounds, as Export As with Use Artboards off does: the dialog has no Artboards section and its `__artBounds` field is true. `ui.dialog.confirm` writes `path` (else asks for one), returns `{path, bytes, warnings}` and opens the file when `viewAfterSaving` is set. With `useArtboards: false` it writes the page as `app.export` does and returns `{path, warnings}`, or `{background: true, status}` while Background Export writes it | | `file.save` / `file.saveAs` / `file.saveCopy` / `file.saveAsTemplate` (via `engine.execute`) | `{path?, format?, options?, svg?}` | Save writes the document's own file in its own format (a document opened from or saved as SVG/PDF saves as that again; the result's `warnings` say what the format loses). With `path` the file is written at once (Save As or a Copy to an SVG path without SVG options first opens SVG Options, below). Without one (never saved, a converted older file, Save As, a Copy, a Template) the app shows a save panel with one file type per save format (`vectorcraft`, `template`, `pdf`, `svg`, `svgz`, `ai`; for a Template, `template` and `ait`), then the format's options: SVG opens the `svgOptions` dialog (below; returns `{"pending": "svgOptions", "path"}`), PDF the `savePdf` dialog (its `__save` field names the save command); `ui.dialog.confirm` finishes the save. A name typed in the panel without the file type's extension gets it, and a name the panel returns with the extension of a format the panel does not list has it replaced (in a native save, `card.png` and `card.ait` are saved as `card.vectorcraft`, and `notes.v2`, whose extension names no format, is saved as `notes.v2.vectorcraft`); when a file of that name exists, which the panel did not ask about, the save (and every export or other write through a save panel) answers `cancelled` and opens a `replaceFile` dialog (fields `message`, `detail`, `path`): `ui.dialog.confirm` writes that file, `ui.dialog.cancel` writes nothing. A save or export that writes other files beside that path (a file per artboard, linked images, image maps) checks them before it writes anything: when any of them exists, it writes nothing and opens a `replaceFiles` dialog (fields `message`, `detail` (each file's name when there are several), `files`, `__command`, `__params`; the reply is `{"pending": "replaceFiles"}`, or comes once a Background Save or Export ends): `ui.dialog.confirm` runs the save or export again and replaces them, `ui.dialog.cancel` writes nothing; a dialog open when a background job asks stays open, and the question follows it. A save does not ask about the files the document's last Save or Save As in this session wrote. On the web a `saveOptions` dialog (fields `path`, `format`) first names the file and picks the format. `file.formatOptions {format?}` reads the options a save would use. `file.revert` opens a `confirm` dialog (`{"pending": "confirm"}`); `ui.dialog.confirm` reloads the saved file in the same tab. Location refusals return `READ_ONLY_LOCATION: ` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | SVG Options (`engine.execute` of `file.export.svg`, `file.saveAs`, `file.saveCopy`) | `{}` / `{path?, svg?: {…}}` | `file.export.svg` without params, and Save As or Save a Copy to an `.svg`/`.svgz` path without SVG options, open the `svgOptions` dialog (`ui.dialog.set` its fields: `styling`, `outlineText`, `images`, `objectIds`, `decimals`, `minify`, `responsive`, `fewerTspans`, `metadata`, `preserveEditing`, `useArtboards`, `allArtboards`, `range`, `showCode`, `profile` (`svg11`/`tiny12`), `encoding` (`utf8`/`utf16`/`latin1`), `embedFonts`; `ui.dialog.confirm` exports or saves and remembers the choices). The dialog's Show in Browser button (`file.export.svg.browser`) writes the SVG of the current choices for one page to a temporary folder and opens it in the default browser, leaving the dialog open; a request through `engine.execute` is refused because it opens another app. With `svg: {…}` (the `document.formats` SVG options) they run directly. `app.save {path?, svg?}` takes the same options; a document saved as SVG saves as SVG again with the same options | | `engine.execute` `file.place` | `{paths?}` / `{path \| name+dataBase64, …file.place params}` | with no file, picks files and opens the `place` dialog; with `paths`, opens it for them (fields `files`, `link`, `template`, `replace`; `__replace` says whether Replace applies, `__info` describes each file). `ui.dialog.confirm` places one file centered in the view (or in place of the selected object) and loads the place cursor with several (`file.place.queue`). In the desktop app the dialog reads its files off the UI thread: `__info` is empty until they are read, `ui.dialog.confirm` returns `{background: true, status}`, `ui.inspect` lists the files still being read in `placing`, and the file is placed (or the cursor loaded) once it is read. With a file, it runs `file.place` centered in the view, at once. Files dropped on the window with no document open open. On the web, files dropped on the canvas are placed at the drop point (linked; Shift embeds) and files dropped off it (the tab bar) open, as in Illustrator; desktop drops carry no pointer position, so documents (native, SVG, PDF, `.ai`, EPS, DXF, EMF/WMF) open as tabs of their own and pictures and text are placed in the middle of the view. Swatch libraries and color books (`.vcswatches`, `.gpl`, `.ase`, `.acb`), graphic style libraries (`.vcstyles`), Libraries panel files (`.vclibrary`), presets (`.vcflattener`, `.vcpdfpresets`, `.vcprintpresets`, `.vcperspective`, `.vcexportpresets`), plug-ins (`.wasm`) and shortcut sets (`.kys`, in Import Shortcut Set) open wherever they are dropped, as File › Open opens them. With the cursor loaded (`ui.inspect` → `tool: "place"`, `toolOptions: {count, current, name, names}`), `ui.pointer` clicks and drags place files (in the desktop app each file is read off the UI thread and placed once it is read, and `ui.inspect` lists it in `placing` until then) and `ui.key` ←/→/↑/↓ and Escape cycle and discard them |