PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Warp Text: the dialog opens with the layer's warp and previews it live (#218) (#2539)
Simon0384b1af6db2
diff --git a/crates/text/src/warp.rs b/crates/text/src/warp.rsindex 13a5c8a39..8ad433e5c 100644--- a/crates/text/src/warp.rs+++ b/crates/text/src/warp.rs@@ -37,6 +37,14 @@ pub fn psd_style(id: &str) -> Option<&'static str> {STYLES.iter().find(|(psd, short)| psd.to_ascii_lowercase() == l || short.to_ascii_lowercase() == l).map(|(psd, _)| *psd)}+/// Short id (`flag`, `none`) for a PSD style name (`warpFlag`, `warpNone`): the reverse of [`psd_style`].+pub fn short_style(psd: &str) -> Option<&'static str> {+ if psd == "warpNone" {+ return Some("none");+ }+ STYLES.iter().find(|(p, _)| *p == psd).map(|(_, short)| *short)+}+/// A warp prepared for one layout: the shared style math of/// [`photocraft_geom::warp::StyleWarp`] (also used by Edit › Transform › Warp) over the text box.#[derive(Clone, Copy, Debug)]@@ -71,6 +79,18 @@ mod tests {Warp::new(&w, [0.0, -40.0, 200.0, 10.0]).unwrap()}+ /// #218: the Warp Text dialog shows a layer's PSD style by its short id.+ #[test]+ fn short_ids_round_trip_with_psd_styles() {+ assert_eq!(short_style("warpFlag"), Some("flag"));+ assert_eq!(short_style("warpNone"), Some("none"));+ assert_eq!(short_style("warpCustom"), None);+ for (psd, short) in STYLES {+ assert_eq!(short_style(psd), Some(short));+ assert_eq!(psd_style(short_style(psd).unwrap()), Some(psd));+ }+ }+#[test]fn styles_resolve_and_none_is_identity() {assert_eq!(psd_style("Arc"), Some("warpArc"));diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex d2e4faedc..e23cd3203 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1174,7 +1174,7 @@ fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx:/// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the/// deterministic inline path (#1676), which also lets headless/CPU tests inspect previews/// without a GPU texture.-fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> {+pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> {if let Some(held) = committed_filter_preview(app, idx) {return held;}diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 3f610aa6c..c53fd8139 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -247,6 +247,7 @@ pub const PREVIEWED: &[&str] = &["layer.matting.defringe","layer.matting.colorDecontaminate","layer.layerStyle.scaleEffects",+ "type.warpText",];pub fn has_dialog(command: &str) -> bool {@@ -339,6 +340,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {if command == "image.rotation.arbitrary" {straighten_defaults(app, &mut fields);}+ if command == "type.warpText" {+ warp_defaults(app, &mut fields);+ }// Photoshop's Pattern Name dialog starts from the name the pattern would get anyway.if command == "edit.definePattern" {fields.insert("name".into(), json!(photocraft_engine::pattern_cmds::default_name(&app.session)));@@ -364,6 +368,28 @@ fn straighten_defaults(app: &PhotocraftApp, fields: &mut Map<String, Value>) {fields.insert("direction".into(), json!(if rot < 0.0 { "ccw" } else { "cw" }));}+/// Warp Text edits the type layers it opened on (the selected ones, or the one being edited) and+/// starts from the warp the shown layer has, or None, never from remembered values (#218).+fn warp_defaults(app: &PhotocraftApp, fields: &mut Map<String, Value>) {+ if let Some(Value::Object(targets)) = crate::type_tool::formatting_params(app) {+ fields.extend(targets);+ }+ let warp = crate::type_tool::target_text(app).and_then(|t| t.warp.clone());+ let w = warp.unwrap_or(photocraft_doc::text::TextWarp {+ style: "warpNone".into(),+ value: 50.0,+ horizontal_distortion: 0.0,+ vertical_distortion: 0.0,+ horizontal: true,+ });+ // A style without a short id (from a PSD) shows as None, with the layer's values.+ fields.insert("style".into(), json!(photocraft_text::warp::short_style(&w.style).unwrap_or("none")));+ fields.insert("bend".into(), json!(w.value));+ fields.insert("horizontalDistortion".into(), json!(w.horizontal_distortion));+ fields.insert("verticalDistortion".into(), json!(w.vertical_distortion));+ fields.insert("orientation".into(), json!(if w.horizontal { "horizontal" } else { "vertical" }));+}+/// A filter dialog with live preview for `command` whose parameters follow `spec` (registry/// notation) instead of the command's own; `fixed` params (e.g. a plug-in id) are passed through.pub fn open_with_spec(app: &mut PhotocraftApp, command: &str, label: &str, spec: &str, fixed: Map<String, Value>) -> u64 {@@ -590,7 +616,10 @@ pub fn preview_document_with(k: u32,cancel: Option<&photocraft_engine::jobs::JobCtx>,) -> Option<Document> {- let proxy = crate::proxy::proxy_document(doc, k);+ // Warp Text renders the type again from the layer model (font size, position), which a+ // reduced proxy doesn't scale: it runs at full size and the result is reduced (#218).+ let (run_k, reduce_k) = if command == "type.warpText" { (1, k) } else { (k, 1) };+ let proxy = crate::proxy::proxy_document(doc, run_k);let mut s = photocraft_engine::Session::new();s.set_inline_job_ctx(cancel.cloned());s.add_document(proxy, None);@@ -598,7 +627,7 @@ pub fn preview_document_with(s.select_layer(id).ok()?;}let mut p = params.clone();- if k > 1+ if run_k > 1&& let Some(o) = p.as_object_mut(){let spec = photocraft_engine::commands::find(command).map(|c| parse_spec(c.params)).unwrap_or_default();@@ -615,13 +644,13 @@ pub fn preview_document_with(let floor = minimum.unwrap_or(0.0).max(if key == "cellSize" { 1.0 } else { 0.1 });// Negative lengths (Offset's left/up shift, Displace's inverted scale) keep their// sign: the floor that keeps a radius positive turned them into +0.1 (#2063).- let x = x / k as f64;+ let x = x / run_k as f64;*v = json!(if x > 0.0 { x.max(floor) } else { minimum.map_or(x, |m| x.max(m)) });}}}s.execute(command, p).ok()?;- s.active().map(|d| (*d.doc).clone())+ s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))}/// Cached preview state on the app.@@ -1127,6 +1156,29 @@ mod tests {assert!(is_pixel_param_of("filter.stylize.extrude", "size"));}+ /// #218: Warp Text renders the type again from the layer model, which a reduced proxy doesn't+ /// scale: the preview showed the text k times too large. It is the full-size result, reduced.+ #[test]+ fn warp_text_preview_matches_the_full_size_result_on_a_reduced_proxy() {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width": 4000, "height": 3000})).unwrap();+ s.execute("type.create", json!({"x": 300, "y": 1600, "text": "Warp", "size": 400})).unwrap();+ let st = s.active().unwrap();+ let (doc, layer) = ((*st.doc).clone(), st.active_layer.unwrap());+ let p = json!({"style": "arc", "bend": 40.0});+ let k = preview_factor("type.warpText", &p, crate::proxy::preview_factor(&doc, true));+ assert!(k > 1, "the preview runs on a reduced proxy");+ let cache = |d: &Document| match &d.layer(layer).unwrap().content {+ photocraft_doc::LayerContent::Text(t) => t.cache.clone().unwrap(),+ _ => panic!("a type layer"),+ };+ let full = crate::proxy::proxy_document(&preview_document(&doc, Some(layer), "type.warpText", &p, 1).unwrap(), k);+ let shown = preview_document(&doc, Some(layer), "type.warpText", &p, k).unwrap();+ assert_eq!(shown.size, full.size);+ assert_eq!(cache(&shown).content_bounds(), cache(&full).content_bounds());+ assert_eq!(photocraft_compose::flatten(&shown).px, photocraft_compose::flatten(&full).px);+ }+/// #2063: a pixel-sized parameter divided by the proxy factor was clamped to the command's/// minimum (Pointillize's 5 px cells became 3 px proxy cells = 12 px), so the preview factor/// drops until every pixel-sized value fits its range.diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 3dd7cfe2d..53f575238 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1939,6 +1939,9 @@ mod hidden_layer_tests;#[cfg(test)]mod blend_dropdown_keys_tests;+#[cfg(test)]+mod warp_text_dialog_tests;+#[cfg(test)]mod blend_dropdown_wheel_tests;diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsindex 0e0317560..38e659ada 100644--- a/crates/ui-egui/src/type_tool.rs+++ b/crates/ui-egui/src/type_tool.rs@@ -892,6 +892,12 @@ fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> {Some((id.0, None))}+/// The type layer whose properties the Type controls and dialogs show (see [`target`]).+pub(crate) fn target_text(app: &PhotocraftApp) -> Option<&TextLayer> {+ let (id, _) = target(app)?;+ text_layer(&app.session.active()?.doc, LayerId(id))+}+/// Snapshot the mutation scope separately from the representative used to display properties./// An inline edit remains on its layer/range; layer selection formats every selected type layer.pub(crate) fn formatting_params(app: &PhotocraftApp) -> Option<serde_json::Value> {diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rsindex d1049cf29..6e9a32c66 100644--- a/crates/ui-egui/src/type_tool_tests.rs+++ b/crates/ui-egui/src/type_tool_tests.rs@@ -1411,6 +1411,7 @@ mod multi_layer_formatting {for label in ["Layer", "Layers", "Range", "Coalesce"] {assert!(h.query_by_label(label).is_none(), "target metadata must not become a form field: {label}");}+ h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("style".into(), json!("arc"));h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("bend".into(), json!(25.0));selected(h.state_mut(), &[ids[2]]);h.get_by_label("OK").click();diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex 422e51702..3aa4a7957 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -764,9 +764,7 @@ mod label_tests {/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns.pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let choices = f.get("__choices").cloned().unwrap_or(Value::Null);- let warp_text = f.get("__command").and_then(Value::as_str) == Some("type.warpText");- let keys: Vec<String> =- f.keys().filter(|k| !(k.starts_with("__") || warp_text && matches!(k.as_str(), "layer" | "layers" | "range" | "coalesce"))).cloned().collect();+ let keys: Vec<String> = f.keys().filter(|k| !k.starts_with("__")).cloned().collect();egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {for k in keys {let v = f.get(&k).cloned().unwrap_or(Value::Null);@@ -909,16 +907,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Vallet fields = app.ui.view.guide_layout.clone();dialog(app, fields, json!({}))}- "type.warpText" => {- let styles: Vec<&str> = std::iter::once("none").chain(photocraft_text::warp::STYLES.iter().map(|(_, s)| *s)).collect();- let mut fields = json!({"style": "arc", "orientation": "horizontal", "bend": 50.0, "horizontalDistortion": 0.0, "verticalDistortion": 0.0});- if let Some(Value::Object(target)) = crate::type_tool::formatting_params(app) {- for (key, value) in target {- fields[key] = value;- }- }- dialog(app, fields, json!({"style": styles, "orientation": ["horizontal", "vertical"]}))- }+ "type.warpText" => Some(Ok(json!({"dialog": crate::dialogs::open_command_dialog(app, id, label)}))),"file.export.layersToFiles" => {let (_, _, name) = doc?;dialog(diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rsindex 13cc0fcdf..40ab54a11 100644--- a/crates/ui-egui/src/view_cmds/tests.rs+++ b/crates/ui-egui/src/view_cmds/tests.rs@@ -188,6 +188,7 @@ fn engine_commands_open_their_dialogs() {assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![0.0, 22.5, 32.5, 55.0]);app.run("type.create", json!({"x": 5, "y": 40, "text": "Warp", "size": 20})).unwrap();let d = menu(&mut app, &ctx, "type.warpText", json!({})).unwrap()["dialog"].as_u64().unwrap();+ app.ui.dialog_mut(d).unwrap().fields.insert("style".into(), json!("arc"));crate::dialogs::confirm(&mut app, d).unwrap();assert!(app.run("type.info", json!({})).unwrap()["warp"]["style"] == "warpArc");// Batch needs a recorded action.diff --git a/crates/ui-egui/src/warp_text_dialog_tests.rs b/crates/ui-egui/src/warp_text_dialog_tests.rsnew file mode 100644index 000000000..6057b8582--- /dev/null+++ b/crates/ui-egui/src/warp_text_dialog_tests.rs@@ -0,0 +1,195 @@+//! #218: Type › Warp Text… opens with the type layer's current warp (it always started at Arc)+//! and previews the warp live on the canvas.++use egui::vec2;+use egui_kittest::Harness;+use egui_kittest::kittest::Queryable;+use photocraft_doc::text::TextWarp;+use photocraft_doc::{Document, LayerContent};+use serde_json::{Map, Value, json};++use crate::PhotocraftApp;++/// A document with one type layer, active.+fn app_with_type() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 400, "height": 200})).unwrap();+ app.run("type.create", json!({"x": 20, "y": 120, "text": "Warp", "size": 60})).unwrap();+ app+}++fn flag() -> Value {+ json!({"style": "flag", "bend": -30.0, "horizontalDistortion": 20.0, "verticalDistortion": -10.0, "orientation": "vertical"})+}++fn warp(app: &PhotocraftApp) -> Option<TextWarp> {+ let st = app.session.active().unwrap();+ warp_of(&st.doc, st.active_layer.unwrap())+}++fn warp_of(doc: &Document, id: photocraft_doc::LayerId) -> Option<TextWarp> {+ match &doc.layer(id).unwrap().content {+ LayerContent::Text(t) => t.warp.clone(),+ _ => panic!("the layer is a type layer"),+ }+}++fn steps(app: &PhotocraftApp) -> usize {+ app.session.active().unwrap().history.entries().len()+}++/// The open dialogs drawn over `app`, as the window shows them.+fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {+ let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state(+ |ui, app| {+ if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {+ crate::dialogs::show(app, ui.ctx());+ }+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, Default::default());+ h.run_steps(4);+ h+}++/// Set dialog values as the sliders and dropdowns would, and compute the canvas preview as a+/// frame of the canvas does.+fn edit_and_preview(h: &mut Harness<'_, PhotocraftApp>, id: u64, values: Value) {+ let f = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields;+ for (k, v) in values.as_object().unwrap() {+ f.insert(k.clone(), v.clone());+ }+ h.run_steps(2);+ crate::canvas::ensure_filter_preview(h.state_mut(), 0, &egui::Context::default());+}++/// Open Warp Text from the Type menu and return the dialog with its fields.+fn open(app: &mut PhotocraftApp) -> (u64, Map<String, Value>) {+ let r = crate::menus::invoke(app, &egui::Context::default(), "type.warpText", json!({})).unwrap();+ let id = r["dialog"].as_u64().unwrap();+ (id, app.ui.dialog_mut(id).unwrap().fields.clone())+}++fn shown(fields: &Map<String, Value>) -> (&str, f64, f64, f64, &str) {+ let n = |k: &str| fields[k].as_f64().unwrap();+ (fields["style"].as_str().unwrap(), n("bend"), n("horizontalDistortion"), n("verticalDistortion"), fields["orientation"].as_str().unwrap())+}++#[test]+fn warp_text_opens_with_the_type_layers_current_warp() {+ let mut app = app_with_type();+ app.run("type.warpText", flag()).unwrap();+ let (_, fields) = open(&mut app);+ assert_eq!(shown(&fields), ("flag", -30.0, 20.0, -10.0, "vertical"));+}++#[test]+fn confirming_the_warp_text_dialog_unchanged_keeps_the_layers_warp() {+ let mut app = app_with_type();+ app.run("type.warpText", flag()).unwrap();+ let before = warp(&app);+ assert_eq!(before.as_ref().map(|w| w.style.as_str()), Some("warpFlag"));+ let (id, _) = open(&mut app);+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(warp(&app), before);+}++#[test]+fn warp_text_opens_at_none_for_a_layer_without_warp() {+ let mut app = app_with_type();+ let (id, fields) = open(&mut app);+ assert_eq!(shown(&fields), ("none", 50.0, 0.0, 0.0, "horizontal"));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(warp(&app), None);+}++#[test]+fn remembered_warp_values_never_override_the_layers_warp() {+ let mut app = app_with_type();+ let (id, _) = open(&mut app);+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;+ f.insert("style".into(), json!("twist"));+ f.insert("bend".into(), json!(80.0));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(warp(&app).map(|w| (w.style, w.value)), Some(("warpTwist".to_string(), 80.0)));+ app.run("type.create", json!({"x": 20, "y": 60, "text": "Other", "size": 30})).unwrap();+ app.run("type.warpText", flag()).unwrap();+ let (_, fields) = open(&mut app);+ assert_eq!(shown(&fields), ("flag", -30.0, 20.0, -10.0, "vertical"));+}++/// A PSD can carry a style without a short id: the dialog shows None with the layer's values.+#[test]+fn an_unknown_warp_style_opens_at_none_with_the_layers_values() {+ let mut app = app_with_type();+ let st = app.session.active_mut().unwrap();+ let id = st.active_layer.unwrap();+ let mut doc = (*st.doc).clone();+ if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {+ t.warp = Some(TextWarp { style: "warpCustom".into(), value: 12.0, horizontal_distortion: -5.0, vertical_distortion: 7.0, horizontal: false });+ }+ st.doc = std::sync::Arc::new(doc);+ let (_, fields) = open(&mut app);+ assert_eq!(shown(&fields), ("none", 12.0, -5.0, 7.0, "vertical"));+}++#[test]+fn warp_text_dialog_previews_the_warp_without_editing_the_document() {+ let mut app = app_with_type();+ let (id, fields) = open(&mut app);+ assert_eq!(fields.get("__preview"), Some(&json!(true)));+ let (revision, original) = {+ let st = app.session.active().unwrap();+ (st.revision, st.doc.clone())+ };+ let layer = app.session.active().unwrap().active_layer.unwrap();+ let mut h = harness(app);+ assert!(h.query_by_label("Preview").is_some(), "the dialog offers Preview");+ edit_and_preview(&mut h, id, json!({"style": "arc", "bend": 40.0}));+ let app = h.state();+ let shown = app.filter_preview.as_ref().and_then(|p| p.result.clone()).expect("a preview");+ assert_eq!(warp_of(&shown, layer).map(|w| (w.style, w.value)), Some(("warpArc".to_string(), 40.0)));+ assert_ne!(photocraft_compose::flatten(&shown).px, photocraft_compose::flatten(&original).px, "the preview shows the warp");+ let st = app.session.active().unwrap();+ assert_eq!(st.revision, revision);+ assert_eq!(warp(app), None, "the document is not edited");+}++#[test]+fn cancelling_warp_text_leaves_the_document_and_history_untouched() {+ let mut app = app_with_type();+ app.run("type.warpText", flag()).unwrap();+ let (before, history) = (warp(&app), steps(&app));+ let revision = app.session.active().unwrap().revision;+ let (id, _) = open(&mut app);+ let mut h = harness(app);+ edit_and_preview(&mut h, id, json!({"style": "wave", "bend": 70.0}));+ assert!(h.state().filter_preview.as_ref().is_some_and(|p| p.result.is_some()), "the preview is on screen");+ h.get_by_label("Cancel").click();+ h.run_steps(2);+ let app = h.state();+ assert!(app.ui.dialogs.is_empty());+ assert!(app.filter_preview.is_none(), "the preview is gone");+ assert_eq!(app.session.active().unwrap().revision, revision);+ assert_eq!((warp(app), steps(app)), (before, history));+}++#[test]+fn confirming_warp_text_is_one_undoable_step() {+ let mut app = app_with_type();+ app.run("type.warpText", flag()).unwrap();+ let (before, history) = (warp(&app), steps(&app));+ let (id, _) = open(&mut app);+ let mut h = harness(app);+ edit_and_preview(&mut h, id, json!({"style": "fish", "bend": 25.0, "orientation": "horizontal"}));+ h.get_by_label("OK").click();+ h.run_steps(2);+ let app = h.state_mut();+ assert!(app.ui.dialogs.is_empty());+ assert_eq!(warp(app).map(|w| (w.style, w.value, w.horizontal)), Some(("warpFish".to_string(), 25.0, true)));+ assert_eq!(steps(app), history + 1);+ assert_eq!(app.session.active().unwrap().history.entries().last().map(|e| e.to_string()), Some("Warp Text".to_string()));+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(warp(app), before);+}