diff --git a/Cargo.lock b/Cargo.lock index ff52f61b56c..e29c9c84d73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6934,6 +6934,7 @@ dependencies = [ "craft-image-codecs", "craft-print", "craft-psd", + "craft-xml", "eframe", "egui", "egui_extras", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index e2ef8d367e2..e91a63dc85c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -16,6 +16,7 @@ suite = ["craft/suite"] [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", "tracked-serde"] } # Interface translations over the embedded craft-i18n catalogs (`build.rs`, `src/i18n.rs`). craft-i18n = { workspace = true } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 46a359792dd..4377a8ee871 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/image_processor_settings_tests.rs b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs new file mode 100644 index 00000000000..a925c45b69e --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_settings_tests.rs @@ -0,0 +1,268 @@ +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;", + "A & B", + "A &", + "", + "", + ] { + 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()); +} + +#[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)>>>; + +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); + 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(); + 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"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("unescaped ampersand")); +} + +#[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..f0853bad668 100644 --- a/crates/ui-egui/src/dialogs/image_processor_ui.rs +++ b/crates/ui-egui/src/dialogs/image_processor_ui.rs @@ -2,7 +2,12 @@ //! 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::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 serde_json::{Map, Value}; @@ -56,5 +61,120 @@ 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::unique("pc-image-processor-settings-action") +} + +fn generation_id() -> egui::Id { + egui::Id::unique("pc-image-processor-settings-generation") +} + +pub(crate) fn settings_footer(dialog: ParamDialog<'_>) -> ParamDialog<'_> { + dialog.ok_label(Label::from(tl!("Run"))).shaped(|dialog| { + dialog.footer(|ui, _| { + 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)); + } + } + }) + }) +} + +/// 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::(settings_action_id()); + }); +} + +pub(crate) fn take_settings_action(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) { + 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 + { + 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, 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..267c863e1c8 --- /dev/null +++ b/crates/ui-egui/src/dialogs/image_processor_ui/settings.rs @@ -0,0 +1,202 @@ +//! 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 craft_xml::{Doctype, Event, Limits, Node, Options}; + +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}'); + 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}>"); + 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()); + } + 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, ""); + } + let _ = writeln!(xml, ""); + if xml.len() > MAX_BYTES { + return Err(too_large()); + } + Ok(xml.into_bytes()) +} + +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 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() + }); + 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()); + } + 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 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.iter().any(|node| matches!(node, Node::El(_))) { + return Err(invalid(tag)); + } + let value = parse_value(kind, child.text(), current).ok_or_else(|| invalid(tag))?; + if let Some(field) = field { + updates.set(field, value); + } + } + 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 { + OpenDocuments => { + let open = trimmed.parse::().ok()?; + if open { + "open" + } else if current { + "current" + } else { + "folder" + } + .into() + } + Bool(_) => trimmed.parse::().ok()?.into(), + Text => text.into_owned().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() + } + }) +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index ddb5005730a..2d4b64db55f 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; @@ -56,9 +57,14 @@ 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| { derive(&key, fields); - 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 } }) }