From 7be0322c1a3a85e36c064bba02e74687476d0e26 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 09:40:19 +0000 Subject: [PATCH 1/7] Save and load Image Processor XML settings --- Cargo.lock | 1 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/dialogs/filter_dialog.rs | 6 + .../dialogs/image_processor_settings_tests.rs | 247 ++++++++++++++++++ .../ui-egui/src/dialogs/image_processor_ui.rs | 112 +++++++- .../dialogs/image_processor_ui/settings.rs | 188 +++++++++++++ 7 files changed, 557 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/dialogs/image_processor_settings_tests.rs create mode 100644 crates/ui-egui/src/dialogs/image_processor_ui/settings.rs diff --git a/Cargo.lock b/Cargo.lock index 12b584bbc1b..2a9f169af13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6852,6 +6852,7 @@ dependencies = [ "photocraft-text", "photocraft-vector", "rayon", + "roxmltree 0.21.2", "serde", "serde_json", "sys-locale", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 1cf6b437c82..fc4a828a530 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -41,6 +41,7 @@ egui_extras = { version = "0.37", default-features = false, features = ["svg"] } eframe = { workspace = true, features = ["wgpu", "accesskit", "clipboard"] } serde = { workspace = true } serde_json = { workspace = true } +roxmltree = "0.21" # The tables of craft-host's `SectionStore` (`app/framework.rs`); already linked through craft-host. toml = { version = "1.1", default-features = false, features = ["std", "serde"] } log = { workspace = true } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f4de4e5b25d..0812039fcd9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -299,6 +299,9 @@ pub(crate) mod params { if let (Some(action), Some(footer)) = (footer, family.and_then(|family| family.footer)) { footer(app, ctx, id, &action); } + if key.as_deref() == Some(image_processor_ui::COMMAND) { + image_processor_ui::take_settings_action(app, ctx, id); + } } } diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 4fad587bf05..33cb96ac6ad 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -519,6 +519,9 @@ fn builder( dialog = dialog .extra_buttons(vec![("load".to_owned(), Label::from(tl!("Load…").to_string())), ("save".to_owned(), Label::from(tl!("Save…").to_string()))]); } + if key == crate::dialogs::image_processor_ui::COMMAND { + dialog = crate::dialogs::image_processor_ui::settings_footer(dialog); + } dialog } } @@ -536,6 +539,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result if command == MATCH_COLOR { reconcile_match_color(app); } + if command == crate::dialogs::image_processor_ui::COMMAND { + crate::dialogs::image_processor_ui::settings_opened(app.ctx()); + } Ok(id) } diff --git a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs new file mode 100644 index 00000000000..64ef92b6781 --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -0,0 +1,247 @@ +use std::cell::RefCell; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; + +use craft::host::{FileFilter, PickKind, Picked, ScriptedFiles}; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog}; +use egui_kittest::{Harness, kittest::Queryable}; +use serde_json::{Value, json}; + +use super::{COMMAND, settings}; +use crate::{PhotocraftApp, Services}; + +#[test] +fn settings_xml_follows_the_reference_order_and_formats() { + let mut fields = DialogFields::from_pairs([("source", "folder"), ("input", "C:\\é & \r\n"), ("output", "C:\\résultats")]); + fields.set("jpeg/quality", 5.25); + fields.set("jpeg/resize", true); + fields.set("jpeg/width", 100_i64); + fields.set("jpeg/height", 80_i64); + let xml = settings::encode(&fields).unwrap(); + let text = std::str::from_utf8(&xml).unwrap(); + assert_eq!( + text, + concat!( + "\u{feff}\n", + "\t1\n", + "\tfalse\n", + "\tfalse\n", + "\tC:\\é & <source> \n", + "\tfalse\n", + "\tfalse\n", + "\tC:\\résultats\n", + "\ttrue\n", + "\tfalse\n", + "\tfalse\n", + "\tfalse\n", + "\tfalse\n", + "\t5.25\n", + "\ttrue\n", + "\ttrue\n", + "\t100\n", + "\t80\n", + "\tfalse\n", + "\t1\n", + "\t1\n", + "\tfalse\n", + "\t1\n", + "\t1\n", + "\tfalse\n", + "\t\n", + "\t\n", + "\t\n", + "\ttrue\n", + "\ttrue\n", + "\n", + ) + ); + let decoded = settings::decode(&xml).unwrap(); + assert_eq!(decoded.text("input"), fields.text("input")); + assert_eq!(decoded.text("output"), fields.text("output")); + assert_eq!(decoded.number("jpeg/quality"), Some(5.25)); +} + +#[test] +fn partial_xml_keeps_missing_fields_and_ignores_unknown_elements() { + let fields = settings::decode( + br#"trueinvalidMissing set "#, + ) + .unwrap(); + assert_eq!(fields, DialogFields::from_pairs([("source", "open"), ("input", "")])); + for source in ["current", "open", "folder"] { + let current = DialogFields::from_pairs([("source", source)]); + let encoded = settings::encode(¤t).unwrap(); + assert_eq!(settings::decode(&encoded).unwrap().text("source"), Some(source)); + } +} + +#[test] +fn invalid_settings_are_rejected() { + for invalid in [ + "", + "", + "", + "", + "abc", + "NaN", + "12.01", + "30001", + "0", + "maybe", + "true", + "falsetrue", + "&bad;", + "", + ] { + assert!(settings::decode(invalid.as_bytes()).is_err(), "{invalid}"); + } + assert!(settings::decode(&[0xff]).is_err()); + assert!(settings::decode(&vec![b' '; settings::MAX_BYTES + 1]).is_err()); + assert!(settings::encode(&DialogFields::from_pairs([("input", "bad\0path")])).is_err()); +} + +type AppHarness = Harness<'static, Box>; +type Written = Rc)>>>; + +fn open(app: &mut PhotocraftApp) -> DialogId { + let ctx = app.ctx().clone(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + app.framework.dialogs.stack().top().unwrap() +} + +fn harness() -> (AppHarness, DialogId, Arc, Written) { + let files = Arc::new(ScriptedFiles::held()); + let written: Written = Default::default(); + let log = written.clone(); + let services = Services { + files: Some(files.clone()), + write: Some(Box::new(move |path, bytes| { + log.borrow_mut().push((path.to_owned(), bytes.to_vec())); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 40, "height": 20})).unwrap(); + let id = open(&mut app); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 1000.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + app.poll_file_dialog(); + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + (h, id, files, written) +} + +fn fields(h: &AppHarness, id: DialogId) -> &DialogFields { + h.state().framework.dialogs.get_by_id::(id).unwrap().fields() +} + +fn set(h: &mut AppHarness, id: DialogId, key: &str, value: Value) { + let ctx = h.ctx.clone(); + h.state_mut().framework.dialogs.set_json_field(&ctx, id, key, value).unwrap_or_else(|error| panic!("{key}: {error}")); +} + +fn click(h: &mut AppHarness, label: &str) { + h.get_by_role_and_label(egui::accesskit::Role::Button, label).click(); + h.run_steps(4); +} + +#[test] +fn the_footer_saves_and_loads_pending_values_without_running_image_processor() { + let (mut h, id, files, written) = harness(); + for (key, value) in [ + ("source", json!("folder")), + ("input", json!("pictures & sketches")), + ("output", json!("exports")), + ("includeSubfolders", json!(true)), + ("jpeg/quality", json!(9.75)), + ("jpeg/convertToSrgb", json!(true)), + ("jpeg/resize", json!(true)), + ("jpeg/width", json!(2048)), + ("jpeg/height", json!(1536)), + ("psd/enabled", json!(true)), + ("psd/maximizeCompatibility", json!(false)), + ("psd/resize", json!(true)), + ("psd/width", json!(1024)), + ("psd/height", json!(768)), + ("tiff/enabled", json!(true)), + ("tiff/lzw", json!(true)), + ("tiff/resize", json!(true)), + ("tiff/width", json!(4096)), + ("tiff/height", json!(3072)), + ] { + set(&mut h, id, key, value); + } + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Run"); + let original = fields(&h, id).clone(); + click(&mut h, "Save…"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, PickKind::Save); + assert_eq!(request.title.as_deref(), Some("Pick an XML file to save")); + assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]); + files.answer(Picked::Paths(vec![PathBuf::from("preset.xml")])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + let (path, saved) = written.borrow_mut().pop().unwrap(); + assert_eq!(path, "preset.xml"); + + set(&mut h, id, "source", json!("open")); + set(&mut h, id, "jpeg/quality", json!(2.0)); + set(&mut h, id, "psd/enabled", json!(false)); + set(&mut h, id, "tiff/width", json!(16)); + h.run_steps(3); + click(&mut h, "Load…"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, PickKind::Open); + assert_eq!(request.title.as_deref(), Some("Pick an XML file to load")); + assert_eq!(request.filters, [FileFilter::new("XML Files (*.xml)", &["xml"])]); + files.answer(Picked::Contents(vec![(path, saved)])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + assert!(written.borrow().is_empty(), "Load does not write output or close the dialog"); +} + +#[test] +fn malformed_and_cancelled_picks_leave_the_form_unchanged() { + let (mut h, id, files, written) = harness(); + let original = fields(&h, id).clone(); + + click(&mut h, "Save…"); + files.answer(Picked::Cancelled).unwrap(); + h.run_steps(3); + assert!(written.borrow().is_empty()); + click(&mut h, "Load…"); + files.answer(Picked::Cancelled).unwrap(); + h.run_steps(3); + assert_eq!(h.state().framework.dialogs.stack().top(), Some(id)); + + let path = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(path.path(), b"truewrong").unwrap(); + click(&mut h, "Load…"); + files.answer(Picked::Paths(vec![path.path().to_path_buf()])).unwrap(); + h.run_steps(3); + assert_eq!(fields(&h, id), &original); + let alert = h.state().framework.dialogs.stack().top().unwrap(); + assert_ne!(alert, id, "an error is shown over the form"); + assert!(h.state().ui.status.contains("Invalid Image Processor setting: q")); +} + +#[test] +fn a_load_answer_for_a_closed_dialog_does_not_edit_a_reopened_dialog() { + let (mut h, id, files, _) = harness(); + click(&mut h, "Load…"); + let ctx = h.ctx.clone(); + crate::dialogs::cancel(h.state_mut(), &ctx, id).unwrap(); + let reopened = open(h.state_mut()); + let original = fields(&h, reopened).clone(); + files.answer(Picked::Contents(vec![("preset.xml".into(), b"12".to_vec())])).unwrap(); + h.run_steps(4); + assert_eq!(fields(&h, reopened), &original); +} diff --git a/crates/ui-egui/src/dialogs/image_processor_ui.rs b/crates/ui-egui/src/dialogs/image_processor_ui.rs index 05bfc16396f..40d24fdcc47 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -2,8 +2,11 @@ //! built with the rest of the form by `view_cmds::dialogs::params_for`; this module folds their values into the //! per-format objects the command takes and refuses an OK with no format ticked. -use craft::ui::patterns::form_dialogs::ParamResult; +use craft::host::{PickRequest, Picked}; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamDialog, ParamResult}; use craft::ui::runtime::env::Label; +use craft::ui::sections::{DialogRole, FooterBar, FooterButton}; use serde_json::{Map, Value}; use crate::PhotocraftApp; @@ -56,5 +59,112 @@ pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), } } +#[derive(Clone, Copy)] +enum SettingsAction { + Load, + Save, +} + +fn settings_action_id() -> egui::Id { + egui::Id::new((COMMAND, "settings-action")) +} + +fn generation_id() -> egui::Id { + egui::Id::new((COMMAND, "generation")) +} + +pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> { + dialog.ok_label(Label::from(tl!("Run"))).shaped(|dialog| { + dialog.footer(|ui, _| { + let buttons = [ + FooterButton::new(tl!("Load…"), DialogRole::Other).tooltip(tl!("Load a settings file from disk")), + FooterButton::new(tl!("Save…"), DialogRole::Other).tooltip(tl!("Save the current dialog settings to disk")), + ]; + if let Some(action) = FooterBar::buttons(buttons).show_footer(ui).picked.and_then(|index| [SettingsAction::Load, SettingsAction::Save].get(index)) { + ui.ctx().data_mut(|data| data.insert_temp(settings_action_id(), *action)); + } + }) + }) +} + +/// The dialog's id is reused when it reopens. A picker left over from a previous opening must not touch the new form. +pub(crate) fn settings_opened(ctx: &egui::Context) { + ctx.data_mut(|data| { + let generation = data.get_temp_mut_or_default::(generation_id()); + *generation = generation.wrapping_add(1); + data.remove_temp::(settings_action_id()); + }); +} + +pub(crate) fn take_settings_action(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) { + let Some(action) = ctx.data_mut(|data| data.remove_temp::(settings_action_id())) else { return }; + let result = pick_settings(app, id, action); + if let Err(error) = result + && error != crate::file_dialog::CANCELLED + { + crate::dialogs::alerts::alert(app, error); + } +} + +fn pick_settings(app: &mut PhotocraftApp, id: DialogId, action: SettingsAction) -> Result { + const PURPOSE: &str = "imageProcessorSettings"; + let generation = app.ctx().data(|data| data.get_temp::(generation_id())); + let (request, bytes) = match action { + SettingsAction::Load => (PickRequest::open(PURPOSE).title(tl!("Pick an XML file to load")), None), + SettingsAction::Save => { + let Some(dialog) = app.framework.dialogs.get_by_id::(id) else { return Ok(Value::Null) }; + let request = PickRequest::save(PURPOSE).title(tl!("Pick an XML file to save")).file_name("Image Processor.xml").suggested_extension("xml"); + (request, Some(settings::encode(dialog.fields())?)) + } + }; + app.ask_file(request.filter(tl!("XML Files (*.xml)"), &["xml"]), move |app, picked| { + if app.ctx().data(|data| data.get_temp::(generation_id())) != generation || app.framework.dialogs.get_by_id::(id).is_none() { + return Ok(Value::Null); + } + let result = match bytes { + Some(bytes) => write_settings(app, picked, &bytes), + None => load_settings(app, id, picked), + }; + result.inspect_err(|error| { + if error != crate::file_dialog::CANCELLED { + crate::dialogs::alerts::alert(app, error.clone()); + } + }) + }) +} + +fn load_settings(app: &mut PhotocraftApp, id: DialogId, picked: Picked) -> Result { + let bytes = match picked { + Picked::Contents(files) => files.into_iter().next().map(|(_, bytes)| bytes).ok_or(crate::file_dialog::CANCELLED)?, + #[cfg(not(target_arch = "wasm32"))] + Picked::Paths(paths) => { + let path = paths.first().ok_or(crate::file_dialog::CANCELLED)?; + photocraft_format::read_file_limited(path, settings::MAX_BYTES as u64).map_err(|error| format!("{}: {error}", path.display()))? + } + _ => return Err(tl!("Could not open the Image Processor settings file.").into()), + }; + let fields = settings::decode(&bytes)?; + if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { + for (key, value) in fields.iter() { + dialog.set_field(key.clone(), value.clone()); + } + } + Ok(Value::Null) +} + +fn write_settings(app: &mut PhotocraftApp, picked: Picked, bytes: &[u8]) -> Result { + let path = picked.first_path().ok_or(crate::file_dialog::CANCELLED)?; + let path = path.to_str().ok_or(tl!("The settings file name is not valid text."))?; + let write = app.services.write.as_mut().ok_or(tl!("Saving Image Processor settings is unavailable."))?; + write(path, bytes)?; + Ok(Value::Null) +} + +mod settings; + #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "image_processor_settings_tests.rs"] +mod settings_tests; diff --git a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs new file mode 100644 index 00000000000..1368b7642bd --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs @@ -0,0 +1,188 @@ +//! XML presets for the Image Processor dialog. The element names and order follow the measured settings file. + +use std::fmt::Write; + +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use roxmltree::{Document, ParsingOptions}; + +pub(super) const MAX_BYTES: usize = 256 * 1024; + +const ROOT: &str = "ImageProcessor"; +// XML has only an open-documents/folder switch. A processing instruction preserves PhotoCraft's +// third choice without adding an element to the reference format. +const CURRENT_SOURCE: &str = r#"source="current""#; + +#[derive(Clone, Copy)] +enum Kind { + OpenDocuments, + Bool(bool), + Text, + Int(i64), + Quality, +} + +use Kind::{Bool, Int, OpenDocuments, Quality, Text}; + +// Fields without a dialog key use the current processor behavior. Load validates those settings too. +const ELEMENTS: &[(&str, Option<&str>, Kind)] = &[ + ("version", None, Int(1)), + ("useopen", Some("source"), OpenDocuments), + ("includesub", Some("includeSubfolders"), Bool(false)), + ("source", Some("input"), Text), + ("open", None, Bool(false)), + ("saveinsame", None, Bool(false)), + ("dest", Some("output"), Text), + ("jpeg", Some("jpeg/enabled"), Bool(true)), + ("psd", Some("psd/enabled"), Bool(false)), + ("tiff", Some("tiff/enabled"), Bool(false)), + ("lzw", Some("tiff/lzw"), Bool(false)), + ("converticc", Some("jpeg/convertToSrgb"), Bool(false)), + ("q", Some("jpeg/quality"), Quality), + ("max", Some("psd/maximizeCompatibility"), Bool(true)), + ("jpegresize", Some("jpeg/resize"), Bool(false)), + ("jpegw", Some("jpeg/width"), Int(30_000)), + ("jpegh", Some("jpeg/height"), Int(30_000)), + ("psdresize", Some("psd/resize"), Bool(false)), + ("psdw", Some("psd/width"), Int(30_000)), + ("psdh", Some("psd/height"), Int(30_000)), + ("tiffresize", Some("tiff/resize"), Bool(false)), + ("tiffw", Some("tiff/width"), Int(30_000)), + ("tiffh", Some("tiff/height"), Int(30_000)), + ("runaction", None, Bool(false)), + ("actionset", None, Text), + ("action", None, Text), + ("info", None, Text), + ("icc", None, Bool(true)), + ("keepstructure", None, Bool(true)), +]; + +fn invalid(tag: &str) -> String { + crate::i18n::fmt(tl!("Invalid Image Processor setting: {setting}"), &[("setting", tag)]) +} + +fn too_large() -> String { + tl!("The Image Processor settings file is too large.").into() +} + +pub(super) fn encode(fields: &DialogFields) -> Result, String> { + let mut xml = String::from('\u{feff}'); + if fields.text("source") == Some("current") { + let _ = writeln!(xml, ""); + } + let _ = writeln!(xml, "<{ROOT}>"); + for &(tag, field, kind) in ELEMENTS { + let field = field.unwrap_or_default(); + let _ = write!(xml, "\t<{tag}>"); + match kind { + OpenDocuments => xml.push_str(if fields.text(field) == Some("open") { "true" } else { "false" }), + Bool(default) => { + let _ = write!(xml, "{}", fields.bool(field).unwrap_or(default)); + } + Int(max) => { + let value = fields.int(field).unwrap_or(1); + if !(1..=max).contains(&value) { + return Err(invalid(tag)); + } + let _ = write!(xml, "{value}"); + } + Quality => { + let value = fields.number(field).unwrap_or(5.0); + if !(1.0..=12.0).contains(&value) { + return Err(invalid(tag)); + } + let _ = write!(xml, "{value}"); + } + Text => { + let text = fields.text(field).unwrap_or_default(); + if text.len() > MAX_BYTES { + return Err(too_large()); + } + push_text(&mut xml, text).ok_or_else(|| invalid(tag))?; + } + } + let _ = writeln!(xml, ""); + } + let _ = writeln!(xml, ""); + if xml.len() > MAX_BYTES { + return Err(too_large()); + } + Ok(xml.into_bytes()) +} + +fn push_text(xml: &mut String, text: &str) -> Option<()> { + for c in text.chars() { + match c { + '&' => xml.push_str("&"), + '<' => xml.push_str("<"), + '>' => xml.push_str(">"), + // Keep each element on one line. XML also normalizes literal carriage returns. + '\r' => xml.push_str(" "), + '\n' => xml.push_str(" "), + '\t' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}' => xml.push(c), + _ => return None, + } + } + Some(()) +} + +pub(super) fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(too_large()); + } + let text = std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; + let document = Document::parse_with_options(text, ParsingOptions { nodes_limit: 4096, ..Default::default() }) + .map_err(|error| crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]))?; + let root = document.root_element(); + if !root.has_tag_name(ROOT) || root.tag_name().namespace().is_some() { + return Err(tl!("This file does not contain Image Processor settings.").into()); + } + let current = document.root().children().filter_map(|node| node.pi()).any(|pi| pi.target == "PhotoCraft" && pi.value == Some(CURRENT_SOURCE)); + let mut seen = std::collections::HashSet::new(); + let mut updates = DialogFields::new(); + for child in root.children() { + if child.is_text() && child.text().is_some_and(|text| !text.trim().is_empty()) { + return Err(invalid(ROOT)); + } + if !child.is_element() || child.tag_name().namespace().is_some() { + continue; + } + let tag = child.tag_name().name(); + let Some(&(_, field, kind)) = ELEMENTS.iter().find(|(name, _, _)| *name == tag) else { continue }; + if !seen.insert(tag) || child.children().any(|node| node.is_element()) { + return Err(invalid(tag)); + } + let text: String = child.children().filter(|node| node.is_text()).filter_map(|node| node.text()).collect(); + let value = parse_value(kind, text, current).ok_or_else(|| invalid(tag))?; + if let Some(field) = field { + updates.set(field, value); + } + } + Ok(updates) +} + +fn parse_value(kind: Kind, text: String, current: bool) -> Option { + let trimmed = text.trim(); + Some(match kind { + OpenDocuments => { + let open = trimmed.parse::().ok()?; + if open { + "open" + } else if current { + "current" + } else { + "folder" + } + .into() + } + Bool(_) => trimmed.parse::().ok()?.into(), + Text => text.into(), + Int(max) => { + let value = trimmed.parse::().ok()?; + (1..=max).contains(&value).then_some(value)?.into() + } + Quality => { + let value = trimmed.parse::().ok()?; + (1.0..=12.0).contains(&value).then_some(value)?.into() + } + }) +} From aba988ddfbdbf121248fee7a3ce6e3a4ef8438aa Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 09:47:54 +0000 Subject: [PATCH 2/7] Take the pending settings action from egui memory --- crates/ui-egui/src/dialogs/image_processor_ui.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/image_processor_ui.rs b/crates/ui-egui/src/dialogs/image_processor_ui.rs index 40d24fdcc47..e356eb97f5e 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -92,12 +92,18 @@ pub(crate) fn settings_opened(ctx: &egui::Context) { ctx.data_mut(|data| { let generation = data.get_temp_mut_or_default::(generation_id()); *generation = generation.wrapping_add(1); - data.remove_temp::(settings_action_id()); + data.remove::(settings_action_id()); }); } pub(crate) fn take_settings_action(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) { - let Some(action) = ctx.data_mut(|data| data.remove_temp::(settings_action_id())) else { return }; + let action = ctx.data_mut(|data| { + let id = settings_action_id(); + let action = data.get_temp::(id)?; + data.remove::(id); + Some(action) + }); + let Some(action) = action else { return }; let result = pick_settings(app, id, action); if let Err(error) = result && error != crate::file_dialog::CANCELLED From e399a61719ac48191945de84bae4ab33752d5480 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 09:52:12 +0000 Subject: [PATCH 3/7] Use the shared bounded XML reader for settings --- Cargo.lock | 2 +- crates/ui-egui/Cargo.toml | 2 +- .../dialogs/image_processor_settings_tests.rs | 1 + .../dialogs/image_processor_ui/settings.rs | 72 +++++++++---------- 4 files changed, 35 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2a9f169af13..507f70e16a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6830,6 +6830,7 @@ dependencies = [ "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bafb4522899d9f814a07dad636cdefcbf705dead)", "craft-print", "craft-psd", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bafb4522899d9f814a07dad636cdefcbf705dead)", "eframe", "egui", "egui_extras", @@ -6852,7 +6853,6 @@ dependencies = [ "photocraft-text", "photocraft-vector", "rayon", - "roxmltree 0.21.2", "serde", "serde_json", "sys-locale", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fc4a828a530..98f1c1aeaf9 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] chrono = { workspace = true } craft-print = { workspace = true } +craft-xml = { workspace = true } craft = { workspace = true, features = ["ui", "layers", "color-ui", "draw", "imaging", "window", "keymap", "automation", "theme-store", "print", "menu", "timeline", "text", "text-font-picker", "font-manager", "quit", "cms"] } # Interface translations over the embedded craft-i18n catalogs (`build.rs`, `src/i18n.rs`). craft-i18n = { workspace = true } @@ -41,7 +42,6 @@ egui_extras = { version = "0.37", default-features = false, features = ["svg"] } eframe = { workspace = true, features = ["wgpu", "accesskit", "clipboard"] } serde = { workspace = true } serde_json = { workspace = true } -roxmltree = "0.21" # The tables of craft-host's `SectionStore` (`app/framework.rs`); already linked through craft-host. toml = { version = "1.1", default-features = false, features = ["std", "serde"] } log = { workspace = true } diff --git a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs index 64ef92b6781..7dbb3b8f90e 100644 --- a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -83,6 +83,7 @@ fn invalid_settings_are_rejected() { "", "", "", + "", "", "abc", "NaN", diff --git a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs index 1368b7642bd..5cb7cb6c3be 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs @@ -1,9 +1,10 @@ //! XML presets for the Image Processor dialog. The element names and order follow the measured settings file. +use std::borrow::Cow; use std::fmt::Write; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; -use roxmltree::{Document, ParsingOptions}; +use craft_xml::{Doctype, Limits, Node, Options}; pub(super) const MAX_BYTES: usize = 256 * 1024; @@ -66,10 +67,10 @@ fn too_large() -> String { pub(super) fn encode(fields: &DialogFields) -> Result, String> { let mut xml = String::from('\u{feff}'); - if fields.text("source") == Some("current") { - let _ = writeln!(xml, ""); - } let _ = writeln!(xml, "<{ROOT}>"); + if fields.text("source") == Some("current") { + let _ = writeln!(xml, "\t"); + } for &(tag, field, kind) in ELEMENTS { let field = field.unwrap_or_default(); let _ = write!(xml, "\t<{tag}>"); @@ -97,7 +98,11 @@ pub(super) fn encode(fields: &DialogFields) -> Result, String> { if text.len() > MAX_BYTES { return Err(too_large()); } - push_text(&mut xml, text).ok_or_else(|| invalid(tag))?; + if !text.chars().all(craft_xml::is_xml_char) { + return Err(invalid(tag)); + } + // Keep the preset's one element per line even for paths containing line breaks. + xml.push_str(&craft_xml::esc(text).replace('\n', " ")); } } let _ = writeln!(xml, ""); @@ -109,50 +114,37 @@ pub(super) fn encode(fields: &DialogFields) -> Result, String> { Ok(xml.into_bytes()) } -fn push_text(xml: &mut String, text: &str) -> Option<()> { - for c in text.chars() { - match c { - '&' => xml.push_str("&"), - '<' => xml.push_str("<"), - '>' => xml.push_str(">"), - // Keep each element on one line. XML also normalizes literal carriage returns. - '\r' => xml.push_str(" "), - '\n' => xml.push_str(" "), - '\t' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}' => xml.push(c), - _ => return None, - } - } - Some(()) -} - pub(super) fn decode(bytes: &[u8]) -> Result { if bytes.len() > MAX_BYTES { return Err(too_large()); } - let text = std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; - let document = Document::parse_with_options(text, ParsingOptions { nodes_limit: 4096, ..Default::default() }) - .map_err(|error| crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]))?; - let root = document.root_element(); - if !root.has_tag_name(ROOT) || root.tag_name().namespace().is_some() { + std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; + let options = Options { doctype: Doctype::Reject, pis: true, ..Options::default() }.strict().with_limits(Limits { + max_input: MAX_BYTES, + max_depth: 32, + max_nodes: 4096, + ..Limits::default() + }); + let root = + options.parse(bytes).map_err(|error| crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]))?; + if root.name != ROOT || root.attr("xmlns").is_some_and(|ns| !ns.is_empty()) { return Err(tl!("This file does not contain Image Processor settings.").into()); } - let current = document.root().children().filter_map(|node| node.pi()).any(|pi| pi.target == "PhotoCraft" && pi.value == Some(CURRENT_SOURCE)); + let current = root.children.iter().any(|node| matches!(node, Node::Pi { target, data } if target == "PhotoCraft" && data == CURRENT_SOURCE)); let mut seen = std::collections::HashSet::new(); let mut updates = DialogFields::new(); - for child in root.children() { - if child.is_text() && child.text().is_some_and(|text| !text.trim().is_empty()) { - return Err(invalid(ROOT)); - } - if !child.is_element() || child.tag_name().namespace().is_some() { - continue; - } - let tag = child.tag_name().name(); + for node in &root.children { + let child = match node { + Node::El(child) if child.attr("xmlns").is_none_or(str::is_empty) => child, + Node::Text(text) if !text.trim().is_empty() => return Err(invalid(ROOT)), + _ => continue, + }; + let tag = child.name.as_str(); let Some(&(_, field, kind)) = ELEMENTS.iter().find(|(name, _, _)| *name == tag) else { continue }; - if !seen.insert(tag) || child.children().any(|node| node.is_element()) { + if !seen.insert(tag) || child.children.iter().any(|node| matches!(node, Node::El(_))) { return Err(invalid(tag)); } - let text: String = child.children().filter(|node| node.is_text()).filter_map(|node| node.text()).collect(); - let value = parse_value(kind, text, current).ok_or_else(|| invalid(tag))?; + let value = parse_value(kind, child.text(), current).ok_or_else(|| invalid(tag))?; if let Some(field) = field { updates.set(field, value); } @@ -160,7 +152,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result { Ok(updates) } -fn parse_value(kind: Kind, text: String, current: bool) -> Option { +fn parse_value(kind: Kind, text: Cow<'_, str>, current: bool) -> Option { let trimmed = text.trim(); Some(match kind { OpenDocuments => { @@ -175,7 +167,7 @@ fn parse_value(kind: Kind, text: String, current: bool) -> Option { .into() } Bool(_) => trimmed.parse::().ok()?.into(), - Text => text.into(), + Text => text.into_owned().into(), Int(max) => { let value = trimmed.parse::().ok()?; (1..=max).contains(&value).then_some(value)?.into() From ddff72c40565a830079f7a2c879bb918ed6877f3 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 10:00:43 +0000 Subject: [PATCH 4/7] Wire settings buttons into the Image Processor menu form --- crates/ui-egui/src/dialogs/filter_dialog.rs | 6 ------ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 8 +++++++- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 33cb96ac6ad..4fad587bf05 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -519,9 +519,6 @@ fn builder( dialog = dialog .extra_buttons(vec![("load".to_owned(), Label::from(tl!("Load…").to_string())), ("save".to_owned(), Label::from(tl!("Save…").to_string()))]); } - if key == crate::dialogs::image_processor_ui::COMMAND { - dialog = crate::dialogs::image_processor_ui::settings_footer(dialog); - } dialog } } @@ -539,9 +536,6 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result if command == MATCH_COLOR { reconcile_match_color(app); } - if command == crate::dialogs::image_processor_ui::COMMAND { - crate::dialogs::image_processor_ui::settings_opened(app.ctx()); - } Ok(id) } diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 46b293d0e2b..3caeb97db8b 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1,5 +1,6 @@ use super::dispatch::no_params; use super::{PhotocraftApp, Value, json}; +use crate::dialogs::image_processor_ui; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Outcome as _, Props as _, Show as _}; use craft::ui::dialog::DialogId; @@ -49,8 +50,13 @@ fn opened(id: DialogId) -> Value { fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec, fields: DialogFields, fixed: Value) -> DialogId { let title = crate::dialogs::filter_dialog::title_of(title); let key = id.to_owned(); + let image_processor = id == image_processor_ui::COMMAND; + if image_processor { + image_processor_ui::settings_opened(app.ctx()); + } crate::dialogs::params::open_param(app, id, fields, fixed, move |fields: &mut DialogFields| { - ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields)) + let dialog = ParamDialog::command(key.clone(), title.clone(), params.clone()).values(Bind::bound(fields)); + if image_processor { image_processor_ui::settings_footer(dialog) } else { dialog } }) } From 7df77e0b94106249951f08f516e83657e7ef0ac6 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 10:01:15 +0000 Subject: [PATCH 5/7] Use current egui ID constructors for XML settings --- crates/ui-egui/src/dialogs/image_processor_ui.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/image_processor_ui.rs b/crates/ui-egui/src/dialogs/image_processor_ui.rs index e356eb97f5e..6a372d5a6c3 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -66,11 +66,11 @@ enum SettingsAction { } fn settings_action_id() -> egui::Id { - egui::Id::new((COMMAND, "settings-action")) + egui::Id::unique("pc-image-processor-settings-action") } fn generation_id() -> egui::Id { - egui::Id::new((COMMAND, "generation")) + egui::Id::unique("pc-image-processor-settings-generation") } pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> { @@ -152,7 +152,7 @@ fn load_settings(app: &mut PhotocraftApp, id: DialogId, picked: Picked) -> Resul let fields = settings::decode(&bytes)?; if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { for (key, value) in fields.iter() { - dialog.set_field(key.clone(), value.clone()); + dialog.set_field(key, value.clone()); } } Ok(Value::Null) From 2f1f612b5628aa70d123bf0b1a5d499edbbeb567 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 10:20:19 +0000 Subject: [PATCH 6/7] Keep XML and Run controls clear of each other --- .../dialogs/image_processor_settings_tests.rs | 6 +++++- .../ui-egui/src/dialogs/image_processor_ui.rs | 18 +++++++++++------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs index 7dbb3b8f90e..bb470ecdc43 100644 --- a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -180,7 +180,11 @@ fn the_footer_saves_and_loads_pending_values_without_running_image_processor() { set(&mut h, id, key, value); } h.run_steps(3); - h.get_by_role_and_label(egui::accesskit::Role::Button, "Run"); + let buttons = ["Load…", "Save…", "Cancel", "Run"].map(|label| h.get_by_role_and_label(egui::accesskit::Role::Button, label).rect()); + for (index, button) in buttons.iter().enumerate() { + assert!(button.is_positive(), "button {index} is visible"); + assert!(buttons.iter().skip(index + 1).all(|other| !button.intersects(*other)), "footer buttons must not overlap"); + } let original = fields(&h, id).clone(); click(&mut h, "Save…"); let request = files.requests().pop().unwrap(); diff --git a/crates/ui-egui/src/dialogs/image_processor_ui.rs b/crates/ui-egui/src/dialogs/image_processor_ui.rs index 6a372d5a6c3..f0853bad668 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -3,10 +3,12 @@ //! per-format objects the command takes and refuses an OK with no format ticked. use craft::host::{PickRequest, Picked}; +use craft::theme::Variant; +use craft::ui::buttons::Button; +use craft::ui::contract::{LeastWidth, Props as _, Show as _, TooltipSpec, clicked}; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamDialog, ParamResult}; use craft::ui::runtime::env::Label; -use craft::ui::sections::{DialogRole, FooterBar, FooterButton}; use serde_json::{Map, Value}; use crate::PhotocraftApp; @@ -76,12 +78,14 @@ fn generation_id() -> egui::Id { pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> { dialog.ok_label(Label::from(tl!("Run"))).shaped(|dialog| { dialog.footer(|ui, _| { - let buttons = [ - FooterButton::new(tl!("Load…"), DialogRole::Other).tooltip(tl!("Load a settings file from disk")), - FooterButton::new(tl!("Save…"), DialogRole::Other).tooltip(tl!("Save the current dialog settings to disk")), - ]; - if let Some(action) = FooterBar::buttons(buttons).show_footer(ui).picked.and_then(|index| [SettingsAction::Load, SettingsAction::Save].get(index)) { - ui.ctx().data_mut(|data| data.insert_temp(settings_action_id(), *action)); + for (action, label, tip) in [ + (SettingsAction::Load, tl!("Load…"), tl!("Load a settings file from disk")), + (SettingsAction::Save, tl!("Save…"), tl!("Save the current dialog settings to disk")), + ] { + let button = Button::new(label).variant(Variant::SECONDARY).least_width(LeastWidth::DialogButton).tooltip(TooltipSpec::new(tip)); + if clicked(&button.show(ui)) { + ui.ctx().data_mut(|data| data.insert_temp(settings_action_id(), action)); + } } }) }) From 13924e259159d608506531dca2fd985f9faaab59 Mon Sep 17 00:00:00 2001 From: Dan Date: Fri, 20 Nov 2026 11:49:45 +0000 Subject: [PATCH 7/7] Reject bare ampersands in Image Processor presets --- .../dialogs/image_processor_settings_tests.rs | 20 +++++++++++-- .../dialogs/image_processor_ui/settings.rs | 30 ++++++++++++++++--- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs index bb470ecdc43..a925c45b69e 100644 --- a/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -94,6 +94,9 @@ fn invalid_settings_are_rejected() { "true", "falsetrue", "&bad;", + "A & B", + "A &", + "", "", ] { assert!(settings::decode(invalid.as_bytes()).is_err(), "{invalid}"); @@ -103,6 +106,19 @@ fn invalid_settings_are_rejected() { assert!(settings::encode(&DialogFields::from_pairs([("input", "bad\0path")])).is_err()); } +#[test] +fn escaped_ampersands_and_literal_cdata_remain_valid() { + let xml = concat!( + "\u{feff}", + "", + "A & B & C &amp;", + "", + ); + let fields = settings::decode(xml.as_bytes()).unwrap(); + assert_eq!(fields.text("output"), Some("A & B & C &")); + assert_eq!(fields.text("input"), Some("A & B")); +} + type AppHarness = Harness<'static, Box>; type Written = Rc)>>>; @@ -228,14 +244,14 @@ fn malformed_and_cancelled_picks_leave_the_form_unchanged() { assert_eq!(h.state().framework.dialogs.stack().top(), Some(id)); let path = tempfile::NamedTempFile::new().unwrap(); - std::fs::write(path.path(), b"truewrong").unwrap(); + std::fs::write(path.path(), b"trueA & B").unwrap(); click(&mut h, "Load…"); files.answer(Picked::Paths(vec![path.path().to_path_buf()])).unwrap(); h.run_steps(3); assert_eq!(fields(&h, id), &original); let alert = h.state().framework.dialogs.stack().top().unwrap(); assert_ne!(alert, id, "an error is shown over the form"); - assert!(h.state().ui.status.contains("Invalid Image Processor setting: q")); + assert!(h.state().ui.status.contains("unescaped ampersand")); } #[test] diff --git a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs index 5cb7cb6c3be..267c863e1c8 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs @@ -4,7 +4,7 @@ use std::borrow::Cow; use std::fmt::Write; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; -use craft_xml::{Doctype, Limits, Node, Options}; +use craft_xml::{Doctype, Event, Limits, Node, Options}; pub(super) const MAX_BYTES: usize = 256 * 1024; @@ -118,15 +118,17 @@ pub(super) fn decode(bytes: &[u8]) -> Result { if bytes.len() > MAX_BYTES { return Err(too_large()); } - std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; + let text = std::str::from_utf8(bytes).map_err(|_| tl!("Image Processor settings must be UTF-8.").to_string())?; let options = Options { doctype: Doctype::Reject, pis: true, ..Options::default() }.strict().with_limits(Limits { max_input: MAX_BYTES, max_depth: 32, max_nodes: 4096, ..Limits::default() }); - let root = - options.parse(bytes).map_err(|error| crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]))?; + if text.contains('&') { + validate_references(text.strip_prefix('\u{feff}').unwrap_or(text), &options)?; + } + let root = options.parse(bytes).map_err(xml_error)?; if root.name != ROOT || root.attr("xmlns").is_some_and(|ns| !ns.is_empty()) { return Err(tl!("This file does not contain Image Processor settings.").into()); } @@ -152,6 +154,26 @@ pub(super) fn decode(bytes: &[u8]) -> Result { Ok(updates) } +fn xml_error(error: craft_xml::Error) -> String { + crate::i18n::fmt(tl!("Could not read Image Processor settings: {error}"), &[("error", &error.to_string())]) +} + +/// The shared reader accepts bare ampersands even in strict mode. Its event spans let us +/// check the original text and attributes without treating CDATA, comments or instructions as XML text. +fn validate_references(text: &str, options: &Options<'_>) -> Result<(), String> { + let mut events = options.events(text.as_bytes()); + while let Some(event) = events.next().map_err(xml_error)? { + if !matches!(event, Event::Text(_) | Event::Start { .. }) { + continue; + } + let raw = text.get(events.span()).ok_or_else(|| invalid(ROOT))?; + if raw.split('&').skip(1).any(|tail| tail.split_once(';').and_then(|(name, _)| craft_xml::entity(name)).is_none()) { + return Err(tl!("Image Processor settings contain an unescaped ampersand.").into()); + } + } + Ok(()) +} + fn parse_value(kind: Kind, text: Cow<'_, str>, current: bool) -> Option { let trimmed = text.trim(); Some(match kind {