Merge pull request #9615 from dotCooCoo/fix/svg-filter-browser-selected-encoding

Preserve SVG Filter encoding from browser files
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-26 21:37:33 -08:00
commit 651da6fd85
4 files changed
+73 -9

No files matched your search

+1
View File
@@ -97,6 +97,7 @@ mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
mod swatch;
pub mod swatchlib;
pub(crate) mod symboledit;
+16 -8
View File
@@ -8,6 +8,8 @@
//! editing one adds a copy to the document under the default's name, and from then on that copy is
//! the filter of that name. Deleting the copy lists the default again.
use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, Document, SvgFilter};
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
@@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param};
/// The largest SVG file Import SVG Filter reads.
const MAX_IMPORT_BYTES: usize = 16 << 20;
pub const MAX_IMPORT_BYTES: usize = 16 << 20;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -53,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import SVG Filter…",
[],
None,
"{path?|svg?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
"{path?|svg?|dataBase64?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
has_doc,
import
),
@@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
}
/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`.
fn import_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) {
/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes.
fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result<Cow<'a, [u8]>> {
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) {
// One byte past the cap is enough to refuse the file below.
(Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?,
(None, Some(svg)) => svg.as_bytes().to_vec(),
_ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")),
(Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?),
(None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()),
(None, None, Some(encoded)) => {
if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 {
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
}
Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?)
}
_ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")),
};
if bytes.len() > MAX_IMPORT_BYTES {
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
+33
View File
@@ -34,6 +34,39 @@ fn names(s: &mut Session) -> Vec<String> {
const BLUR: &str = r#"<filter id="Soft"><feGaussianBlur stdDeviation="2"/></filter>"#;
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
#[test]
fn byte_import_keeps_svg_encodings_and_uses_one_undo_step() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><filter id="café"><feOffset dx="3"/></filter></svg>"#;
let utf16: Vec<u8> = [0xff, 0xfe].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect();
let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>{svg}").chars().map(|c| c as u8).collect();
for bytes in [svg.as_bytes().to_vec(), utf16, latin1] {
let mut s = session();
let out = run(&mut s, "svgFilter.import", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)}));
assert_eq!(out["added"], json!(["café"]));
assert_eq!(names(&mut s), ["café"]);
assert_eq!(steps(&s), 1);
run(&mut s, "edit.undo", json!({}));
assert!(names(&mut s).is_empty());
}
}
#[test]
fn byte_import_refuses_invalid_oversized_and_compressed_files_without_an_edit() {
let mut s = session();
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": "!"})).contains("dataBase64"));
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": 3})).contains("must be a string"));
let mut inline = "é".repeat(8 << 20);
inline.push(' ');
assert!(err(&mut s, "svgFilter.import", json!({"svg": inline})).contains("larger than 16777216 bytes"));
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("<svg/>")] {
assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err());
assert!(names(&mut s).is_empty());
assert_eq!(steps(&s), 0);
}
}
#[test]
fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() {
let mut s = session();
+23 -1
View File
@@ -474,7 +474,10 @@ fn ask_import(app: &mut VectorcraftApp, source: Option<Arc<Opening>>) -> Value {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
if bytes.len() > vectorcraft_engine::cmd::MAX_SVG_FILTER_IMPORT_BYTES {
return Err("The SVG file is larger than 16 MB".into());
}
json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) })
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
@@ -499,6 +502,25 @@ mod tests {
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3"/></filter>"#;
#[test]
fn browser_filter_import_keeps_the_picked_file_encoding() {
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><filter id="café"><feOffset dx="3"/></filter></svg>"#;
let utf16: Vec<u8> = [0xfe, 0xff].into_iter().chain(svg.encode_utf16().flat_map(u16::to_be_bytes)).collect();
let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>{svg}").chars().map(|c| c as u8).collect();
for bytes in [utf16, latin1] {
let mut app = app();
let picker = scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
open(&mut app, &json!({})).unwrap();
import_file(&mut app).unwrap();
picker.answer_contents(&[("filter.svg", &bytes)]);
poll(&mut app, &ctx);
assert_eq!(app.session.active().unwrap().doc.svg_filters[0].name, "café");
assert_eq!(fields(&app)[SELECTED], "café");
assert_eq!(app.session.active().unwrap().history.undo.len(), 1);
}
}
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();