From 1b1f60ba8c04a57eaad6fabfc250f7ce22d5d937 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:27:17 -0800 Subject: [PATCH] SVG Options: Show in Browser opens the SVG in the default browser The SVG export options on the help page list a Show in browser option beside Show Code, which displays the image in the default web browser: https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html SVG Options gets a Show in Browser button beside Show Code. It writes the SVG of the dialog's current, unconfirmed choices for one page (the selection's crop under Export Selection, otherwise the first artboard the options choose) to a new folder inside "VectorCraft SVG Preview" in the system's temporary folder and opens it (file.export.svg.browser). The dialog stays open, the choices are not remembered, and nothing is written to the chosen file. The folder follows Save for Web's preview folders: a private folder per preview, and folders an hour old are removed; each kind removes only its own. The button is disabled on the web build, and control and MCP requests are refused, as Save for Web's Preview in Browser is. Show Code and Show in Browser share one encoding step, so Show Code changes in two ways. A range that OK refuses now shows OK's error: before, Show Code showed the first artboard's code for a range it could not read, and the first artboard named for a range such as "1, 9" when the document has no artboard 9. A range naming one missing artboard was already an error, with a different message. From Save As or Save a Copy, both keep hidden layers, as the save does. A document with no artboards shows the bounds of its art. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs/save_for_web.rs | 46 ++-- crates/ui-egui/src/dialogs/svg_options.rs | 300 ++++++++++++++++++--- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/io.rs | 2 +- crates/ui-egui/src/io/export.rs | 2 +- crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 6 + docs/control-protocol.md | 2 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 39 files changed, 345 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b6da21331e..0d5769f1cf 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,6 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), + ( + "file.export.svg.browser", + "Show in Browser", + "", + "{svg?: {…SVG options}, exportSelection?} SVG Options' Show in Browser: write the SVG of one page (with exportSelection the selection's crop, else the first artboard the options choose) and its linked images to a new temporary folder and open it in the default browser (desktop; refused for control and MCP requests) → {path, warnings}", + ), ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), ( "file.exportForScreens", diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..bfe21b8482 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -237,29 +237,41 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result Result { - preview_folder_in(&std::env::temp_dir(), PREVIEW_KEEP) + temp_folder_under(ROOT) } -/// The name of a folder that a preview made in the temporary folder, beside a `VectorCraft Save -/// for Web` it couldn't use, before the process id and the count. +/// A new folder for a browser preview in the system's temporary folder, under the folder named +/// `root` ([`preview_folder_under`]). #[cfg(not(target_arch = "wasm32"))] -const BESIDE: &str = "VectorCraft Save for Web "; +pub(super) fn temp_folder_under(root: &str) -> Result { + preview_folder_under(&std::env::temp_dir(), root, PREVIEW_KEEP) +} -/// A new folder for a browser preview in the temporary folder `tmp`: inside `VectorCraft Save for -/// Web` ([`preview_folder`]), or, when that folder can't be used, directly in `tmp`, named -/// [`BESIDE`] followed by the process id and a count. The log says why the shared folder wasn't -/// used. Each preview first removes the folders of that name in `tmp` last changed `keep` or longer -/// ago ([`remove_old`]). -#[cfg(not(target_arch = "wasm32"))] +/// A new folder for a Save for Web browser preview in the temporary folder `tmp` +/// ([`preview_folder_under`] with `VectorCraft Save for Web`). +#[cfg(all(test, not(target_arch = "wasm32")))] pub(super) fn preview_folder_in(tmp: &std::path::Path, keep: std::time::Duration) -> Result { - remove_old(tmp, BESIDE, keep); - preview_folder(&tmp.join("VectorCraft Save for Web"), keep).or_else(|e| { - log::warn!("vectorcraft: Preview in Browser can't use {e}, so the preview goes to a new folder of its own"); - new_folder(tmp, BESIDE) + preview_folder_under(tmp, ROOT, keep) +} + +/// A new folder for a browser preview in the temporary folder `tmp`: inside the folder named `root` +/// ([`preview_folder`]), or, when that folder can't be used, directly in `tmp`, named `root`, a +/// space, the process id and a count. The log says why the shared folder wasn't used. Each preview +/// first removes the folders of that name in `tmp` last changed `keep` or longer ago +/// ([`remove_old`]). Previews under one `root` never remove the folders of another. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn preview_folder_under(tmp: &std::path::Path, root: &str, keep: std::time::Duration) -> Result { + let beside = format!("{root} "); + remove_old(tmp, &beside, keep); + preview_folder(&tmp.join(root), keep).or_else(|e| { + log::warn!("vectorcraft: a browser preview can't use {e}, so the preview goes to a new folder of its own"); + new_folder(tmp, &beside) }) } @@ -381,7 +393,7 @@ fn is_preview_name(name: &std::ffi::OsStr, prefix: &str) -> bool { } #[cfg(target_arch = "wasm32")] -fn temp_folder() -> Result { +pub(super) fn temp_folder_under(_: &str) -> Result { Err("no file system here".into()) } diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 13586ae3e1..c185a3d5cb 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,16 +1,19 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, //! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with -//! them as `svg: {…}`. +//! them as `svg: {…}`. Show in Browser (`file.export.svg.browser`) writes the SVG the choices give +//! to a temporary folder and opens it in the default browser, leaving the dialog open. +use std::borrow::Cow; use std::sync::Arc; use serde_json::{Map, Value, json}; +use vectorcraft_engine::cmd::fileio; use super::DialogSpec; use crate::state::Dialog; use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; +use crate::{VectorcraftApp, io, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("SVG Options").into(), @@ -26,6 +29,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// `Dialog::kind` of this dialog. pub const KIND: &str = "svgOptions"; +/// The UI command of the dialog's Show in Browser button. +pub const BROWSER: &str = "file.export.svg.browser"; + +/// The folder in the system's temporary folder that Show in Browser's previews go to. +const PREVIEW_ROOT: &str = "VectorCraft SVG Preview"; + /// What OK does: Export As SVG, Save As or Save a Copy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { @@ -196,8 +205,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); let show = d.bool("showCode"); - if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { - d.fields.insert("showCode".into(), json!(!show)); + let mut browser = false; + ui.horizontal(|ui| { + if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { + d.fields.insert("showCode".into(), json!(!show)); + } + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Show in Browser"))); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + if browser && let Err(e) = app.run(BROWSER, preview_params(d)) { + app.status(e); } if show { ui.add_space(6.0); @@ -269,6 +286,102 @@ fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// The SVG options the dialog `d`'s OK writes with: [`options`], with hidden layers kept (not +/// displayed) when OK saves, as a save keeps them unless told otherwise. +fn written_options(d: &Dialog) -> Value { + let mut o = options(d); + if Mode::of(d) != Mode::Export + && let Some(m) = o.as_object_mut() + { + m.entry("hiddenLayers").or_insert(json!(true)); + } + o +} + +/// The params of [`BROWSER`] for the dialog `d`: the SVG options OK writes with +/// ([`written_options`]), and `exportSelection` when Export Selection opened it. +fn preview_params(d: &Dialog) -> Value { + super::export_as::exported(d, json!({ "svg": written_options(d) })) +} + +/// The SVG file that the SVG options `svg` write for one page of the document `st`, and the +/// document it is drawn from. With `selection` (Export Selection) the page is the selection alone, +/// cropped to it. Otherwise it is the first artboard the options choose, checked against the +/// document's artboards as OK checks them, or what the options write without artboards (also for +/// a document that has none). Linked scripts and images are checked against the read roots in +/// force first. +fn encode_page<'a>( + st: &'a vectorcraft_engine::DocState, + svg: &Value, + selection: bool, +) -> Result<(Cow<'a, vectorcraft_doc::Document>, fileio::Encoded), String> { + let mut opts = svg.clone(); + if let Some(o) = opts.as_object_mut() { + if selection { + // Export Selection writes one crop, without artboards to choose. + for k in fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { + o.remove(*k); + } + } else if st.doc.artboards.is_empty() { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + } else { + let pick: fileio::ArtboardPick = serde_json::from_value(Value::Object(o.clone())).map_err(|e| e.to_string())?; + if let Some(first) = pick.resolve(st.doc.artboards.len())?.and_then(|v| v.first().copied()) { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + o.insert("artboard".into(), json!(first)); + } + } + } + let params = json!({ "svg": opts }); + fileio::check_linked_scripts("document.export", "svg", st, ¶ms).map_err(|e| e.to_string())?; + let doc = if selection { + Cow::Owned(fileio::selection_doc(st, "document.exportSelection", false).map_err(|e| e.to_string())?.0) + } else { + Cow::Borrowed(&*st.doc) + }; + fileio::check_linked_images("document.export", "svg", st, &doc, ¶ms).map_err(|e| e.to_string())?; + let enc = fileio::encode_all(&doc, "svg", ¶ms).map_err(|e| e.to_string())?; + Ok((doc, enc)) +} + +/// `file.export.svg.browser {svg?, exportSelection?}` (SVG Options' Show in Browser): the SVG file +/// that the SVG options `svg` write for one page ([`encode_page`]), written with its linked images +/// to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder and opened in +/// the default browser (desktop) → `{path, warnings}`. Nothing is written to the chosen +/// destination, and the document, its path and the remembered choices are left as they were. +/// When the export has warnings, the status bar shows them as [`io::report_saved`] shows a save's +/// notes. Nothing opens when a check, the encoding or a write fails. +pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result { + if io::is_web(app) { + return Err("no file system here".into()); + } + app.refuse_automation(BROWSER)?; + let (selection, p) = io::take_selection(p)?; + let svg = p.get("svg").cloned().unwrap_or_else(|| json!({})); + let (path, warnings) = { + let st = app.session.active().ok_or("no document")?; + let stem = fileio::file_stem(&st.doc.title); + let (doc, enc) = encode_page(st, &svg, selection)?; + let dir = super::save_for_web::temp_folder_under(PREVIEW_ROOT)?; + let target = format!("{dir}/{}.svg", super::save_for_web::preview_name(&stem)); + let named = enc.named(&doc, &target); + for (p, bytes) in &named { + io::write_to(&mut app.services, p, bytes)?; + } + (named.first().map_or(target, |(p, _)| p.clone()), enc.notes()) + }; + app.open_url(&io::file_url(&path)); + let r = json!({ "path": path, "warnings": warnings }); + if !warnings.is_empty() { + io::report_saved(app, &path, &r); + } + Ok(r) +} + /// The SVG the current options write for the first chosen artboard, or under Export Selection for /// the selection alone, cropped to it (read-only, selectable), encoded again only when the /// options, the document or the selection change. @@ -276,19 +389,7 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; let selection = d.bool(super::export_as::SELECTION_FIELD); - let mut opts = options(d); - if let Some(o) = opts.as_object_mut() { - if selection { - // Export Selection writes one crop, without artboards to choose. - for k in vectorcraft_engine::cmd::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { - o.remove(*k); - } - } else if let Some(r) = o.remove("range") { - // The first artboard of the range (or the first one). - let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok()); - o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1)))); - } - } + let opts = written_options(d); // One cached text, replaced when the document, the options or the selection change. let key = egui::Id::unique("svg-code"); // The read roots in force and the document's folder decide whether the text may be shown. @@ -299,27 +400,15 @@ 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, ¶ms).and_then(|()| { - let selected; - let doc = if selection { - selected = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?.0; - &selected - } else { - &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 { + let mut text = match encode_page(st, &opts, selection) { // Shown as text whatever the file's encoding. - Ok(enc) => enc + Ok((_, enc)) => enc .files .into_iter() .next() .map(|(_, b)| vectorcraft_svg::text_of(&b).map_or_else(|_| String::from_utf8_lossy(&b).into_owned(), |t| t.into_owned())) .unwrap_or_default(), - Err(e) => e.to_string(), + Err(e) => e, }; if text.len() > MAX { let cut = (0..=MAX).rev().find(|i| text.is_char_boundary(*i)).unwrap_or(0); @@ -389,6 +478,153 @@ mod tests { String::from_utf8(w.borrow()[i].1.clone()).unwrap() } + type Opened = Rc>>; + + /// [`app`] whose browser records each URL it is asked to open. + fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) { + let (mut app, written) = app(picked); + let opened = Opened::default(); + let o = opened.clone(); + app.services.open_url = Some(Box::new(move |u: &str| o.borrow_mut().push(u.to_string()))); + (app, written, opened) + } + + /// Show in Browser for the open dialog's current choices, as its button runs it. + fn show_in_browser(app: &mut VectorcraftApp) -> Result { + let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open")); + app.run(BROWSER, p) + } + + /// Show in Browser writes the SVG of the dialog's current, unconfirmed choices for the first + /// artboard of the range to a new temporary folder and opens that file once. The dialog stays + /// open, nothing is remembered, and OK then writes the same SVG to the chosen file. + #[test] + fn show_in_browser_opens_what_ok_writes_without_confirming() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + frame(&mut app); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("decimals".into(), json!(1)); + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("2")); + let remembered = app.ui.svg_options.clone(); + let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.contains("/VectorCraft SVG Preview/") && path.ends_with("/Untitled-1.svg"), "{path}"); + assert_eq!(*opened.borrow(), [io::file_url(&path)]); + assert_eq!(written.borrow().len(), 1); + assert_eq!(written.borrow()[0].0, path); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(app.ui.svg_options, remembered, "nothing is remembered"); + assert!(app.session.active().unwrap().path.is_none()); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/out.svg"); + assert_eq!(text(&written, 0), text(&written, 1), "the preview is the file OK writes"); + assert_eq!(opened.borrow().len(), 1); + } + + /// A range the document has no artboard for is refused, as OK refuses it: nothing is written + /// or opened, and the dialog stays open. + #[test] + fn show_in_browser_refuses_a_range_the_document_lacks() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("5")); + assert!(show_in_browser(&mut app).is_err()); + assert!(written.borrow().is_empty() && opened.borrow().is_empty()); + assert!(app.ui.dialog.is_some()); + } + + /// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it. + #[test] + fn show_in_browser_under_export_selection_shows_the_selection() { + let (mut app, written, opened) = browsing("/tmp/selection.svg"); + app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap(); + app.run("document.exportSelection", Value::Null).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool(super::super::export_as::SELECTION_FIELD)); + show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/selection.svg"); + assert_eq!(text(&written, 0), text(&written, 1)); + assert_eq!(text(&written, 0).matches("