diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index f50d00d1d7..98cbe43ccd 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -131,23 +131,25 @@ fn move_anchors(s: &mut Session, p: &Value) -> Result { if duplicate && anchors.iter().any(|a| a[0] != sub) { return Err(bad(CMD, "`duplicate` takes all the anchors of one subpath")); } + if duplicate && p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { + return Err(bad(CMD, "`duplicate` and `curvature` can't be combined")); + } let label = step_name(CMD, p, if duplicate { "Drag Path" } else { "Drag Anchor Points" }, &["Drag Path", "Drag Anchor Point"])?; let curvature = p.get("curvature").and_then(Value::as_bool).unwrap_or(false); edit_path(s, CMD, p, label, |path| { - let mut anchors = anchors; if duplicate { - // Direct Selection's ⌥-drag (#13211): the copy, with the source's operation, goes last - // and moves; the source stays. - let copy = path.subpaths.get(sub).cloned().ok_or_else(|| format!("no subpath {sub} (the path has {})", path.subpaths.len()))?; + // Direct Selection's and Add Anchor Point's ⌥-drag (#13211, #12709): the copy goes + // last and moves; the source stays. The copy keeps the source's operation, but a copy + // of a joined subpath takes its component's (`edit::duplicate_subpaths`), so it stands + // alone instead of joining whichever component is last. + let count = path.subpaths.get(sub).ok_or_else(|| format!("no subpath {sub} (the path has {})", path.subpaths.len()))?.knots.len(); let mut knots: Vec = anchors.iter().map(|a| a[1]).collect(); knots.sort_unstable(); knots.dedup(); - if !knots.iter().copied().eq(0..copy.knots.len()) { + if !knots.iter().copied().eq(0..count) { return Err("`duplicate` takes all the anchors of one subpath".into()); } - path.subpaths.push(copy); - let last = path.subpaths.len() - 1; - anchors.iter_mut().for_each(|a| a[0] = last); + return edit::duplicate_subpaths(path, &anchors, d).map(|_| ()); } if curvature { edit::move_anchors_curvature(path, &anchors, d) } else { edit::move_anchors(path, &anchors, d) } }) @@ -322,7 +324,7 @@ pub fn specs() -> Vec { journal: true, }; vec![ - spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors),"duplicate":bool=false (anchors = all of one subpath's; that subpath is copied, with its operation, as the path's last subpath, and the copy's anchors move instead; the source stays; Direct Selection's ⌥-drag on a segment),"stepName":"Drag Path"|"Drag Anchor Point"? (History step name; the Convert Point tool sends "Drag Path" when it drags a whole path, Direct Selection "Drag Anchor Point" when it drags one anchor; default "Drag Anchor Points", "Drag Path" with duplicate; any other value is refused)"#.into(), move_anchors), + spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors),"duplicate":bool=false (anchors = all of one subpath's; that subpath is copied, with its operation (a joined subpath's copy takes its component's), as the path's last subpath, and the copy's anchors move instead; the source stays; Direct Selection's ⌥-drag on a segment, Add Anchor Point's ⌥-drag; not with curvature),"stepName":"Drag Path"|"Drag Anchor Point"? (History step name; the Convert Point tool sends "Drag Path" when it drags a whole path, Direct Selection "Drag Anchor Point" when it drags one anchor, Add Anchor Point "Drag Path" when it duplicates a subpath; default "Drag Anchor Points", "Drag Path" with duplicate; any other value is refused)"#.into(), move_anchors), spec( "path.moveHandle", "Drag Control Point", @@ -838,6 +840,9 @@ mod tests { ("path.moveAnchors", json!({"anchors": [[0]], "move": [1, 1]})), ("path.moveAnchors", json!({"anchors": [[0, 0]], "move": [1e300, 1]})), ("path.moveAnchors", json!({"anchors": [[0, 0]]})), + ("path.moveAnchors", json!({"anchors": [[0, 0]], "move": [1, 1], "duplicate": "yes"})), + ("path.moveAnchors", json!({"anchors": [[0, 0]], "move": [1, 1], "duplicate": true, "curvature": true})), + ("path.moveAnchors", json!({"anchors": [[1, 0]], "move": [1, 1], "duplicate": true})), ("path.moveHandle", json!({"subpath": 0, "knot": 0, "handle": "up", "to": [1, 1]})), ("path.moveHandle", json!({"subpath": 0, "knot": 0, "handle": "in"})), ("path.moveHandle", json!({"subpath": -1, "knot": 0, "handle": "in", "to": [1, 1]})), @@ -905,6 +910,33 @@ mod tests { assert!(s.undo()); assert_eq!(work(&s), before); } + + /// A copy of a joined subpath (a component's hole) takes its component's operation and stands + /// alone: it never joins the last component, which would cut it out of that one instead. + #[test] + fn a_duplicated_joined_subpath_stands_alone() { + let mut s = session(); + s.execute( + "path.set", + json!({"path": {"subpaths": [ + {"closed": true, "knots": [[10, 10], [60, 10], [60, 60], [10, 60]]}, + {"closed": true, "op": "join", "knots": [[25, 25], [25, 45], [45, 45], [45, 25]]}, + {"closed": true, "op": "subtract", "knots": [[70, 10], [110, 10], [110, 50], [70, 50]]}, + ]}}), + ) + .unwrap(); + let before = work(&s); + let at = |p: &photocraft_doc::Path, x: i32, y: i32| photocraft_vector::path_coverage(p, photocraft_geom::Rect::new(x, y, x + 1, y + 1))[0]; + assert_eq!((at(&before, 35, 35), at(&before, 15, 15), at(&before, 90, 35)), (0.0, 1.0, 0.0), "A has its hole; B cuts nothing"); + s.execute("path.moveAnchors", json!({"anchors": [[1, 0], [1, 1], [1, 2], [1, 3]], "move": [55, 0], "duplicate": true})).unwrap(); + let after = work(&s); + assert_eq!(after.subpaths[..3], before.subpaths[..], "the source stays"); + assert_eq!(after.subpaths.len(), 4); + assert_eq!(after.subpaths[3].op, PathOp::Combine, "the copy of A's hole takes A's operation"); + assert_eq!(after.components(), vec![0..2, 2..3, 3..4], "the copy is a component of its own"); + assert_eq!(at(&after, 90, 35), 1.0, "the copy fills where it landed"); + assert_eq!((at(&after, 35, 35), at(&after, 15, 15)), (0.0, 1.0), "A and its hole are unchanged"); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index 8091a10f99..4b2433b008 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -1424,6 +1424,12 @@ fn printers(s: &mut Session, _: &Value) -> Result { } fn printer_page(_: &mut Session, p: &Value) -> Result { + page_of_printer(p, printing_disabled()) +} + +/// `file.print.page` with printing turned off or not (`disabled`). A test passes `false` to reach the printer route, +/// which `printing_disabled` never is once a test of the process or CI's `PHOTOCRAFT_NO_PRINT` turned it off. +fn page_of_printer(p: &Value, disabled: bool) -> Result { // Checked before the printer, so a bad value is the error whether or not a printer answers. let landscape = match p.get("orientation").filter(|v| !v.is_null()) { None => None, @@ -1433,8 +1439,13 @@ fn printer_page(_: &mut Session, p: &Value) -> Result { _ => return Err(bad("file.print.page", "orientation is \"portrait\" or \"landscape\"")), }, }; - let printer = printer_name(p)?; let mut settings = printer_settings(p)?; + // A driver query is still a call into a printer driver, which can hang (and holds SPOOLER + // while it does), so a process that turned printing off asks no driver here either. + if disabled { + return Err(other("printing is disabled in this process (disable_printing or PHOTOCRAFT_NO_PRINT); file.print.page asks no printer driver")); + } + let printer = printer_name(p)?; if let Some(landscape) = landscape { let base = match settings { Some(s) => s, @@ -1451,11 +1462,14 @@ fn printer_page(_: &mut Session, p: &Value) -> Result { Ok(out) } -/// Set once by test harnesses (the panic hunt) so no command in the process can reach a printer. +/// Set once by test harnesses (the panic hunt) so no command in the process can reach a printer +/// or its driver: `file.print` and `file.printOneCopy` refuse to spool, and `file.print.page` +/// refuses to ask a driver for its page. static PRINTING_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -/// Refuse to spool anything from this process from now on (tests, fuzzing). The -/// `PHOTOCRAFT_NO_PRINT` environment variable does the same for a whole shell (CI). +/// Refuse to spool anything, or ask a printer driver for its page, from this process from now on +/// (tests, fuzzing). The `PHOTOCRAFT_NO_PRINT` environment variable does the same for a whole +/// shell (CI). pub fn disable_printing() { PRINTING_DISABLED.store(true, std::sync::atomic::Ordering::Relaxed); } diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index 8136cd2fba..1d35fc3cc4 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -783,6 +783,19 @@ fn disabled_printing_never_spools() { let e = s.execute("file.print", json!({})).unwrap_err().to_string(); assert!(e.contains("printing is disabled"), "{e}"); assert!(s.execute("file.printOneCopy", json!({})).is_err()); + // Nor does it ask a driver for its page: on a Windows runner that call can hang, holding SPOOLER. + let e = s.execute("file.print.page", json!({})).unwrap_err().to_string(); + assert!(e.contains("printing is disabled"), "{e}"); + // Bad values are still the error they were, before the check. + let e = s.execute("file.print.page", json!({"orientation": "sideways"})).unwrap_err().to_string(); + assert!(e.contains("orientation"), "{e}"); + // With printing on the command goes past the switch to the printer route: off Windows the GDI route has no + // printers, so a named printer's page is the route's own refusal (no driver is asked there). + #[cfg(not(windows))] + { + let e = super::page_of_printer(&json!({"printer": "Anything"}), false).unwrap_err().to_string(); + assert!(!e.contains("printing is disabled"), "{e}"); + } // A dry run still renders and reports the command it would have run. let r = s.execute("file.print", json!({"dryRun": true})).unwrap(); assert_eq!(r["sent"], false); diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index 1024dae194..4fe4c3fccc 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -222,7 +222,11 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM let fmt = doc.pixel_format(); // The path is stored in the document's data sets. let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the image", path, why))?; - let bytes = std::fs::read(&file).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?; + let bytes = std::fs::read(&file).map_err(|e| match e.kind() { + // The reference application's alert; the error also names the file (#14500). + std::io::ErrorKind::NotFound => EngineError::Other(format!("{DATA_SET_FILE_MISSING} ({path})")), + _ => EngineError::Other(format!("read `{path}`: {e}")), + })?; let src = crate::file_cmds::import(path, &bytes)?; let img = crate::file_cmds::flattened(&src, fmt); let (iw, ih) = (src.size.width.max(1) as f64, src.size.height.max(1) as f64); @@ -289,7 +293,15 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { s.edit(label, |_, _| Ok(()))?; return Err(EngineError::Other(DATA_SET_LAYER_LOCKED.into())); } - s.edit(label, |doc, _| apply_to_doc(doc, &vars, &set))?; + match s.edit(label, |doc, _| apply_to_doc(doc, &vars, &set)) { + // A missing replacement file applies nothing of the set (the edit is dropped whole), but + // the attempt is still a history state that changes nothing, as for a locked layer (#14500). + Err(EngineError::Other(m)) if m.starts_with(DATA_SET_FILE_MISSING) => { + s.edit(label, |_, _| Ok(()))?; + return Err(EngineError::Other(m)); + } + r => r?, + } set_vars(s, |v| v.active = Some(idx))?; Ok(json!({"applied": set.name, "index": idx})) } @@ -317,6 +329,10 @@ pub fn data_set_preview(s: &Session, index: usize) -> Result { /// under Lock All. pub const DATA_SET_LAYER_LOCKED: &str = "Could not apply data set because the layer is locked."; +/// The reference application's alert when a Pixel Replacement value names a file that does not +/// exist. The command's error starts with it and names the file in parentheses. +pub const DATA_SET_FILE_MISSING: &str = "Could not apply data set because the replacement file was not found."; + /// Whether `set` has a Text value for a type layer with its own Lock All. Visibility and Pixel /// Replacement values still apply to locked layers, as in the reference application; partial /// locks and a locked group were not measured and keep applying (#14499). @@ -626,5 +642,8 @@ mod import_enabled_tests; #[cfg(test)] mod locked_text_layer_tests; +#[cfg(test)] +mod missing_file_tests; + #[cfg(test)] mod apply_history_name_tests; diff --git a/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs b/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs new file mode 100644 index 0000000000..87d78575ce --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs @@ -0,0 +1,161 @@ +//! #14500: Apply Data Set with a Pixel Replacement value naming a file that does not exist fails +//! with the reference application's alert, the error naming the file. Nothing of the set is +//! applied, but one history state that changes nothing is still added. A file that exists but +//! cannot be decoded keeps an error naming the file (not measured). + +use super::*; +use photocraft_doc::{Layer, TextLayer}; +use photocraft_geom::Rect; + +const APPLY: &str = "image.applyDataSet"; + +/// A document with a grey raster "photo", a red raster "badge" and a text layer "title", bound to +/// the variables `photo` (pixels), `showBadge` (visibility) and `headline` (text). +fn session() -> (Session, LayerId, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let (photo, badge, title) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut photo = Layer::raster("photo", fmt); + photo.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0])); + let mut badge = Layer::raster("badge", fmt); + badge.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 10, 10), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() })); + let ids = (photo.id, badge.id, title.id); + doc.layers.extend([photo, badge, title]); + Ok(ids) + }) + .unwrap(); + s.execute( + "image.variables.define", + json!({"defs": [ + {"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"}, + {"name": "showBadge", "layer": badge.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + ]}), + ) + .unwrap(); + (s, photo, badge, title) +} + +/// A fresh scratch folder for one test. +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("pc-vars-{}-missing-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The set "Two": hides the badge, replaces the headline and the photo with `png`. +fn set_two(s: &mut Session, png: &str) { + s.execute( + "image.variables.dataSets", + json!({"dataSets": [{"name": "Two", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "New"}, + {"variable": "photo", "kind": "pixels", "value": png}, + ]}]}), + ) + .unwrap(); +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn text_of(s: &Session, id: LayerId) -> String { + match &doc(s).layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + _ => panic!("not a text layer"), + } +} + +fn history(s: &Session) -> (usize, Option) { + let h = &s.active().unwrap().history; + (h.past_len(), h.entries().last().map(|e| e.to_string())) +} + +#[test] +fn a_missing_replacement_file_fails_with_the_alert_text_and_names_the_file() { + let (mut s, ..) = session(); + let dir = scratch("text"); + let png = dir.join("renamed.png").to_string_lossy().into_owned(); + set_two(&mut s, &png); + + let r = s.execute(APPLY, json!({"name": "Two"})); + let Err(EngineError::Other(m)) = &r else { panic!("{r:?}") }; + assert_eq!(DATA_SET_FILE_MISSING, "Could not apply data set because the replacement file was not found."); + assert!(m.starts_with(DATA_SET_FILE_MISSING), "{m}"); + assert!(m.contains(&png), "the error names the file: {m}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_missing_replacement_file_applies_nothing_but_adds_one_history_state() { + let (mut s, photo, badge, title) = session(); + let dir = scratch("nothing"); + set_two(&mut s, &dir.join("renamed.png").to_string_lossy()); + let before = doc(&s).clone(); + let (n, _) = history(&s); + + assert!(s.execute(APPLY, json!({"name": "Two"})).is_err()); + + // Nothing of the set: also not its valid Visibility and Text values. + assert!(doc(&s).layer(badge).unwrap().visible); + assert_eq!(text_of(&s, title), "Old"); + assert_eq!(doc(&s).layer(photo).unwrap().surface().unwrap().pixel(32, 24), before.layer(photo).unwrap().surface().unwrap().pixel(32, 24)); + assert_eq!(doc(&s).layers, before.layers); + assert_eq!(doc(&s).variables.active, None, "the set did not become the applied one"); + + // One history state for the attempt, which changes nothing. + let (after, label) = history(&s); + assert_eq!(after, n + 1); + assert!(label.as_deref().is_some_and(|l| l.starts_with("Apply Data Set")), "{label:?}"); + assert!(s.undo()); + assert_eq!(history(&s).0, n); + assert_eq!(doc(&s).layers, before.layers); + assert!(s.redo()); + assert_eq!(doc(&s).layers, before.layers, "the state changes nothing"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_file_that_cannot_be_decoded_keeps_an_error_naming_it_and_no_history_state() { + let (mut s, _photo, badge, _title) = session(); + let dir = scratch("garbage"); + let png = dir.join("broken.png"); + std::fs::write(&png, b"not an image at all").unwrap(); + let png = png.to_string_lossy().into_owned(); + set_two(&mut s, &png); + let (n, _) = history(&s); + + let r = s.execute(APPLY, json!({"name": "Two"})); + let Err(e) = &r else { panic!("{r:?}") }; + let m = e.to_string(); + assert!(!m.contains(DATA_SET_FILE_MISSING), "not the missing-file alert: {m}"); + assert!(m.contains("broken.png"), "the error names the file: {m}"); + assert!(doc(&s).layer(badge).unwrap().visible, "nothing applied"); + assert_eq!(history(&s).0, n, "today's behaviour: no history state"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_same_set_applies_once_the_file_is_back() { + let (mut s, photo, badge, title) = session(); + let dir = scratch("back"); + let png = dir.join("blue.png"); + set_two(&mut s, &png.to_string_lossy()); + assert!(s.execute(APPLY, json!({"name": "Two"})).is_err()); + + let mut src = Session::new(); + src.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap(); + let bytes = photocraft_io::export(&src.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; + std::fs::write(&png, bytes).unwrap(); + s.execute(APPLY, json!({"name": "Two"})).unwrap(); + assert!(!doc(&s).layer(badge).unwrap().visible); + assert_eq!(text_of(&s, title), "New"); + assert_eq!(doc(&s).layer(photo).unwrap().surface().unwrap().pixel(32, 24), vec![0.0, 0.0, 1.0, 1.0]); + assert_eq!(doc(&s).variables.active, Some(0)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 71ceb89ee6..f23eabd7d5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,7 +45,7 @@ pub mod select_mask_edits; pub mod shell_commands; pub mod shortcut_sets; pub mod snap; -pub use variables_cmds::{DATA_SET_LAYER_LOCKED, data_set_preview, export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, data_set_preview, export_data_sets_with, import_data_sets_text}; pub use video_cmds::render_video_with; use std::sync::Arc; diff --git a/crates/engine/src/presets/patterns.rs b/crates/engine/src/presets/patterns.rs index 04d5160b81..9644af6bb0 100644 --- a/crates/engine/src/presets/patterns.rs +++ b/crates/engine/src/presets/patterns.rs @@ -20,17 +20,27 @@ pub fn builtin_groups() -> Vec> { vec![Group::new("Geometric", ids(&["Checkerboard", "Diagonal Lines", "Dots", "Grid"])), Group::new("Textures", ids(&["Bricks", "Weave", "Paper Noise"]))] } -/// Bring the groups in line with the library (see the module docs). +/// Bring the groups in line with the library (see the module docs). Groups already in line are left unwritten: a +/// write moves the presets' revision, which the menus and the preset views rebuild on, and the Patterns panel syncs +/// in every pass it shows. pub fn sync(s: &mut Session) { - let lib: Vec = s.patterns.items.iter().map(|p| p.id.clone()).collect(); + let lib = &s.patterns.items; + let in_lib = |id: &String| lib.iter().any(|p| &p.id == id); + let groups = &s.presets.pattern_groups; + let stale = groups.iter().any(|g| !g.items.iter().all(in_lib)); + let loose: Vec = lib.iter().map(|p| &p.id).filter(|id| !groups.iter().any(|g| g.items.contains(id))).cloned().collect(); + if !stale && loose.is_empty() { + return; + } let groups = &mut s.presets.pattern_groups; for g in groups.iter_mut() { - g.items.retain(|id| lib.contains(id)); + g.items.retain(in_lib); } - let loose: Vec = lib.iter().filter(|id| !groups.iter().any(|g| g.items.contains(id))).cloned().collect(); if !loose.is_empty() { let gi = group_index(groups, Some(UNGROUPED)); - groups[gi].items.extend(loose); + if let Some(group) = groups.get_mut(gi) { + group.items.extend(loose); + } } } diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs index 35b150a1df..19c32059da 100644 --- a/crates/engine/src/presets/tests.rs +++ b/crates/engine/src/presets/tests.rs @@ -433,6 +433,28 @@ fn pattern_groups_select_apply_and_sync() { assert!(crate::pattern_cmds::resolve(&s, "Weave").is_none()); } +/// #16221: syncing groups already in line with the library leaves the presets' revision alone (the Patterns panel +/// syncs in every pass, and the menus rebuild on that revision); a library change still moves it. +#[test] +fn pattern_sync_writes_only_when_the_groups_change() { + let mut s = session(8); + super::patterns::sync(&mut s); + let settled = s.presets.revision(); + super::patterns::sync(&mut s); + assert_eq!(s.presets.revision(), settled, "groups in line with the library are not written"); + let mut extra = s.patterns.items[0].clone(); + extra.id = "sync-test-extra".into(); + s.patterns.items.push(extra); + super::patterns::sync(&mut s); + assert_ne!(s.presets.revision(), settled, "a new library pattern joins a group"); + assert!(s.presets.pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); + let joined = s.presets.revision(); + s.patterns.items.retain(|p| p.id != "sync-test-extra"); + super::patterns::sync(&mut s); + assert_ne!(s.presets.revision(), joined, "a deleted pattern leaves its group"); + assert!(!s.presets.pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); +} + #[test] fn pattern_batch_delete_keeps_the_library_when_one_name_is_missing() { let mut s = session(8); diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 81f893ee68..acb260b918 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -10,7 +10,8 @@ use std::sync::{Mutex, Once, PoisonError, mpsc}; use std::time::Duration; fn fresh() -> Session { - // Belt and braces with the EXTERNAL skip below: nothing in this process may reach a printer. + // Belt and braces with CI's PHOTOCRAFT_NO_PRINT: nothing in this process may reach a printer + // or its driver (file.print.page refuses to ask one, so a hung driver can't hold SPOOLER). photocraft_engine::print_cmds::disable_printing(); let mut s = Session::new(); // `file.printers` and `file.print.printers` list no printers and do not ask the spooler. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 4e61d8a721..95b016792c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -72,6 +72,7 @@ impl PhotocraftApp { menu_model: None, toolbar_slots: Default::default(), dock_model: Default::default(), + preset_art: Default::default(), move_preview: None, move_hover: None, move_distance: None, @@ -339,3 +340,6 @@ mod clipboard_tests; #[cfg(test)] mod apply_data_set_alert_tests; + +#[cfg(test)] +mod apply_data_set_missing_file_tests; diff --git a/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs new file mode 100644 index 0000000000..f36607d621 --- /dev/null +++ b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs @@ -0,0 +1,53 @@ +//! #14500: Apply Data Set with a missing replacement file closes the dialog and shows the +//! reference application's alert, which names no file; the status bar keeps the file's name. + +use super::*; +use serde_json::json; + +const MISSING: &str = "Could not apply data set because the replacement file was not found."; + +/// An app with a raster layer bound to a `photo` pixel variable and one data set `Two` whose +/// image is `missing.png` in a new, empty folder. The folder lives as long as the returned guard, +/// and is removed also when an assertion fails. +fn app() -> (Box, tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let png = dir.path().join("missing.png"); + assert!(!png.exists()); + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.session.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + let id = app.session.execute("layer.new.layer", json!({})).unwrap()["layer"].clone(); + app.session.execute("image.variables.define", json!({"defs": [{"name": "photo", "layer": id, "type": "pixelReplacement"}]})).unwrap(); + app.session + .execute( + "image.variables.dataSets", + json!({"dataSets": [{"name": "Two", "values": [{"variable": "photo", "kind": "pixels", "value": png.to_string_lossy()}]}]}), + ) + .unwrap(); + app.sync_views(); + (app, dir, png) +} + +/// The messages of the open framework alerts. +fn alerts(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(String::from)).collect() +} + +#[test] +fn ok_in_the_apply_dialog_closes_it_and_shows_the_alert() { + let (mut app, _dir, png) = app(); + crate::menus::invoke(&mut app, &egui::Context::default(), "image.applyDataSet", json!({})).unwrap(); + let dialog = app.top_dialog().expect("the Apply Data Set dialog is open"); + // The hosted dialog reports the refusal through the status bar and the alert, not as OK's result. + let _ = crate::dialogs::testing::confirm(&mut app, dialog); + assert!(app.framework.dialogs.get_dyn(dialog).is_none(), "the Apply Data Set dialog closed"); + assert_eq!(alerts(&app), [MISSING]); + assert!(app.ui.status.contains(&*png.to_string_lossy()), "the status names the file: {}", app.ui.status); +} + +#[test] +fn the_command_shows_the_alert_without_the_file_name() { + let (mut app, _dir, png) = app(); + let e = app.run("image.applyDataSet", json!({"name": "Two"})).unwrap_err(); + assert!(e.starts_with(MISSING) && e.contains(&*png.to_string_lossy()), "{e}"); + assert_eq!(alerts(&app), [MISSING]); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index a521eb15e1..8910563fb3 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -223,9 +223,15 @@ impl PhotocraftApp { Err(e) => { self.ui.status = e.clone(); self.ui.status_error = true; - if id == "image.applyDataSet" && e == photocraft_engine::DATA_SET_LAYER_LOCKED { - // The reference application refuses a locked type layer with an alert (#14499). - let _ = crate::dialogs::alerts::alert(self, tl!(photocraft_engine::DATA_SET_LAYER_LOCKED)); + // The reference application refuses a locked type layer (#14499) and a missing + // replacement file (#14500) with an alert; the alert names no layer or file. + let alert = [photocraft_engine::DATA_SET_LAYER_LOCKED, photocraft_engine::DATA_SET_FILE_MISSING] + .into_iter() + .find(|a| e == *a || e.strip_prefix(a).is_some_and(|rest| rest.starts_with(" ("))); + if id == "image.applyDataSet" + && let Some(alert) = alert + { + let _ = crate::dialogs::alerts::alert(self, tl!(alert)); } } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b3ba2963a0..e441ae2f6a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -262,9 +262,10 @@ mod rotation_preview_isolation_tests { use super::*; - /// Opens the filter dialog of `command` and returns its id. + /// Opens the filter dialog of `command` with its Preview box and returns its id. Rotate Canvas has no Preview + /// (#14462); its size-changing preview (#1436) is reached through `open_previewing`. fn open(app: &mut PhotocraftApp, command: &str) -> DialogId { - let id = crate::filter_dialog::open(app, command).expect("the dialog opens"); + let id = crate::filter_dialog::open_previewing(app, command).expect("the dialog opens"); // The Preview box is on from the dialog's first drawn pass. for _ in 0..2 { crate::smart_filter_dialog::tests::pass(app); diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 446295699e..052581d13d 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -503,23 +503,6 @@ fn canvas_controls( ) -> Option<(photocraft_doc::LayerId, photocraft_doc::Fill)> { let pointer = ui.input(|i| i.pointer.hover_pos()); let now = ui.input(|i| i.time); - // The scroll bars (Standard Screen Mode only) and the rotation compass change the view they are bound to. They - // are shown first: a control shown later is above the earlier ones, and a body part such as the text editor - // takes no press under a member that covers the whole canvas. - let mut shown = space.view; - if !app.ui.view.hides_chrome() { - let size = app.session.documents()[host.idx].doc.size; - let bounds = Rect64::from_origin_size(Point::ZERO, Size::new(f64::from(size.width), f64::from(size.height))); - CanvasScrollbars::new("Scroll bars", Bind::bound(&mut shown), bounds) - .overscroll(app.session.prefs().tools.overscroll) - .document_chrome() - .show_at(ui, rect); - } - if RotateView::visible(shown.rotation) { - let mut rotation = shown.rotation; - RotateView::new("Rotate View", Bind::bound(&mut rotation), shown.flip_x).show_at(ui, RotateView::compass_rect(ui, rect)); - shown.rotation = rotation; - } crate::distort_ui::show_in_canvas(app, ui, rect); crate::blur_pins::overlay(app, ui, rect); let doc = app.session.documents()[host.idx].doc.id; @@ -552,6 +535,24 @@ fn canvas_controls( if primary { reported.crop = super::tools::crop::show_frame(app, ui, rect); } + // The scroll bars (Standard Screen Mode only) and the rotation compass change the view they are bound to. They are + // window chrome that works with every tool, so they are shown after the tools' controls: a control shown later is + // above the earlier ones, and the Crop frame covers the whole canvas (its outside turns the frame; #16231). They + // declare parts only over the bars and the compass, so a press elsewhere still reaches the controls below. + let mut shown = space.view; + if !app.ui.view.hides_chrome() { + let size = app.session.documents()[host.idx].doc.size; + let bounds = Rect64::from_origin_size(Point::ZERO, Size::new(f64::from(size.width), f64::from(size.height))); + CanvasScrollbars::new("Scroll bars", Bind::bound(&mut shown), bounds) + .overscroll(app.session.prefs().tools.overscroll) + .document_chrome() + .show_at(ui, rect); + } + if RotateView::visible(shown.rotation) { + let mut rotation = shown.rotation; + RotateView::new("Rotate View", Bind::bound(&mut rotation), shown.flip_x).show_at(ui, RotateView::compass_rect(ui, rect)); + shown.rotation = rotation; + } // One contextual task bar per window: the active document's tile carries it, not the tile drawn last. if app.session.active_index() == Some(host.idx) { crate::crop_task_bar::show(app, ui, rect); @@ -725,6 +726,59 @@ mod tests { } } + /// #16231: with the Crop tool active the scroll bars still scroll the view. The crop frame is shown after them and + /// covers the whole canvas (its outside turns the frame), so it took every press on them before. + #[test] + fn canvas_scrollbars_scroll_while_the_crop_tool_is_active() { + use egui::accesskit::Role; + use egui::{Event, PointerButton, vec2}; + use egui_kittest::kittest::Queryable; + + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_pixels_per_point(1.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.tool = Tool::Crop; + app + }); + h.run_steps(6); + // 400 % makes the document larger than the window, so both bars have room to scroll. + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 4.0; + view.center = [200.0, 150.0]; + view.clear_pending(); + h.run_steps(4); + let frame = h.state().canvas_tools.crop.tool.frame(); + assert!(frame.is_some(), "the Crop tool shows its default frame"); + + for (label, along) in [("Horizontal scroll bar", vec2(40.0, 0.0)), ("Vertical scroll bar", vec2(0.0, 40.0))] { + let before = testing::view(h.state()).expect("the document is shown"); + // The view is centred, so the thumb lies over the middle of its track. + let thumb = h.get_by_role_and_label(Role::ScrollBar, label).rect().center(); + h.hover_at(thumb); + h.run_steps(2); + h.drag_at(thumb); + h.run_steps(1); + for step in [0.25, 0.5, 1.0] { + h.hover_at(thumb + along * step); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: thumb + along, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + let after = testing::view(h.state()).expect("the document is shown"); + if along.x > 0.0 { + assert!(after.center.x > before.center.x + 10.0, "{label} drag scrolls the view: {before:?} -> {after:?}"); + assert_eq!(after.center.y, before.center.y, "{label} drag keeps the other axis"); + } else { + assert!(after.center.y > before.center.y + 10.0, "{label} drag scrolls the view: {before:?} -> {after:?}"); + assert_eq!(after.center.x, before.center.x, "{label} drag keeps the other axis"); + } + let tool = &h.state().canvas_tools.crop.tool; + assert_eq!(tool.frame(), frame, "{label} drag leaves the crop frame alone"); + assert!(!tool.modified(), "{label} drag starts no crop edit"); + } + } + /// Four conditions decide whether the selection's ants show; each hides them alone, and Escape on an open polygon /// outline brings them back. #[test] diff --git a/crates/ui-egui/src/canvas/raster_source/tests.rs b/crates/ui-egui/src/canvas/raster_source/tests.rs index 4d617d01c8..3c4be1af2a 100644 --- a/crates/ui-egui/src/canvas/raster_source/tests.rs +++ b/crates/ui-egui/src/canvas/raster_source/tests.rs @@ -349,7 +349,8 @@ fn a_size_changing_preview_lies_centred_on_the_document() { let mut app = app_with(64, 32, "white"); app.background_jobs = false; app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap(); - let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + // Rotate Canvas has no Preview of its own (#14462); the canvas still places a size-changing one. + let id = crate::filter_dialog::open_previewing(&mut app, "image.rotation.arbitrary").unwrap(); let ctx = app.ctx().clone(); app.framework.dialogs.set_json_field(&ctx, id, "angle", json!(90.0)).unwrap(); // The Preview box is on from the dialog's first drawn pass. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8e827d7e4d..e3cca6c221 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -749,6 +749,9 @@ pub(crate) mod pattern_fill_ui; pub mod preset_group_prompt; pub mod rasterize_prompt; #[cfg(test)] +mod rotate_canvas_layout_tests; +pub(crate) mod rotate_canvas_ui; +#[cfg(test)] mod scale_effects_layout_tests; pub mod screen_picker; pub mod select_mask_ui; diff --git a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs index 4bcc4dd328..8d0885aa2d 100644 --- a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs +++ b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs @@ -54,7 +54,8 @@ fn ruler_prefill_keeps_the_measured_two_decimal_angle() { } /// #13067 (f32 double rounding): the 43x27 ruler is 32.1249984 degrees. OK with no shown pass -/// between open and OK, and again after Alt+Reset, sends 32.12 exactly. +/// between open and OK, and again after the dialog was drawn, sends 32.12 exactly. (Rotate Canvas +/// has no Alt+Reset, #14462.) #[test] fn the_ruler_angle_is_rounded_before_the_first_frame() { let (mut app, id) = open_ruler([143, 127]); @@ -67,11 +68,6 @@ fn the_ruler_angle_is_rounded_before_the_first_frame() { .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); PhotocraftApp::setup_context(&h.ctx, Default::default()); h.run_steps(3); - // Move off the pre-fill first, so only the reset can bring 32.12 back. - let set_ctx = h.ctx.clone(); - h.state_mut().framework.dialogs.set_json_field(&set_ctx, id, "angle", json!(5.0)).unwrap(); - h.run_steps(2); - h.get_by_label("Cancel").click_modifiers(egui::Modifiers::ALT); - h.run_steps(3); - assert_eq!(confirmed_angle(h.state_mut(), id), Some(32.12), "after Alt+Reset, OK sends the rounded angle"); + assert!(h.query_by_label("Cancel").is_some(), "the dialog is drawn"); + assert_eq!(confirmed_angle(h.state_mut(), id), Some(32.12), "drawn, OK sends the rounded angle"); } diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index d823352e3a..7b460e473a 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -82,8 +82,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { } let [r, g, b, _] = app.session.tools.foreground; let first = app.session.patterns.items.first().map(|p| p.id.clone()); - let ctx = app.ctx().clone(); - let patterns = crate::panels::preset_browser::pattern_swatches(app, &ctx); + let patterns = crate::panels::preset_browser::pattern_swatches(app); let rows = rows([r, g, b], first.clone()); let reset = defaults([r, g, b], first); let title = Label::from(tl!("Fill")); diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 4654ed7847..806a31822e 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -178,7 +178,6 @@ pub const PREVIEWED: &[&str] = &[ "image.adjustments.replaceColor", MATCH_COLOR, "image.adjustments.hdrToning", - "image.rotation.arbitrary", "image.mode.indexedColor", "image.mode.bitmap", "image.mode.duotone", @@ -210,6 +209,8 @@ pub fn has_dialog(command: &str) -> bool { || matches!( command, "image.trim" + // Rotate Canvas has no preview, as in the reference application (#14462). + | "image.rotation.arbitrary" | "view.proofSetup" | "layer.layerStyle.globalLight" | "image.mode.colorTable" @@ -336,12 +337,6 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if document_derived(command, &p.key) { p = p.not_remembered(); } - // #14465: the row opens from Preferences › General › Image Interpolation on every - // opening, so a pick there applies to that opening only; the row stays out of the - // remembered values, as the rows above do. - if command == "image.rotation.arbitrary" && p.key == "interpolation" { - p = p.not_remembered(); - } // Global Light's Altitude takes whole degrees, as its Angle does (#14980). if command == "layer.layerStyle.globalLight" && p.key == "altitude" { p = p.decimals(0); @@ -365,6 +360,10 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec< if command == "image.mode.colorTable" { list.extend(crate::color_table_ui::rows(app)); } + // Rotate Canvas: one row of its own, without the Interpolation row (#14462). + if command == super::rotate_canvas_ui::COMMAND { + list = super::rotate_canvas_ui::params(); + } rows::custom_rows(app, command, &mut list); if command == "edit.colorSettings" { // The monitor line under the rows: the cell holds the text each frame refreshes, which the build closure cannot read from the app. @@ -421,6 +420,9 @@ pub(crate) fn fields(app: &PhotocraftApp, command: &str, params: &[Param]) -> Di if command == crate::bitmap_dialog::COMMAND { crate::bitmap_dialog::defaults(app, &mut fields); } + if command == super::rotate_canvas_ui::COMMAND { + super::rotate_canvas_ui::open_values(&mut fields); + } fields } @@ -429,17 +431,9 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map let mut map = Map::new(); if command == "image.rotation.arbitrary" { straighten_defaults(app, &mut map); - // #14465: the reference dialog offers no interpolation choice; its resampling - // follows Preferences › General › Image Interpolation (the dropdown itself goes - // away with #14462). The *not measured* variants show and act as Bicubic, as the - // Free Transform options bar renders them. - use photocraft_engine::prefs::Interpolation; - let interp = match app.session.prefs().general.image_interpolation { - Interpolation::Nearest => "nearest", - Interpolation::Bilinear => "bilinear", - _ => "bicubic", - }; - map.insert("interpolation".into(), json!(interp)); + // #14465: the reference dialog offers no interpolation choice, and the dialog has no row + // for it (#14462): it sends none, so the command resamples as Preferences › General › + // Image Interpolation says on every run. } if command == "type.warpText" { warp_defaults(app, &mut map); @@ -543,6 +537,12 @@ pub(crate) fn title_of(label: &str) -> Label { Label::from(crate::i18n::t(label).trim_end_matches('…').to_string()) } +/// The title of `command`'s dialog: [`title_of`] its label, or the dialog's own name where the reference application +/// gives it one (Arbitrary opens "Rotate Canvas", #14462). +fn dialog_title(command: &str, label: &str) -> Label { + if command == super::rotate_canvas_ui::COMMAND { super::rotate_canvas_ui::title() } else { title_of(label) } +} + /// The build closure of a command dialog over its values, over the active document's canvas: its droppers, the Blur /// Gallery's pins and the preview pane's locator take presses there. fn builder( @@ -551,6 +551,7 @@ fn builder( title: Label, params: Vec, reset: DialogFields, + preview: bool, ) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static { let key = command.to_owned(); let canvas = app.session.active_index().map(|idx| crate::canvas::document_display::CanvasHost::primary(app, idx).canvas_id()); @@ -559,7 +560,9 @@ fn builder( .values(Bind::bound(fields)) .reset_to(reset.clone()) .layout(ParamLayout::Stacked) - .previews(previews(&key)) + .previews(preview) + // Alt keeps Rotate Canvas's Cancel a Cancel, as in the reference application (#14462). + .alt_resets(key != super::rotate_canvas_ui::COMMAND) .alert_title(tl!("PhotoCraft")); if let Some(canvas) = canvas { dialog = dialog.canvas(canvas); @@ -575,6 +578,17 @@ fn builder( /// Opens `command`'s schema dialog using the current settings and editing target. The dialog's key /// is the command; Match Color captures its destination document and layer. pub fn open(app: &mut PhotocraftApp, command: &str) -> Result { + open_as(app, command, previews(command)) +} + +/// [`open`] with the Preview box whether or not `command`'s dialog has one. Rotate Canvas has none (#14462), but the +/// canvas still places a preview that changes the document's size (#1436); its tests reach that path through here. +#[doc(hidden)] +pub fn open_previewing(app: &mut PhotocraftApp, command: &str) -> Result { + open_as(app, command, true) +} + +fn open_as(app: &mut PhotocraftApp, command: &str, preview: bool) -> Result { let spec = photocraft_engine::commands::find(command).ok_or_else(|| format!("{command} has no dialog"))?; let params = params(app, command, spec.params); let fields = fields(app, command, ¶ms); @@ -588,8 +602,8 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Result }; let reset = reset_values(¶ms, &fields); // Photoshop titles the Scale Effects… dialog with the longer name (#14996). - let title = if command == SCALE_EFFECTS { Label::from(tl!("Scale Layer Effects")) } else { title_of(spec.label) }; - let build = builder(app, command, title, params, reset); + let title = if command == SCALE_EFFECTS { Label::from(tl!("Scale Layer Effects")) } else { dialog_title(command, spec.label) }; + let build = builder(app, command, title, params, reset, preview); let id = crate::dialogs::params::open_param(app, command, fields, captured, build); if command == MATCH_COLOR { reconcile_match_color(app); @@ -609,7 +623,7 @@ pub fn open_with_spec(app: &mut PhotocraftApp, command: &str, label: &str, spec: fields.set("target", FieldValue::Json(target)); } let reset = reset_values(¶ms, &fields); - let build = builder(app, command, title_of(label), params, reset); + let build = builder(app, command, title_of(label), params, reset, previews(command)); // PLAN: assumed `open_param_unsaved(app, key, fields, captured, build) -> DialogId` (dialogs-w19): `open_param` without the remember key. crate::dialogs::params::open_param_unsaved(app, command, fields, Value::Null, build) } @@ -624,7 +638,7 @@ pub fn open_smart_edit(app: &mut PhotocraftApp, command: &str, recorded: &Map Value { if command == crate::dialogs::image_processor_ui::COMMAND { crate::dialogs::image_processor_ui::nest(&mut map); } + if command == super::rotate_canvas_ui::COMMAND { + super::rotate_canvas_ui::command_params(&mut map); + } params_of(&map) } diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 99f4179f15..4284dec547 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -218,33 +218,26 @@ fn remembering_dialogs_never_persists_paths_or_document_indices() { assert_ne!(f.int("mapDocument"), Some(0), "a document index is never remembered"); } -/// #14465 review: the Rotate Canvas dialog fills Interpolation from Preferences › General › -/// Image Interpolation on every opening, so a dropdown pick applies to that opening only and -/// never carries into the next one. The reference application has no Interpolation row at all: -/// the preference decides. The other rows of the dialog keep opening from the document -/// (angle and direction are the ruler's, #12035). +/// #14465 review: the Rotate Canvas dialog's resampling follows Preferences › General › Image +/// Interpolation on every run. The reference application has no Interpolation row (#14462), so +/// the dialog files no interpolation, before or after an OK, and the command reads the +/// preference (`rotate_canvas_interpolation_pref_tests` in the engine). The other rows of the +/// dialog keep opening from the document (angle and direction are the ruler's, #12035). #[test] fn arbitrary_rotation_interpolation_reopens_at_the_preference() { const CMD: &str = "image.rotation.arbitrary"; let mut app = new_app(); app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - // 1. The preference's default (Bicubic Automatic) opens the row at bicubic. let id = open(&mut app, CMD).unwrap(); - assert_eq!(field_json(&app, id, "interpolation"), json!("bicubic"), "the row opens at the preference"); + assert_eq!(field_json(&app, id, "interpolation"), Value::Null, "no interpolation value: the preference decides"); set(&mut app, id, "angle", json!(30.0)); - set(&mut app, id, "interpolation", json!("bilinear")); assert!(ok(&mut app, id), "OK rotates and files its values"); - // 2. A later opening starts from the preference again, not from the confirmed Bilinear pick. - let id = open(&mut app, CMD).unwrap(); - assert_eq!(field_json(&app, id, "interpolation"), json!("bicubic"), "a one-time Bilinear pick does not carry into the next opening"); - cancel(&mut app, id); - - // 3. A changed preference reaches the next opening. + // A later opening files none either, whatever the preference says. app.session.edit_prefs(|p| p.general.image_interpolation = photocraft_engine::prefs::Interpolation::Nearest); let id = open(&mut app, CMD).unwrap(); - assert_eq!(field_json(&app, id, "interpolation"), json!("nearest"), "Nearest Neighbor shows nearest"); + assert_eq!(field_json(&app, id, "interpolation"), Value::Null, "a reopened dialog files no interpolation"); cancel(&mut app, id); } diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index b2795605ac..de856173ae 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -611,13 +611,13 @@ fn gradient_presets(app: &PhotocraftApp) -> Vec<(String, GradientStops)> { #[derive(craft::ui::contract::MemoProps)] struct StylePresets { groups: Vec<(String, Vec)>, - library: Tracked, + library: std::sync::Arc>, } /// The Styles page's presets. -fn style_presets(app: &PhotocraftApp) -> PresetSource<'static, String> { +fn style_presets(app: &mut PhotocraftApp) -> PresetSource<'static, String> { let groups = app.session.presets.styles.iter().map(|group| (group.name.clone(), group.items.iter().map(|st| st.name.clone()).collect())).collect(); - let inputs = StylePresets { groups, library: StyleLibrary::of(&app.session) }; + let inputs = StylePresets { groups, library: StyleLibrary::held(app) }; PresetSource::new(inputs, PresetFns::new(style_rows).thumb(style_thumb)) } diff --git a/crates/ui-egui/src/dialogs/rotate_canvas_layout_tests.rs b/crates/ui-egui/src/dialogs/rotate_canvas_layout_tests.rs new file mode 100644 index 0000000000..22bb018ddb --- /dev/null +++ b/crates/ui-egui/src/dialogs/rotate_canvas_layout_tests.rs @@ -0,0 +1,219 @@ +//! #14462: Image › Image Rotation › Arbitrary opens the reference application's Rotate Canvas +//! dialog: titled "Rotate Canvas", one row with the Angle field (`°`, two decimals) behind a +//! scrubby label, then the Clockwise and Counter clockwise radios, OK and Cancel. No slider, no +//! Interpolation control, no Preview, and Alt does not turn Cancel into Reset. The command and its +//! params stay as they are. + +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; +use egui::accesskit::Role; +use egui::{Event, Key, Modifiers, PointerButton, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use super::rotate_canvas_ui::COMMAND; +use crate::PhotocraftApp; +use crate::new_layer_ui::testing::{fields, set, top}; + +type H = Harness<'static, Box>; + +/// The whole app on a 64x32 document with the dialog opened through the menu, drawn a few frames. +fn dialog() -> (H, DialogId) { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + app + }); + h.run_steps(3); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + let id = top(h.state()); + h.run_steps(4); + (h, id) +} + +fn field(h: &H, id: DialogId, key: &str) -> Option { + fields(h.state(), id).get(key).cloned() +} + +fn angle(h: &H, id: DialogId) -> Option { + fields(h.state(), id).number("angle") +} + +fn direction(h: &H, id: DialogId) -> Option { + fields(h.state(), id).text("direction").map(str::to_owned) +} + +fn set_angle(h: &mut H, id: DialogId, v: f64) { + set(h.state_mut(), id, "angle", json!(v)).unwrap(); + h.run_steps(2); +} + +/// The dialog window's rectangle: the area that draws its OK button. +fn dialog_rect(h: &H) -> egui::Rect { + let ok = h.get_by_role_and_label(Role::Button, "OK").rect(); + h.ctx.layer_id_at(ok.center()).and_then(|layer| h.ctx.memory(|m| m.area_rect(layer.id))).expect("the dialog's window") +} + +/// Drags the Angle label `dx` points to the right (left when negative), in small moves. +fn scrub(h: &mut H, dx: f32) { + let label = h.get_by_role_and_label(Role::Label, "Angle").rect(); + let from = label.center(); + h.event(Event::PointerMoved(from)); + h.run_steps(1); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + let steps = 10; + for k in 1..=steps { + h.event(Event::PointerMoved(from + vec2(dx * k as f32 / steps as f32, 0.0))); + h.run_steps(1); + } + let to = from + vec2(dx, 0.0); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn the_dialog_is_titled_rotate_canvas() { + let (h, _) = dialog(); + assert!(h.query_all_by_label("Rotate Canvas").next().is_some(), "the window shows the title"); + assert!(h.query_by_label("Arbitrary").is_none(), "the old title is gone"); +} + +#[test] +fn the_controls_are_the_angle_field_two_radios_ok_and_cancel() { + let (h, id) = dialog(); + let angle = h.get_by_role_and_label(Role::SpinButton, "Angle").rect(); + let cw = h.get_by_role_and_label(Role::RadioButton, "Clockwise").rect(); + let ccw = h.get_by_role_and_label(Role::RadioButton, "Counter clockwise").rect(); + // One row, left to right. + for r in [cw, ccw] { + assert!((r.center().y - angle.center().y).abs() < 6.0, "the radios share the Angle row: {r:?} vs {angle:?}"); + } + assert!(angle.right() <= cw.left() && cw.right() <= ccw.left(), "Angle, Clockwise, Counter clockwise in order"); + h.get_by_role_and_label(Role::Button, "OK"); + h.get_by_role_and_label(Role::Button, "Cancel"); + let window = dialog_rect(&h); + assert!(h.query_all_by_role(Role::Slider).all(|s| !window.intersects(s.rect())), "no slider in the dialog"); + assert!(h.query_by_label("Interpolation").is_none(), "no Interpolation control"); + assert!(h.query_by_label("Preview").is_none(), "no Preview checkbox"); + assert_eq!(field(&h, id, "interpolation"), None, "the dialog sends no interpolation"); + assert!(!crate::filter_dialog::PREVIEWED.contains(&COMMAND)); + assert!(crate::filter_dialog::has_dialog(COMMAND), "the menu still opens the dialog"); + // The command keeps its param for scripts and recorded actions. + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + assert!(craft::ui::patterns::form_dialogs::Param::parse_list(spec.params).iter().any(|p| p.key == "interpolation")); +} + +#[test] +fn the_radios_set_cw_and_ccw_and_ok_runs_them() { + let (mut h, id) = dialog(); + assert_eq!(direction(&h, id).as_deref(), Some("cw"), "a fresh dialog is Clockwise"); + h.get_by_role_and_label(Role::RadioButton, "Counter clockwise").click(); + h.run_steps(2); + assert_eq!(direction(&h, id).as_deref(), Some("ccw")); + h.get_by_role_and_label(Role::RadioButton, "Clockwise").click(); + h.run_steps(2); + assert_eq!(direction(&h, id).as_deref(), Some("cw")); + h.get_by_role_and_label(Role::RadioButton, "Counter clockwise").click(); + h.run_steps(2); + set_angle(&mut h, id, 90.0); + let params = crate::filter_dialog::command_params(COMMAND, fields(h.state(), id)); + assert_eq!(params, json!({"angle": 90.0, "direction": "ccw"}), "OK sends the angle and the radio's direction"); + crate::dialogs::testing::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + assert_eq!((st.doc.size.width, st.doc.size.height), (32, 64), "90° Counter clockwise turns 64x32 upright"); +} + +/// The Angle label scrubs the angle: right raises it, left lowers it, and it keeps its hundredths. +#[test] +fn a_scrub_of_the_angle_label_moves_the_angle() { + let (mut h, id) = dialog(); + set_angle(&mut h, id, 30.0); + scrub(&mut h, 50.0); + let right = angle(&h, id).unwrap(); + assert!(right > 30.0, "dragging right raises it: {right}"); + scrub(&mut h, -20.0); + let left = angle(&h, id).unwrap(); + assert!(left < right, "dragging left lowers it: {left}"); + assert_eq!((left * 100.0).round() / 100.0, left, "two decimals at most"); +} + +/// The reference application moves the angle 1° a point of drag on its label (30° and 50 px give 80°), while the arrow +/// keys move it by hundredths. The framework's number field scrubs by its key step, so this waits for a scrub step of +/// its own in craft's `NumberField`. +#[test] +#[ignore = "needs a scrub step apart from the arrow-key step in craft's NumberField"] +fn a_50_point_scrub_of_the_angle_label_turns_30_into_80() { + let (mut h, id) = dialog(); + set_angle(&mut h, id, 30.0); + scrub(&mut h, 50.0); + assert_eq!(angle(&h, id), Some(80.0)); + scrub(&mut h, -20.0); + assert_eq!(angle(&h, id), Some(60.0), "dragging left lowers it"); +} + +#[test] +fn a_set_angle_keeps_the_hundredths_and_stops_at_359_99() { + let (mut h, id) = dialog(); + set_angle(&mut h, id, 33.69); + assert_eq!(crate::filter_dialog::command_params(COMMAND, fields(h.state(), id))["angle"], json!(33.69)); + // An agent's value reaches the row's key unchecked; OK sends it in the field's range at two decimals. + for (set_to, sent) in [(400.0, 359.99), (-400.0, -359.99), (12.3456, 12.35)] { + set_angle(&mut h, id, set_to); + assert_eq!(crate::filter_dialog::command_params(COMMAND, fields(h.state(), id))["angle"], json!(sent), "{set_to}"); + } +} + +#[test] +fn the_arrow_keys_step_hundredths_and_tenths() { + let (mut h, id) = dialog(); + set_angle(&mut h, id, 30.0); + h.get_by_role_and_label(Role::SpinButton, "Angle").click(); + h.run_steps(3); + h.key_press(Key::ArrowUp); + h.run_steps(3); + assert_eq!(angle(&h, id), Some(30.01)); + h.key_press(Key::ArrowUp); + h.run_steps(3); + assert_eq!(angle(&h, id), Some(30.02), "a second press"); + // Shift moves a tenth, onto the tenths (the framework's large step lands on its grid). + set_angle(&mut h, id, 30.1); + h.get_by_role_and_label(Role::SpinButton, "Angle").click(); + h.run_steps(3); + h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowUp); + h.run_steps(3); + assert_eq!(angle(&h, id), Some(30.2)); +} + +#[test] +fn alt_keeps_cancel_and_escape_cancels() { + let (mut h, id) = dialog(); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(h.query_by_label("Reset").is_none(), "Alt does not turn Cancel into Reset"); + h.get_by_role_and_label(Role::Button, "Cancel"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); + let revision = h.state().session.active().unwrap().revision; + h.key_press(Key::Escape); + h.run_steps(3); + assert!(h.state().framework.dialogs.open_dialogs().iter().all(|d| d.id != id), "Escape closes the dialog"); + assert_eq!(h.state().session.active().unwrap().revision, revision, "and changes nothing"); +} + +/// The dialog has no Interpolation row, but values that carry one (a recorded step shown again) still send it. +#[test] +fn a_recorded_interpolation_still_runs() { + let mut f = DialogFields::new(); + f.set("angle", FieldValue::Number(12.5)); + f.set("direction", FieldValue::Text("ccw".into())); + f.set("interpolation", FieldValue::Json(json!("nearest"))); + let params = crate::filter_dialog::command_params(COMMAND, &f); + assert_eq!(params, json!({"angle": 12.5, "direction": "ccw", "interpolation": "nearest"})); + assert_eq!(params.get("__preview"), None::<&Value>); +} diff --git a/crates/ui-egui/src/dialogs/rotate_canvas_ui.rs b/crates/ui-egui/src/dialogs/rotate_canvas_ui.rs new file mode 100644 index 0000000000..696cc2e49b --- /dev/null +++ b/crates/ui-egui/src/dialogs/rotate_canvas_ui.rs @@ -0,0 +1,114 @@ +//! Image › Image Rotation › Arbitrary: the reference application's Rotate Canvas dialog (#14462). +//! One row: the Angle field (`°`, two decimals) behind a scrubby label, then the Clockwise and +//! Counter clockwise radios. No slider, no interpolation choice, no preview, and Alt does not turn +//! Cancel into Reset. +//! +//! It stays the command's schema dialog (`filter_dialog::open`), so the ruler pre-fill, Enter / +//! Escape and `ui.dialog.*` work as for every other command dialog; only its rows, title and +//! buttons differ. The command's `interpolation` param stays for scripts and recorded actions: the +//! dialog just has no row for it, so the command's own default applies. + +use craft::behavior::NumberCodec; +use craft::ui::choice::{Radio, RadioGroup}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; +use craft::ui::runtime::env::{Env, Label}; +use craft::ui::text::NumberField; +use serde_json::{Map, Value, json}; + +pub const COMMAND: &str = "image.rotation.arbitrary"; +/// The dialog's title, as the reference application names it. +pub fn title() -> Label { + Label::from(tl!("Rotate Canvas").to_string()) +} +/// The Angle field's shown decimals: hundredths of a degree (#12035). +pub const DECIMALS: u32 = 2; +/// What an arrow press moves the angle by: its last shown decimal (Shift moves ten of them). +const STEP: f64 = 0.01; +/// The field's range, should the command's schema ever lose it. +const RANGE: (f64, f64) = (-359.99, 359.99); + +/// The Angle field's range, from the command's schema. +pub fn angle_range() -> (f64, f64) { + photocraft_engine::commands::find(COMMAND) + .into_iter() + .flat_map(|c| Param::parse_list(c.params)) + .find_map(|p| match p.kind { + ParamKind::Range { min, max, .. } if p.key == "angle" && min <= max => Some((min, max)), + _ => None, + }) + .unwrap_or(RANGE) +} + +/// `angle` kept in the field's range at its two decimals; a non-finite one is 0. +pub fn settle(angle: f64) -> f64 { + let (min, max) = angle_range(); + if !angle.is_finite() { + return 0.0; + } + let scale = 10f64.powi(DECIMALS as i32); + ((angle.clamp(min, max)) * scale).round() / scale +} + +/// The dialog's one row, in place of the schema's Angle, Direction and Interpolation rows: the row +/// keeps `angle` and its companion `direction`. +pub(crate) fn params() -> Vec { + vec![Param::custom("angle", Label::Empty, |ui, fields, _| row(ui, fields)).companions(["direction"]).opens_with(FieldValue::Number(0.0)).full_width()] +} + +/// The values the dialog opens with besides the ruler pre-fill: Clockwise, as on a fresh dialog. +pub(crate) fn open_values(fields: &mut DialogFields) { + if !fields.contains("angle") { + fields.set("angle", FieldValue::Number(0.0)); + } + if fields.text("direction").is_none() { + fields.set("direction", FieldValue::Text("cw".into())); + } +} + +/// The command params of the dialog's values: the angle kept in the field's range at two decimals +/// (an agent's `ui.dialog.set` reaches the row's key unchecked), the direction as chosen. +pub(crate) fn command_params(map: &mut Map) { + if let Some(angle) = map.get("angle").and_then(Value::as_f64) { + map.insert("angle".into(), json!(settle(angle))); + } +} + +fn row(ui: &mut egui::Ui, fields: &mut DialogFields) -> egui::Response { + let (min, max) = angle_range(); + let angle = settle(fields.number("angle").unwrap_or(0.0)); + let cw = fields.text("direction") != Some("ccw"); + let caption = Label::from(tl!("Angle").to_string()); + Row::new() + .show(ui, |ui, _| { + Field::new(caption.clone()).side(SideLabel::new().scrub(true)).id_salt("angle").sizing(Sizing::Content).show(ui, |ui, _| { + let codec = NumberCodec::new(Env::of(ui).units().reader(None), DECIMALS as usize); + let field = NumberField::new(caption.clone(), Bind::given(Some(angle))) + .range(min..=max) + .step(STEP) + .codec(codec) + .commit_decimals(DECIMALS as usize) + .unit("°") + // The reference application scrubs 1° a point of drag; craft's NumberField scrubs by its key step + // (0.01 here) until it takes a scrub step of its own. + .scrub_by_label() + .show(ui); + if let Some(next) = field.value().copied().flatten() { + fields.set("angle", FieldValue::Number(settle(next))); + } + }); + let direction = if cw { "cw" } else { "ccw" }.to_owned(); + let group = RadioGroup::new(tl!("Direction").to_owned(), Bind::given(direction)).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Radio::new("cw".to_owned()).label(tl!("Clockwise").to_owned()).show(ui); + Radio::new("ccw".to_owned()).label(tl!("Counter clockwise").to_owned()).show(ui); + }); + }); + if let Some(picked) = group.output.value().cloned() { + fields.set("direction", FieldValue::Text(picked)); + } + }) + .output +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5f849c8e9d..b95d040ebe 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -360,6 +360,8 @@ pub struct PhotocraftApp { pub(crate) toolbar_slots: panels::tool_commands::ToolbarSlots, /// The dock's spec model and kept panels (`panel_docking::DockModel`). pub(crate) dock_model: panels::panel_docking::DockModel, + /// The patterns and styles the preset views draw from, held while unchanged (`preset_browser::PresetArt`). + pub(crate) preset_art: panels::preset_browser::PresetArt, /// Move tool drag shown live (`move_ui`). pub(crate) move_preview: Option, /// Move tool › Show Highlight on Rollover: the last hover answer (`move_hover`). diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 78975d8024..d78c2facc8 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -6,7 +6,7 @@ use craft::color_ui::ui::gradient::GradientRamp; use craft::keymap::CommandRef; use craft::theme::Srgba; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, DropZone, MemoProps, PlainData, Props as _, Show as _, Tracked}; +use craft::ui::contract::{Bind, DropZone, MemoProps, PlainData, Props as _, Revision, Show as _, Tracked}; use craft::ui::list::ThumbAspect; use craft::ui::menu::PanelRow; use craft::ui::patterns::presets::{ @@ -20,9 +20,12 @@ use craft::ui::runtime::env::Env; use craft::ui::tile_grid::TileZoom; use egui::{Color32, ColorImage, Pos2, Rect, TextureId, pos2}; use photocraft_engine::pattern_cmds::PatternLibrary; +use photocraft_engine::presets::shapes::ShapePreset; use photocraft_engine::presets::styles::StylePreset; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use std::hash::{DefaultHasher, Hash as _, Hasher as _}; +use std::sync::Arc; use super::preset_panels::{PresetUi, run, tool_presets}; use crate::PhotocraftApp; @@ -101,13 +104,82 @@ fn panel_source(inputs: PanelInputs, thumb: Th PresetSource::new(inputs, PresetFns::new(panel_rows).thumb(thumb)) } -/// A thumbnail held in the framework's texture store: the preset's key and name, and the texture. +/// What a swatch's picture is drawn from. +#[derive(Clone)] +enum Art { + Pattern(Arc), + Shape(Arc), +} + +/// A swatch picture's key in the framework's texture store: its kind, the preset's id or name, and the pattern's pixel +/// generation or the shape's path size. +type PictureKey = (&'static str, String, u64); + +/// A thumbnail in the framework's texture store: the preset's key and name, the picture's key in the store and what +/// the picture is drawn from. The texture is asked for when the swatch paints, so only the swatches a browser shows +/// load a picture, and one the store dropped (it holds `TextureCache::CAPACITY` textures) loads again. #[derive(Clone, MemoProps)] pub(crate) struct Swatch { key: String, name: String, - #[memo_props(hash = "a texture handle: the texture store keeps one picture under it")] - texture: TextureId, + #[memo_props(hash = "a texture store key: a kind, the preset's id or name and a number for what its picture shows")] + picture: PictureKey, + #[memo_props(covered_by = "picture", reason = "the picture is drawn from this art, and `picture` names what the drawing shows")] + art: Art, +} + +impl Swatch { + /// The swatch's texture in `ctx`'s store, drawn on a miss. + fn texture(&self, ctx: &egui::Context) -> TextureId { + match &self.art { + Art::Pattern(pattern) => TextureCache::texture(ctx, self.picture.clone(), || pattern_image(pattern)), + Art::Shape(shape) => TextureCache::texture(ctx, self.picture.clone(), || shape_image(shape)), + } + } + + /// Paints the swatch's picture into `rect`. + fn paint(&self, cx: &ContentPainterCx, rect: Rect) { + paint_texture(cx, rect, self.texture(cx.painter.ctx())); + } +} + +/// The patterns and styles the preset views draw from, held while the library and the presets are unchanged, so a +/// view's inputs keep their memo keys between passes instead of being copied and keyed anew in each. +#[derive(Default)] +pub(crate) struct PresetArt { + /// The library's patterns, with the [`patterns_stamp`] they were taken at. + patterns: Option<(u64, HeldPatterns)>, + /// The style library, with the presets' revision and the [`patterns_stamp`] it was taken at. + styles: Option<(StylesStamp, Arc>)>, +} + +/// The library's patterns as the preset views share them. +type HeldPatterns = Arc<[Arc]>; + +/// What a held style library was taken at: the presets' revision and the [`patterns_stamp`]. +type StylesStamp = (Revision, u64); + +/// A number for the library's patterns and their pixels: equal stamps mean the same patterns with the same pixels +/// (`Surface::generation` names a pixel state, and is shared by clones). +fn patterns_stamp(library: &PatternLibrary) -> u64 { + let mut hasher = DefaultHasher::new(); + for pattern in &library.items { + (&pattern.id, &pattern.name, pattern.surface.generation()).hash(&mut hasher); + } + hasher.finish() +} + +/// The library's patterns as the preset views draw them: the held ones while the library is unchanged. +fn held_patterns(app: &mut PhotocraftApp) -> HeldPatterns { + let stamp = patterns_stamp(&app.session.patterns); + if let Some((held, patterns)) = &app.preset_art.patterns + && *held == stamp + { + return Arc::clone(patterns); + } + let patterns: HeldPatterns = app.session.patterns.items.iter().cloned().map(Arc::new).collect(); + app.preset_art.patterns = Some((stamp, Arc::clone(&patterns))); + patterns } /// The swatch of `key` among `swatches`. @@ -229,14 +301,20 @@ fn pattern_image(pattern: &photocraft_doc::Pattern) -> ColorImage { image } +/// The texture store key of `pattern`'s swatch: its id and its pixels, so a pattern replaced under the same id draws +/// anew. +fn pattern_key(pattern: &photocraft_doc::Pattern) -> PictureKey { + ("pattern", pattern.id.clone(), pattern.surface.generation()) +} + /// The cached texture of `pattern`'s swatch. pub(crate) fn pattern_texture(ctx: &egui::Context, pattern: &photocraft_doc::Pattern) -> egui::TextureId { - TextureCache::texture(ctx, ("pattern", pattern.id.clone()), || pattern_image(pattern)) + TextureCache::texture(ctx, pattern_key(pattern), || pattern_image(pattern)) } /// The swatch of `pattern`, keyed by its id and named by its display name. -fn pattern_swatch(ctx: &egui::Context, pattern: &photocraft_doc::Pattern) -> Swatch { - Swatch { key: pattern.id.clone(), name: pattern.display_name().to_string(), texture: pattern_texture(ctx, pattern) } +fn pattern_swatch(pattern: &Arc) -> Swatch { + Swatch { key: pattern.id.clone(), name: pattern.display_name().to_string(), picture: pattern_key(pattern), art: Art::Pattern(Arc::clone(pattern)) } } /// Paints the whole of `texture` into `rect`. @@ -249,7 +327,7 @@ fn swatch_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: if let PresetKey::Item(key) = info.key && let Some(swatch) = swatch_of(&inputs.thumbs, key) { - paint_texture(cx, rect, swatch.texture); + swatch.paint(cx, rect); } } @@ -303,7 +381,7 @@ pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if app.services.preset_store.is_none() { photocraft_engine::presets::patterns::sync(&mut app.session); } - let library = &app.session.patterns.items; + let library = held_patterns(app); let folders: Vec = app .session .presets @@ -320,12 +398,8 @@ pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }) .collect(); let names = names_of(&folders); - let swatches: Vec = folders - .iter() - .flat_map(|folder| &folder.items) - .filter_map(|(id, _)| library.iter().find(|pattern| &pattern.id == id)) - .map(|pattern| pattern_swatch(ui.ctx(), pattern)) - .collect(); + let swatches: Vec = + folders.iter().flat_map(|folder| &folder.items).filter_map(|(id, _)| library.iter().find(|pattern| &pattern.id == id)).map(pattern_swatch).collect(); let source = panel_source(PanelInputs::new(&app.ui.presets_ui, PATTERNS, folders, swatches), swatch_thumb); let zone = canvas_zone(app); let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, PATTERNS, &source, Look::default()); @@ -344,29 +418,49 @@ pub(crate) fn style_image(session: &photocraft_engine::Session, preset: &photocr ColorImage::from_rgba_unmultiplied([S as usize, S as usize], &px) } -/// What the style thumbnails draw from: every style and the patterns their effects use, as the app holds them when the -/// thumbnails' presets are built. +/// What the style thumbnails draw from: every style with its picture's key, and the patterns their effects use, as the +/// app holds them when the thumbnails' presets are built. #[derive(PlainData)] pub(crate) struct StyleLibrary { + /// Each style and the number its picture is keyed by in the texture store ([`style_stamp`]). #[plain_data(assume = "engine presets: owned values with no interior mutability")] - styles: Vec, + styles: Vec<(u64, StylePreset)>, #[plain_data(assume = "the engine's pattern library: owned patterns with no interior mutability")] patterns: PatternLibrary, } +/// The texture store key of `style`'s picture: everything the style holds and the pixels of the patterns its effects +/// may draw (`patterns`, a [`patterns_stamp`]), so a style or pattern edit under the same name draws anew. +fn style_stamp(style: &StylePreset, patterns: u64) -> u64 { + let mut hasher = DefaultHasher::new(); + format!("{style:?}").hash(&mut hasher); + patterns.hash(&mut hasher); + hasher.finish() +} + impl StyleLibrary { - /// The app's styles and patterns now. - pub(crate) fn of(session: &photocraft_engine::Session) -> Tracked { - let styles = session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect(); - Tracked::new(StyleLibrary { styles, patterns: session.patterns.clone() }) + /// The app's styles and patterns now: the held library while the presets and the patterns are unchanged, so the + /// views keyed by it settle. + pub(crate) fn held(app: &mut PhotocraftApp) -> Arc> { + let patterns = patterns_stamp(&app.session.patterns); + let stamp = (app.session.presets.revision(), patterns); + if let Some((held, library)) = &app.preset_art.styles + && *held == stamp + { + return Arc::clone(library); + } + let styles = + app.session.presets.styles.iter().flat_map(|group| group.items.iter()).map(|style| (style_stamp(style, patterns), style.clone())).collect(); + let library = Arc::new(Tracked::new(StyleLibrary { styles, patterns: app.session.patterns.clone() })); + app.preset_art.styles = Some((stamp, Arc::clone(&library))); + library } /// Paints the thumbnail of the style `name`. A picture is rendered on a texture miss only, under one key for /// every place that shows the style, so they share the textures. pub(crate) fn paint(&self, cx: &ContentPainterCx, rect: Rect, name: &str) { - let Some(style) = self.styles.iter().find(|style| style.name == name) else { return }; - let key = ("style", style.name.clone(), style.effects.len(), format!("{:?}{:?}", style.blend, style.fill_opacity)); - picture(cx, rect, key, || { + let Some((stamp, style)) = self.styles.iter().find(|(_, style)| style.name == name) else { return }; + picture(cx, rect, ("style", *stamp), || { let mut scratch = photocraft_engine::Session::new(); scratch.patterns = self.patterns.clone(); style_image(&scratch, style) @@ -375,7 +469,7 @@ impl StyleLibrary { } /// A Styles panel thumbnail. -fn style_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { +fn style_thumb(inputs: &PanelInputs>>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { if let PresetKey::Item(name) = info.key { inputs.thumbs.paint(cx, rect, name); } @@ -386,7 +480,8 @@ fn style_thumb(inputs: &PanelInputs>, cx: &ContentPainterC pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let folders = style_folders(app); let names = names_of(&folders); - let source = panel_source(PanelInputs::new(&app.ui.presets_ui, STYLES, folders, StyleLibrary::of(&app.session)), style_thumb); + let library = StyleLibrary::held(app); + let source = panel_source(PanelInputs::new(&app.ui.presets_ui, STYLES, folders, library), style_thumb); let zone = canvas_zone(app); let look = Look { room_height: Some(STYLES_HEIGHT), ..Look::default() }; let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, STYLES, &source, look); @@ -545,17 +640,14 @@ pub(crate) fn shape_image(shape: &photocraft_engine::presets::shapes::ShapePrese } /// The texture cache key of a shape's raster: its name and size of path. -fn shape_key(shape: &photocraft_engine::presets::shapes::ShapePreset) -> (&'static str, String, usize) { - ("shape", shape.name.clone(), shape.path.subpaths.iter().map(|s| s.knots.len()).sum()) -} - -fn shape_texture(ctx: &egui::Context, shape: &photocraft_engine::presets::shapes::ShapePreset) -> egui::TextureId { - TextureCache::texture(ctx, shape_key(shape), || shape_image(shape)) +fn shape_key(shape: &ShapePreset) -> PictureKey { + let knots: usize = shape.path.subpaths.iter().map(|s| s.knots.len()).sum(); + ("shape", shape.name.clone(), u64::try_from(knots).unwrap_or(u64::MAX)) } /// The swatch of `shape`, keyed and named by its name. -fn shape_swatch(ctx: &egui::Context, shape: &photocraft_engine::presets::shapes::ShapePreset) -> Swatch { - Swatch { key: shape.name.clone(), name: shape.name.clone(), texture: shape_texture(ctx, shape) } +fn shape_swatch(shape: ShapePreset) -> Swatch { + Swatch { key: shape.name.clone(), name: shape.name.clone(), picture: shape_key(&shape), art: Art::Shape(Arc::new(shape)) } } /// A Shapes panel thumbnail: the shape's raster, inset from the tile's edge. @@ -563,7 +655,7 @@ fn shape_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: R if let PresetKey::Item(key) = info.key && let Some(swatch) = swatch_of(&inputs.thumbs, key) { - paint_texture(cx, rect.shrink(2.0), swatch.texture); + swatch.paint(cx, rect.shrink(2.0)); } } @@ -576,7 +668,7 @@ pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { .map(|group| Folder { name: group.name.clone(), items: group.items.iter().map(|shape| (shape.name.clone(), shape.name.clone())).collect() }) .collect(); let names = names_of(&folders); - let swatches: Vec = groups.iter().flat_map(|group| &group.items).map(|shape| shape_swatch(ui.ctx(), shape)).collect(); + let swatches: Vec = groups.into_iter().flat_map(|group| group.items).map(shape_swatch).collect(); let source = panel_source(PanelInputs::new(&app.ui.presets_ui, SHAPES, folders, swatches), shape_thumb); let zone = canvas_zone(app); let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, SHAPES, &source, Look::default()); @@ -626,8 +718,8 @@ fn keep_picker_state(presets: &mut PresetUi, id: &str, state: PresetState)> = photocraft_engine::presets::shapes::all_groups(&app.session) - .iter() - .map(|group| (group.name.clone(), group.items.iter().map(|shape| shape_swatch(ui.ctx(), shape)).collect())) + .into_iter() + .map(|group| (group.name, group.items.into_iter().map(shape_swatch).collect())) .collect(); let source = PresetSource::new(groups, PresetFns::new(shape_rows)); let mut value = Some(app.ui.presets_ui.shape().to_string()); @@ -649,9 +741,9 @@ fn shape_rows(groups: &Vec<(String, Vec)>, _: &Env) -> Vec Vec { - app.session.patterns.items.iter().map(|pattern| pattern_swatch(ctx, pattern)).collect() +pub(crate) fn pattern_swatches(app: &mut PhotocraftApp) -> Vec { + held_patterns(app).iter().map(pattern_swatch).collect() } /// The presets of `swatches`: one row per pattern, keyed by its id, with its swatch and its name as the tooltip. @@ -881,10 +973,10 @@ fn swatch_rows(swatches: &[Swatch], _: &Env) -> Vec> { swatches .iter() .map(|swatch| { - let texture = swatch.texture; + let picture = swatch.clone(); PresetRow::item(swatch.key.clone(), swatch.name.clone(), 0) .tooltip(swatch.name.clone()) - .preview(ThumbAspect::SQUARE, move |cx, rect| paint_texture(cx, rect, texture)) + .preview(ThumbAspect::SQUARE, move |cx, rect| picture.paint(cx, rect)) }) .collect() } @@ -893,7 +985,7 @@ fn swatch_rows(swatches: &[Swatch], _: &Env) -> Vec> { /// each named in its tooltip. Returns the id of a newly picked pattern. pub(crate) fn pattern_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: &str) -> Option { const ID: &str = "patternPicker"; - let source = pattern_source(pattern_swatches(app, ui.ctx())); + let source = pattern_source(pattern_swatches(app)); let mut value = Some(selected.to_string()).filter(|id| app.session.patterns.items.iter().any(|pattern| &pattern.id == id)); let before = value.clone(); let mut state = picker_state(&app.ui.presets_ui, ID); diff --git a/crates/ui-egui/src/panels/preset_browser/tests.rs b/crates/ui-egui/src/panels/preset_browser/tests.rs index ff04ff3e0b..ee3c9c6613 100644 --- a/crates/ui-egui/src/panels/preset_browser/tests.rs +++ b/crates/ui-egui/src/panels/preset_browser/tests.rs @@ -1,7 +1,7 @@ use super::*; use craft::behavior::{EditEvent, Mixed}; use craft::keymap::Mods; -use craft::ui::contract::ReorderMove; +use craft::ui::contract::{MemoKey, ReorderMove}; use std::sync::Arc; fn group(name: &str) -> PresetKey { @@ -114,3 +114,118 @@ fn preset_drops_map_through_the_ruler_inset() { let doc = crate::canvas::document_display::doc_point_at(&app, centre).expect("the canvas centre is on the document"); assert!((doc.x - 32.0).abs() < 1.0 && (doc.y - 24.0).abs() < 1.0, "the canvas centre is the document centre: {doc:?}"); } + +/// Runs one egui pass of `ctx` with `f`. +fn pass(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) { + let mut out = ctx.run_ui(egui::RawInput::default(), f); + out.textures_delta.clear(); +} + +/// #16221: a swatch kept past a texture-store eviction (Fill holds its pattern swatches from when it opened) paints +/// a live texture: it asks the store again and the picture loads anew, instead of drawing the freed id it was built +/// with. +#[test] +fn a_swatch_reloads_a_texture_the_store_dropped() { + let ctx = egui::Context::default(); + let pattern = Arc::new(photocraft_engine::pattern_cmds::builtin().remove(0)); + let swatch = pattern_swatch(&pattern); + let mut first = None; + pass(&ctx, |ui| first = Some(swatch.texture(ui.ctx()))); + let first = first.unwrap(); + assert!(ctx.tex_manager().read().meta(first).is_some()); + // Later passes fill the store past its capacity without the swatch, so its texture goes. + pass(&ctx, |ui| { + for i in 0..TextureCache::CAPACITY + 8 { + TextureCache::texture(ui.ctx(), ("filler", i), || ColorImage::new([1, 1], vec![Color32::RED])); + } + }); + assert!(ctx.tex_manager().read().meta(first).is_none(), "the swatch's first texture was dropped"); + let mut again = None; + pass(&ctx, |ui| again = Some(swatch.texture(ui.ctx()))); + assert!(ctx.tex_manager().read().meta(again.unwrap()).is_some(), "the swatch paints a live texture"); +} + +/// #16221: a swatch draws nothing until it paints, so building a browser's swatches loads no textures; only the rows +/// a browser shows load theirs. +#[test] +fn building_swatches_loads_no_texture() { + let ctx = egui::Context::default(); + let patterns: Vec<_> = photocraft_engine::pattern_cmds::builtin().into_iter().map(Arc::new).collect(); + let mut swatches = Vec::new(); + pass(&ctx, |_| swatches = patterns.iter().map(pattern_swatch).collect::>()); + assert_eq!(TextureCache::len(&ctx), 0); + pass(&ctx, |ui| { + let _ = swatches[0].texture(ui.ctx()); + }); + assert_eq!(TextureCache::len(&ctx), 1, "only the painted swatch loads"); +} + +/// #16221: a pattern replaced under the same id (an imported `.pat` whose id is in the library) keys a new picture. +#[test] +fn a_pattern_replaced_under_its_id_keys_a_new_picture() { + let mut patterns = photocraft_engine::pattern_cmds::builtin(); + let first = patterns.remove(0); + let mut replaced = patterns.remove(0); + replaced.id = first.id.clone(); + replaced.name = first.name.clone(); + assert_ne!(pattern_key(&first), pattern_key(&replaced)); + assert_eq!(pattern_key(&first), pattern_key(&first.clone()), "a clone holds the same pixels"); +} + +/// The flat list of the app's style presets. +fn styles(app: &PhotocraftApp) -> Vec { + app.session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect() +} + +/// #16221: a style's picture key covers its effect values and the patterns' pixels: a same-named style with as many +/// effects, the same blend and the same fill opacity but other effect values draws anew, as it does over other +/// pattern pixels. +#[test] +fn a_style_key_covers_its_effect_values_and_the_pattern_pixels() { + let mut app = app(); + for (name, size) in [("Thin", 2), ("Thick", 9)] { + let effects = json!([["stroke", {"size": size, "color": "#123456"}]]); + app.run("style.presets.new", json!({"name": name, "effects": effects, "blend": "Multiply", "fillOpacity": 40})).unwrap(); + } + let all = styles(&app); + let thin = all.iter().find(|style| style.name == "Thin").unwrap().clone(); + let mut thick = all.iter().find(|style| style.name == "Thick").unwrap().clone(); + thick.name = thin.name.clone(); + assert_eq!((thin.effects.len(), thin.blend, thin.fill_opacity), (thick.effects.len(), thick.blend, thick.fill_opacity)); + assert_ne!(style_stamp(&thin, 1), style_stamp(&thick, 1), "other effect values"); + assert_ne!(style_stamp(&thin, 1), style_stamp(&thin, 2), "other pattern pixels"); + assert_eq!(style_stamp(&thin, 1), style_stamp(&thin.clone(), 1)); +} + +/// #16221: the Styles views read one held library while the styles and patterns are unchanged, so their memo keys +/// settle between passes; a style edit or a replaced pattern gives a new one. +#[test] +fn the_style_library_is_held_until_styles_or_patterns_change() { + let mut app = app(); + let first = StyleLibrary::held(&mut app); + let again = StyleLibrary::held(&mut app); + assert!(Arc::ptr_eq(&first, &again)); + assert_eq!(MemoKey::of(&first), MemoKey::of(&again), "an unchanged library keys the same"); + app.run("style.presets.new", json!({"name": "Fresh", "effects": [["stroke", {"size": 3, "color": "#000000"}]]})).unwrap(); + let edited = StyleLibrary::held(&mut app); + assert!(!Arc::ptr_eq(&first, &edited), "a new style"); + assert_ne!(MemoKey::of(&first), MemoKey::of(&edited)); + let mut replacement = app.session.patterns.items[1].clone(); + replacement.id = app.session.patterns.items[0].id.clone(); + app.session.patterns.upsert(replacement); + assert!(!Arc::ptr_eq(&edited, &StyleLibrary::held(&mut app)), "a pattern replaced under its id"); +} + +/// #16221: the preset views share one held copy of the patterns while the library is unchanged. +#[test] +fn the_patterns_are_held_until_the_library_changes() { + let mut app = app(); + let first = held_patterns(&mut app); + assert!(Arc::ptr_eq(&first, &held_patterns(&mut app))); + let mut extra = app.session.patterns.items[0].clone(); + extra.id = "held-test-extra".into(); + app.session.patterns.items.push(extra); + let grown = held_patterns(&mut app); + assert!(!Arc::ptr_eq(&first, &grown)); + assert!(grown.iter().any(|pattern| pattern.id == "held-test-extra")); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_alt_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_alt_tests.rs new file mode 100644 index 0000000000..8e16824519 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_alt_tests.rs @@ -0,0 +1,142 @@ +//! #12709: ⌥ with Add Anchor Point works on a whole subpath, as in the reference application. An +//! ⌥-click on a segment selects the subpath and records nothing; an ⌥-drag on a segment copies the +//! subpath and moves the copy (one step, Drag Path). ⌥ never turns the tool into Delete Anchor Point. +//! The overlay reports these edits (craft-libs#2284); these tests check what PhotoCraft makes of them. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use photocraft_geom::Point; +use serde_json::json; + +use super::add_anchor_lock_tests::click_with_modifiers; +use super::delete_anchor_targeted_path_tests::{select_layer, setup, shape_path, steps}; +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::direct_select::PathRef; +use crate::state::Tool; + +/// The epic's test document: the saved path "Path 1", targeted in the Paths panel, with the closed +/// square A (100,300)-(300,500), the open line B (400,300)→(700,300) and the open S-curve C +/// (400,450)→(700,450). +fn path_one() -> Box { + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + {"closed": false, "knots": [{"anchor": [400, 450], "in": [400, 450], "out": [500, 350]}, {"anchor": [700, 450], "in": [600, 550], "out": [700, 450]}]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn path(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths[0].path.clone() +} + +fn undo_label(app: &PhotocraftApp) -> Option<&str> { + app.session.active().unwrap().history.undo_label() +} + +/// The canvas maps screen points in f32, so a drag lands within a hundredth of a pixel. +fn near(got: Point, want: [f64; 2], what: &str) { + assert!((got.x - want[0]).abs() < 0.01 && (got.y - want[1]).abs() < 0.01, "{what}: got ({}, {}), want {want:?}", got.x, got.y); +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + testing::press(app, from, mods); + testing::move_to(app, [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0], mods); + testing::move_to(app, to, mods); + testing::release(app, to, mods); +} + +#[test] +fn alt_click_on_a_segment_selects_the_whole_subpath_and_adds_nothing() { + let mut app = path_one(); + let (before, n) = (path(&app), steps(&app)); + click_with_modifiers(&mut app, [200.0, 300.0], Modifiers::ALT); + app.sync_views(); + assert_eq!(path(&app), before, "no anchor added"); + assert_eq!(steps(&app), n, "no History step"); + let ds = &app.ui.direct_selection; + assert_eq!(ds.target, Some(PathRef::Saved(0))); + assert_eq!(ds.anchors, vec![[0, 0], [0, 1], [0, 2], [0, 3]], "A's four anchors"); +} + +#[test] +fn alt_drag_on_a_segment_copies_the_subpath_and_moves_the_copy_in_one_drag_path_step() { + let mut app = path_one(); + let (before, n) = (path(&app), steps(&app)); + // C's middle: the S-curve passes (550,450) at t = 0.5. + drag(&mut app, [550.0, 450.0], [550.0, 500.0], Modifiers::ALT); + app.sync_views(); + let p = path(&app); + assert_eq!(p.subpaths.len(), 4, "a fourth subpath"); + assert_eq!(p.subpaths[..3], before.subpaths[..], "A, B and C stay where they were"); + let copy = &p.subpaths[3]; + assert!(!copy.closed); + near(copy.knots[0].anchor, [400.0, 500.0], "the copy's first anchor"); + near(copy.knots[1].anchor, [700.0, 500.0], "the copy's last anchor"); + near(copy.knots[0].out_ctrl, [500.0, 400.0], "handles move with the copy"); + near(copy.knots[1].in_ctrl, [600.0, 600.0], "handles move with the copy"); + assert_eq!(steps(&app), n + 1); + assert_eq!(undo_label(&app), Some("Drag Path")); + assert_eq!(app.ui.direct_selection.anchors, vec![[3, 0], [3, 1]], "the copy is selected"); + assert!(app.session.undo()); + assert_eq!(path(&app), before); +} + +#[test] +fn alt_click_on_an_anchor_deletes_nothing() { + let mut app = path_one(); + let (before, n) = (path(&app), steps(&app)); + click_with_modifiers(&mut app, [100.0, 300.0], Modifiers::ALT); + assert_eq!(path(&app), before); + assert_eq!(steps(&app), n); + assert_ne!(undo_label(&app), Some("Delete Anchor Point")); +} + +#[test] +fn alt_drag_on_an_anchor_or_empty_canvas_edits_nothing() { + // Not measured in the reference: such a drag neither deletes nor copies. + let mut app = path_one(); + let (before, n) = (path(&app), steps(&app)); + drag(&mut app, [100.0, 300.0], [100.0, 350.0], Modifiers::ALT); + drag(&mut app, [200.0, 400.0], [200.0, 450.0], Modifiers::ALT); + assert_eq!((path(&app), steps(&app)), (before, n)); +} + +#[test] +fn delete_anchor_point_with_alt_still_adds_an_anchor() { + let mut app = path_one(); + app.ui.tool = Tool::DeleteAnchorPoint; + let n = steps(&app); + click_with_modifiers(&mut app, [200.0, 300.0], Modifiers::ALT); + assert_eq!(path(&app).subpaths[0].knots.len(), 5); + assert_eq!(steps(&app), n + 1); + assert_eq!(undo_label(&app), Some("Add Anchor Point")); +} + +/// The anchors of subpath `s` of a path in the compact JSON form (`[x, y]` corners or `{"anchor"}`). +fn json_anchors(v: &serde_json::Value, s: usize) -> Vec<[f64; 2]> { + let knots = v["subpaths"][s]["knots"].as_array().cloned().unwrap_or_default(); + knots.iter().map(|k| if k.is_array() { k } else { &k["anchor"] }).map(|a| [a[0].as_f64().unwrap(), a[1].as_f64().unwrap()]).collect() +} + +#[test] +fn alt_drag_copies_a_subpath_of_the_active_shape_layer() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + drag(&mut app, [550.0, 100.0], [550.0, 60.0], Modifiers::ALT); + let after = shape_path(&mut app, shape); + assert_eq!(after["subpaths"].as_array().map(Vec::len), Some(2), "{after}"); + assert_eq!(json_anchors(&after, 0), json_anchors(&before, 0), "the original stays"); + let moved: Vec<[f64; 2]> = json_anchors(&before, 0).into_iter().map(|[x, y]| [x, y - 40.0]).collect(); + assert_eq!(json_anchors(&after, 1).len(), moved.len()); + for (got, want) in json_anchors(&after, 1).into_iter().zip(moved) { + near(Point::new(got[0], got[1]), want, "the copy moved up 40 px"); + } + assert_eq!(steps(&app), n + 1); + assert_eq!(undo_label(&app), Some("Drag Path")); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_drag_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_drag_tests.rs new file mode 100644 index 0000000000..02a7cd88e9 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_drag_tests.rs @@ -0,0 +1,155 @@ +//! #12707: a drag from a segment with Add Anchor Point inserts the anchor and pulls out its +//! handles, as the Pen does: the outgoing handle follows the pointer and the incoming one mirrors +//! it. ⇧ turns the handle to 45°, ⌥ breaks the pair; the add and the drag are one history step, +//! Add Anchor Point. The drag is the overlay's (`PathEdit::PullAnchor`, storytold/craft-libs#2285), +//! mapped in `direct_select/edits.rs` (`add_and_pull`). + +use egui::Modifiers; +use photocraft_doc::Knot; +use photocraft_geom::Point; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::direct_select::PathRef; +use crate::state::Tool; + +/// 600 x 600 with the closed corner square (100,300) (300,300) (300,500) (100,500) as the saved +/// path "Path 1", selected in the Paths panel, and Add Anchor Point picked. +fn square() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 600, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::AddAnchorPoint; + app.ui.extras.snap = false; + let path = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn saved(app: &PhotocraftApp) -> photocraft_doc::vector::Path { + crate::direct_select::path_of(app, &PathRef::Saved(0)).unwrap().into_owned() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +fn undo_label(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.undo_label().map(str::to_owned) +} + +fn down(app: &mut PhotocraftApp, at: [f64; 2]) { + testing::press(app, at, Modifiers::NONE); +} + +fn to(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { + testing::move_to(app, at, mods); +} + +fn up(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { + testing::release(app, at, mods); +} + +/// The knot at `anchor` (within a pixel) on `path`. +fn knot_at(path: &photocraft_doc::vector::Path, anchor: [f64; 2]) -> Knot { + let near = |p: Point| (p.x - anchor[0]).hypot(p.y - anchor[1]) <= 1.0; + *path.subpaths[0].knots.iter().find(|k| near(k.anchor)).unwrap_or_else(|| panic!("no anchor at {anchor:?}: {path:?}")) +} + +#[track_caller] +fn assert_knot(k: &Knot, anchor: [f64; 2], out: [f64; 2], inc: [f64; 2]) { + let near = |p: Point, q: [f64; 2]| (p.x - q[0]).hypot(p.y - q[1]) <= 0.5; + assert!(near(k.anchor, anchor) && near(k.out_ctrl, out) && near(k.in_ctrl, inc), "want anchor {anchor:?} out {out:?} in {inc:?}, got {k:?}"); +} + +#[test] +fn a_drag_from_the_bottom_edge_pulls_out_mirrored_handles_in_one_step() { + let mut app = square(); + let (before, n) = (saved(&app), steps(&app)); + down(&mut app, [200.0, 500.0]); + for y in [520.0, 540.0, 560.0] { + to(&mut app, [200.0, y], Modifiers::NONE); + } + up(&mut app, [200.0, 560.0], Modifiers::NONE); + let path = saved(&app); + assert_eq!(path.subpaths[0].knots.len(), 5); + let k = knot_at(&path, [200.0, 500.0]); + assert_knot(&k, [200.0, 500.0], [200.0, 560.0], [200.0, 440.0]); + assert!(k.smooth); + assert_eq!((steps(&app), undo_label(&app).as_deref()), (n + 1, Some("Add Anchor Point"))); + assert!(app.session.undo()); + assert_eq!(saved(&app), before, "one undo takes back the add and the pull"); +} + +#[test] +fn shift_turns_the_handle_to_45_degrees_and_the_in_handle_mirrors_it() { + // The anchor goes in at (200,500); the drags are offsets from it. + for (d, want) in [ + ([30.0, 80.0], [0.0, 80.0]), + ([70.0, 40.0], [40.0, 40.0]), + ([-50.0, -60.0], [-50.0, -50.0]), + ([60.0, -20.0], [60.0, 0.0]), + ([50.0, 45.0], [45.0, 45.0]), + ] { + let mut app = square(); + down(&mut app, [200.0, 500.0]); + let at = [200.0 + d[0], 500.0 + d[1]]; + to(&mut app, at, Modifiers::SHIFT); + up(&mut app, at, Modifiers::SHIFT); + let k = knot_at(&saved(&app), [200.0, 500.0]); + assert_knot(&k, [200.0, 500.0], [200.0 + want[0], 500.0 + want[1]], [200.0 - want[0], 500.0 - want[1]]); + } +} + +#[test] +fn alt_during_the_drag_breaks_the_pair_so_only_the_out_handle_follows() { + let mut app = square(); + let n = steps(&app); + down(&mut app, [100.0, 400.0]); + to(&mut app, [40.0, 400.0], Modifiers::NONE); + to(&mut app, [40.0, 420.0], Modifiers::ALT); + to(&mut app, [40.0, 440.0], Modifiers::ALT); + up(&mut app, [40.0, 440.0], Modifiers::ALT); + let k = knot_at(&saved(&app), [100.0, 400.0]); + assert_knot(&k, [100.0, 400.0], [40.0, 440.0], [160.0, 400.0]); + assert_eq!((steps(&app), undo_label(&app).as_deref()), (n + 1, Some("Add Anchor Point"))); +} + +#[test] +fn the_drag_works_on_a_shape_layers_path_in_one_step() { + // 800 x 600, a shape from (450,100) to (650,250), made the active layer. + let (mut app, shape) = super::delete_anchor_targeted_path_tests::setup(Tool::AddAnchorPoint); + super::delete_anchor_targeted_path_tests::select_layer(&mut app, shape); + app.ui.extras.snap = false; + let n = steps(&app); + down(&mut app, [550.0, 250.0]); + to(&mut app, [550.0, 280.0], Modifiers::NONE); + to(&mut app, [550.0, 300.0], Modifiers::NONE); + up(&mut app, [550.0, 300.0], Modifiers::NONE); + let path = crate::direct_select::path_of(&app, &PathRef::Layer(shape)).unwrap().into_owned(); + assert_knot(&knot_at(&path, [550.0, 250.0]), [550.0, 250.0], [550.0, 300.0], [550.0, 200.0]); + assert_eq!((steps(&app), undo_label(&app).as_deref()), (n + 1, Some("Add Anchor Point"))); +} + +#[test] +fn a_click_without_movement_keeps_the_plain_add() { + let mut app = square(); + let mut want = saved(&app); + let Some(photocraft_vector::edit::Hit::Segment(k, t)) = photocraft_vector::edit::hit(&want, Point::new(200.0, 500.0), 6.0, &[]) else { + panic!("no segment") + }; + photocraft_vector::edit::add_anchor(&mut want, k, t).unwrap(); + let n = steps(&app); + down(&mut app, [200.0, 500.0]); + up(&mut app, [200.0, 500.0], Modifiers::NONE); + // Only the add: the canvas maps the click in f32, so the anchor lands within a hundredth of a pixel. + let got = saved(&app); + assert_eq!(got.subpaths[0].knots.len(), want.subpaths[0].knots.len(), "one anchor added"); + for (g, w) in got.subpaths[0].knots.iter().zip(&want.subpaths[0].knots) { + let near = |p: Point, q: Point| (p.x - q.x).hypot(p.y - q.y) < 0.01; + assert!(near(g.anchor, w.anchor) && near(g.in_ctrl, w.in_ctrl) && near(g.out_ctrl, w.out_ctrl) && g.smooth == w.smooth, "{g:?} vs {w:?}"); + } + assert_eq!((steps(&app), undo_label(&app).as_deref()), (n + 1, Some("Add Anchor Point"))); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_select_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_select_tests.rs new file mode 100644 index 0000000000..22aa23f965 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_select_tests.rs @@ -0,0 +1,145 @@ +//! #12708: Add Anchor Point selects, moves and reshapes existing anchors and handles as Direct +//! Selection does, and a click on a segment still adds an anchor. The overlay reports these edits +//! (craft-libs#2283); these tests check that PhotoCraft turns them into the right commands and +//! History steps. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use photocraft_geom::Point; +use serde_json::json; + +use super::delete_anchor_targeted_path_tests::{setup, steps}; +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::direct_select::PathRef; +use crate::state::Tool; + +/// Saved path "Path 1", targeted in the Paths panel: the closed corner square of the issue and an +/// open curve through the measured smooth anchor (549.5,340), in (474.7,340), out (624.7,340). +fn target_path_1(app: &mut PhotocraftApp) { + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [ + [450, 450], + {"anchor": [549.5, 340], "in": [474.7, 340], "out": [624.7, 340], "smooth": true}, + [650, 450]]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); +} + +fn tool_app(tool: Tool) -> Box { + let (mut app, _) = setup(tool); + target_path_1(&mut app); + app +} + +fn path(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths[0].path.clone() +} + +fn knot(app: &PhotocraftApp, s: usize, k: usize) -> photocraft_doc::Knot { + path(app).subpaths[s].knots[k] +} + +fn label(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.undo_label().map(str::to_string) +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { + testing::click(app, at, mods); +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + testing::press(app, from, mods); + testing::move_to(app, [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0], mods); + testing::move_to(app, to, mods); + testing::release(app, to, mods); +} + +fn close(got: Point, want: [f64; 2], what: &str) { + assert!((got.x - want[0]).abs() <= 0.5 && (got.y - want[1]).abs() <= 0.5, "{what}: got ({}, {}), want {want:?}", got.x, got.y); +} + +#[test] +fn a_click_on_an_anchor_selects_it_shift_adds_and_empty_canvas_deselects_without_steps() { + let mut app = tool_app(Tool::AddAnchorPoint); + let (before, n) = (path(&app), steps(&app)); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Saved(0))); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + click(&mut app, [300.0, 500.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [0, 2]]); + click(&mut app, [100.0, 300.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 0]], "a plain click selects that anchor alone"); + click(&mut app, [50.0, 50.0], Modifiers::NONE); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the path stays targeted"); + assert_eq!((path(&app), steps(&app)), (before, n), "selecting changes nothing and records nothing"); +} + +#[test] +fn dragging_an_anchor_moves_it_with_its_handles_in_one_drag_anchor_point_step() { + let mut app = tool_app(Tool::AddAnchorPoint); + let n = steps(&app); + drag(&mut app, [300.0, 300.0], [330.0, 280.0], Modifiers::NONE); + let k = knot(&app, 0, 1); + close(k.anchor, [330.0, 280.0], "anchor"); + close(k.in_ctrl, [330.0, 280.0], "in"); + close(k.out_ctrl, [330.0, 280.0], "out"); + assert_eq!(path(&app).subpaths[0].knots.len(), 4, "no anchor added"); + assert_eq!(steps(&app), n + 1); + assert_eq!(label(&app).as_deref(), Some("Drag Anchor Point")); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "the dragged anchor stays selected"); +} + +#[test] +fn dragging_a_smooth_anchors_out_handle_turns_the_in_handle_and_keeps_its_length() { + let mut app = tool_app(Tool::AddAnchorPoint); + let n = steps(&app); + click(&mut app, [549.5, 340.0], Modifiers::NONE); + assert_eq!(steps(&app), n, "the selecting click records nothing"); + drag(&mut app, [624.7, 340.0], [624.7, 300.0], Modifiers::NONE); + let k = knot(&app, 1, 1); + close(k.anchor, [549.5, 340.0], "anchor"); + close(k.out_ctrl, [624.7, 300.0], "out"); + close(k.in_ctrl, [483.4, 375.2], "in"); + assert_eq!(steps(&app), n + 1, "the drag is one step"); + assert_eq!(label(&app).as_deref(), Some("Drag Control Point")); +} + +#[test] +fn alt_dragging_a_handle_moves_only_that_handle() { + let mut app = tool_app(Tool::AddAnchorPoint); + click(&mut app, [549.5, 340.0], Modifiers::NONE); + let n = steps(&app); + drag(&mut app, [474.7, 340.0], [474.7, 300.0], Modifiers::ALT); + let k = knot(&app, 1, 1); + close(k.in_ctrl, [474.7, 300.0], "in"); + close(k.out_ctrl, [624.7, 340.0], "out unchanged"); + close(k.anchor, [549.5, 340.0], "anchor"); + assert_eq!(path(&app).subpaths[1].knots.len(), 3, "⌥ on a handle neither adds nor deletes"); + assert_eq!(steps(&app), n + 1); + assert_eq!(label(&app).as_deref(), Some("Drag Control Point")); +} + +#[test] +fn a_click_on_a_segment_still_adds_an_anchor_and_selects_only_it() { + let mut app = tool_app(Tool::AddAnchorPoint); + click(&mut app, [300.0, 300.0], Modifiers::NONE); + let n = steps(&app); + click(&mut app, [200.0, 500.0], Modifiers::NONE); + assert_eq!(path(&app).subpaths[0].knots.len(), 5); + assert_eq!(steps(&app), n + 1); + assert_eq!(label(&app).as_deref(), Some("Add Anchor Point")); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 3]], "the new anchor is the only selected one"); +} + +/// A press on a handle that is not shown (its anchor is not selected) grabs nothing. +#[test] +fn a_hidden_handle_is_not_grabbed() { + let mut app = tool_app(Tool::AddAnchorPoint); + let (before, n) = (path(&app), steps(&app)); + drag(&mut app, [624.7, 340.0], [624.7, 300.0], Modifiers::NONE); + assert_eq!((path(&app), steps(&app)), (before, n)); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_tolerance_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_tolerance_tests.rs new file mode 100644 index 0000000000..9729e95552 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_tolerance_tests.rs @@ -0,0 +1,87 @@ +//! #12732: Add Anchor Point reaches a segment within 5 points, as measured at display scale 1: at +//! 100 % a click 5 px from a segment adds an anchor and one 6 px away does nothing; at 200 % that +//! is 2.5 document px. The reach is the overlay's (storytold/craft-libs#2282); these tests drive it +//! through the canvas. Delete Anchor Point keeps its 6 points. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::state::Tool; + +/// The measured document: 800 × 600 px with an open straight subpath from (400, 300) to (700, 300) +/// in the saved path "Path 1", selected in the Paths panel, shown at `zoom`. +fn app(tool: Tool, zoom: f32) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ui.views[0].clear_pending(); + app.ui.tool = tool; + let path = json!({"subpaths": [{"closed": false, "knots": [[400, 300], [700, 300]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + testing::clear_of_dialogs(&mut app, [550.0, 300.0]); + app +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2]) { + testing::click(app, at, Modifiers::NONE); +} + +/// Does a click `dy` document px below the segment's middle add an anchor there, in one History +/// step? A click that adds nothing must leave the path and the History alone. +fn adds_at(zoom: f32, dy: f64) -> bool { + let mut app = app(Tool::AddAnchorPoint, zoom); + let (before, n) = (saved(&app), steps(&app)); + click(&mut app, [550.0, 300.0 + dy]); + let after = saved(&app); + if after == before { + assert_eq!(steps(&app), n, "a click that adds nothing adds no step ({dy} px)"); + return false; + } + assert_eq!(after.subpaths[0].knots.len(), 3, "{dy} px"); + let added = after.subpaths[0].knots[1].anchor; + assert!((added.x - 550.0).abs() < 0.01 && (added.y - 300.0).abs() < 1e-6, "the anchor goes on the segment: {added:?}"); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); + true +} + +#[test] +fn at_100_percent_a_click_5_px_from_a_segment_adds_an_anchor_and_6_px_does_nothing() { + for dy in [2.0, 4.0, 5.0] { + assert!(adds_at(1.0, dy), "{dy} px below adds"); + assert!(adds_at(1.0, -dy), "{dy} px above adds"); + } + assert!(!adds_at(1.0, 6.0)); + assert!(!adds_at(1.0, -6.0)); +} + +#[test] +fn the_reach_is_in_screen_pixels_so_at_200_percent_it_is_2_5_document_px() { + assert!(adds_at(2.0, 2.5)); + assert!(!adds_at(2.0, 3.0)); + // And 10 document px at 50 %. + assert!(adds_at(0.5, 10.0)); + assert!(!adds_at(0.5, 12.0)); +} + +#[test] +fn delete_anchor_point_still_reaches_an_anchor_within_6_points() { + let mut app = app(Tool::DeleteAnchorPoint, 1.0); + let path = json!({"subpaths": [{"closed": false, "knots": [[400, 300], [550, 300], [700, 300]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + click(&mut app, [550.0, 305.5]); + assert_eq!(saved(&app).subpaths[0].knots.len(), 2, "5.5 px from the middle anchor deletes it"); +} diff --git a/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs index b292173892..fb8f4ead04 100644 --- a/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs +++ b/crates/ui-egui/src/tools/art_history_refusal_alert_tests.rs @@ -85,3 +85,44 @@ fn the_history_brush_keeps_the_status_bar() { assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); assert!(!app.ui.status.contains("art history"), "{}", app.ui.status); } + +/// Targets `layer`'s mask, as a click on the mask thumbnail does. +fn target_the_mask(app: &mut PhotocraftApp) { + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::LayerMask; +} + +/// The alerts were measured on a layer's pixels only: a hidden layer with its mask targeted keeps +/// the status bar's text. +#[test] +fn a_hidden_layer_with_its_mask_targeted_keeps_the_status_bar() { + let mut app = art_history(); + let id = active(&app); + target_the_mask(&mut app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before); + assert!(app.ui.status_error && app.ui.status.contains("target layer is hidden"), "{:?}", app.ui.status); + assert!(!app.ui.status.contains("art history"), "{}", app.ui.status); +} + +/// A release-time refusal of a mask target stays in the status bar too, here the 32-bit one; +/// the same refusal on the layer's pixels is an alert. +#[test] +fn a_release_time_refusal_of_a_mask_target_keeps_the_status_bar() { + const BITS32: &str = + "Could not use the art history brush because it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit)."; + let mut app = art_history(); + app.run("image.mode.bits32", json!({})).unwrap(); + app.run("history.setSource", json!({"state": steps(&app)})).unwrap(); + refused(&mut app, BITS32); + target_the_mask(&mut app); + app.run("history.setSource", json!({"state": steps(&app)})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert_eq!(steps(&app), before); + assert!(app.ui.status_error && app.ui.status == BITS32, "{:?}", app.ui.status); +} diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index ed76093d49..395b44022d 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -81,10 +81,27 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { return (!hidden && pixel_layer && layer_refusal(app, tool) == Some(LOCKED)).then(|| tl!(REMOVE_LOCKED).to_string()); } let name = tool_name(app, tool)?; + // The Art History Brush's hidden alert was measured on a layer's pixels only (#12638): a + // hidden mask or channel target keeps the status bar. + if hidden && tool == Tool::ArtHistoryBrush && !pixels_target(&crate::canvas::paint_target(app)) { + return None; + } let template = if hidden { HIDDEN } else { layer_refusal(app, tool)? }; Some(crate::i18n::fmt(tl!(template), &[("tool", name)])) } +/// Whether `target`, a `canvas::paint_target` value, is a layer's pixels as the engine reads it +/// (`channel_cmds::target_of`): not a layer or filter mask, the Quick Mask or an alpha channel. A +/// set of colour channels edits the layer's pixels. +pub(crate) fn pixels_target(target: &serde_json::Value) -> bool { + use serde_json::Value; + match target { + Value::String(s) => !matches!(s.as_str(), "mask" | "filterMask" | "quickMask"), + Value::Object(o) => o.get("channel").and_then(Value::as_u64).is_none(), + _ => true, + } +} + /// [`GROUP`] or [`LOCKED`] when `tool` can't paint the active layer's pixels. fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { let st = app.session.active()?; diff --git a/crates/ui-egui/src/tools/direct_select/edits.rs b/crates/ui-egui/src/tools/direct_select/edits.rs index c015b4be40..cc1fe27f77 100644 --- a/crates/ui-egui/src/tools/direct_select/edits.rs +++ b/crates/ui-egui/src/tools/direct_select/edits.rs @@ -374,19 +374,31 @@ fn edit_draft(app: &mut PhotocraftApp, edit: impl FnOnce(&mut EditPath) -> bool) } } +#[cfg(test)] +#[path = "../anchor_tools/add_anchor_alt_tests.rs"] +mod add_anchor_alt_tests; #[cfg(test)] #[path = "../anchor_tools/add_anchor_delete_key_tests.rs"] mod add_anchor_delete_key_tests; #[cfg(test)] +#[path = "../anchor_tools/add_anchor_drag_tests.rs"] +mod add_anchor_drag_tests; +#[cfg(test)] #[path = "../anchor_tools/add_anchor_escape_tests.rs"] mod add_anchor_escape_tests; #[cfg(test)] #[path = "../anchor_tools/add_anchor_lock_tests.rs"] mod add_anchor_lock_tests; #[cfg(test)] +#[path = "../anchor_tools/add_anchor_select_tests.rs"] +mod add_anchor_select_tests; +#[cfg(test)] #[path = "../anchor_tools/add_anchor_targeted_path_tests.rs"] mod add_anchor_targeted_path_tests; #[cfg(test)] +#[path = "../anchor_tools/add_anchor_tolerance_tests.rs"] +mod add_anchor_tolerance_tests; +#[cfg(test)] #[path = "../anchor_tools/delete_anchor_alt_tests.rs"] mod delete_anchor_alt_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index b5dbf23d15..f08ddfd715 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -270,6 +270,7 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ // The layer mask, an alpha channel or the Quick Mask when targeted, as the Brush paints. p["target"] = crate::canvas::paint_target(app); crate::canvas::unsmoothed_line(&mut p, line); + let pixels = crate::brush_refusal::pixels_target(&p["target"]); let result = app.run(cmd, p); app.retouch_from_live = matches!(&result, Ok(r) if r.get("fromLive").and_then(Value::as_bool) == Some(true)); match result { @@ -282,8 +283,9 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ } Ok(_) => {} // The Art History Brush's source refusals are alerts with OK, as the press-time ones, and - // not in the status bar as well (#12638). - Err(e) if tool == Tool::ArtHistoryBrush && e.starts_with("Could not use the art history brush because") => { + // not in the status bar as well (#12638). They were measured on a layer's pixels only: a + // mask or channel target keeps the status bar. + Err(e) if tool == Tool::ArtHistoryBrush && pixels && e.starts_with("Could not use the art history brush because") => { app.ui.status.clear(); app.ui.status_error = false; let _ = crate::dialogs::alerts::alert(app, tl!(&e).to_owned()); diff --git a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs index 08641b02ac..97ad7528ac 100644 --- a/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs +++ b/crates/ui-egui/tests/it/gpu_tests/arbitrary_rotation_preview.rs @@ -1,5 +1,9 @@ //! #1436: a size-changing Arbitrary rotation preview must remain visible on the real GPU canvas. //! Synthetic blue pixels are measured outside the dialog, so its controls cannot pass the test. +//! +//! Rotate Canvas itself has no Preview, as in the reference application (#14462): the menu's dialog +//! leaves the canvas as it is until OK. The size-changing preview the canvas still places is opened +//! with its Preview box through `filter_dialog::open_previewing`. use egui::accesskit::Toggled; use egui_kittest::kittest::{NodeT, Queryable}; @@ -55,11 +59,18 @@ fn setup(h: &mut Harness, width: u32, height: u32, zoom: f32, center: [f32; 2]) assert!(h.state().perf.gpu, "the fixture must use the GPU canvas"); } -/// Opens the dialog and returns the id the reply gave, in the protocol's own form. +/// Opens the dialog through the menu and returns the id the reply gave, in the protocol's own form. fn open(h: &mut Harness) -> Value { control(h, "ui.menu.invoke", json!({"id":"image.rotation.arbitrary"}))["dialog"].clone() } +/// Opens the dialog with a Preview box, which the menu's has not (#14462), and returns its id in the protocol's form. +fn open_previewing(h: &mut Harness) -> Value { + let id = photocraft_ui_egui::filter_dialog::open_previewing(h.state_mut(), "image.rotation.arbitrary").expect("the dialog opens"); + h.run_steps(4); + json!(id.value().to_string()) +} + fn angle(h: &mut Harness, id: &Value, value: f64) { control(h, "ui.dialog.set", json!({"dialog":id,"field":"angle","value":value})); } @@ -117,7 +128,7 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { { setup(&mut h, width, height, zoom, center); assert_eq!(photocraft_ui_egui::proxy::factor(&h.state().session.active().unwrap().doc), factor); - let id = open(&mut h); + let id = open_previewing(&mut h); let source = blue(&mut h, &format!("{width}x{height}-{degrees}-zero")).0; assert!(source > 5_000, "the unrotated blue image must be visible outside the dialog"); angle(&mut h, &id, degrees); @@ -140,7 +151,7 @@ fn size_changing_rotation_preview_is_visible_and_preserves_the_panned_center() { } #[test] -fn preview_toggle_and_cancel_keep_the_document_while_ok_applies_rotation() { +fn the_dialog_has_no_preview_and_cancel_keeps_the_document_while_ok_applies_rotation() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); @@ -148,18 +159,15 @@ fn preview_toggle_and_cancel_keep_the_document_while_ok_applies_rotation() { let st = h.state().session.active().unwrap(); let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.entries()); let id = open(&mut h); - assert!(blue(&mut h, "control-zero-on").0 > 5_000); - h.get_by_label("Preview").click(); - h.run_steps(4); - assert!(!preview_on(&h)); - assert!(blue(&mut h, "control-zero-off").0 > 5_000); - h.get_by_label("Preview").click(); - h.run_steps(4); - assert!(preview_on(&h)); - assert!(blue(&mut h, "control-zero-restored").0 > 5_000); - h.get_by_label("Preview").click(); - h.run_steps(4); + assert!(h.query_by_label("Preview").is_none(), "Rotate Canvas has no Preview box"); + assert!(blue(&mut h, "control-zero").0 > 5_000); + // A 45° turn would grow the canvas to 453 x 453; while the dialog is open the canvas keeps the document as it is. angle(&mut h, &id, 45.0); + let (count, top, bottom) = blue(&mut h, "control-45-open"); + assert!(count > 5_000, "the unrotated image stays visible ({count})"); + let rect = photocraft_ui_egui::canvas::active_view(h.state()).expect("a shown view").rect; + assert!(((top + bottom) as f32 / 2.0 - rect.center().y).abs() < 3.0, "the image stays centred"); + assert!(bottom - top <= 242, "no rotated preview grows the image: {top}..{bottom}"); h.get_by_label("Cancel").click(); h.run_steps(4); let st = h.state().session.active().unwrap(); @@ -169,8 +177,6 @@ fn preview_toggle_and_cancel_keep_the_document_while_ok_applies_rotation() { assert!(blue(&mut h, "control-cancel").0 > 5_000); let id = open(&mut h); - h.get_by_label("Preview").click(); - h.run_steps(4); angle(&mut h, &id, 45.0); h.get_by_label("OK").click(); h.run_steps(4); diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index 500f28e542..19186f15ad 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -52,6 +52,17 @@ fn inspect(h: &mut H, id: &str) -> Value { listed["result"]["dialogs"].as_array().into_iter().flatten().find(|d| d["id"] == json!(id)).map(|d| d["fields"].clone()).expect("the dialog is listed") } +/// The id of the open dialog whose message is `message`, as `ui.inspect` lists it. +fn alert_id(h: &mut H, message: &str) -> Option { + let listed = control(h, "ui.inspect", json!({})); + listed["result"]["dialogs"] + .as_array() + .into_iter() + .flatten() + .find(|d| d["fields"]["message"] == json!(message)) + .and_then(|d| d["id"].as_str().map(str::to_owned)) +} + fn confirm(h: &mut H, id: &str) { assert!(!refused(&control(h, "ui.dialog.confirm", json!({"dialog": id})))); h.run_steps(3); @@ -82,6 +93,8 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, H, String) { #[cfg(not(target_arch = "wasm32"))] photocraft_raster::spill::use_test_volume_space(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + // The alert assertions use English text; don't follow the system locale. + app.session.prefs.edit(|p| p.interface.language = "en".into()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); let layer = app.session.active().unwrap().active_layer.unwrap(); let mut h = harness(app); @@ -149,6 +162,11 @@ fn failed_apply_can_be_corrected_without_retries_or_cancel_rollback() { h.get_by_label("Apply").click(); h.run_steps(3); assert!(h.state().ui.status.contains("missing.png"), "{}", h.state().ui.status); + // The missing file's alert opens on top (#14500); OK dismisses it. + let alert = alert_id(&mut h, "Could not apply data set because the replacement file was not found.").expect("the missing-file alert is open"); + confirm(&mut h, &alert); + assert_eq!(alert_id(&mut h, "Could not apply data set because the replacement file was not found."), None); + assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); h.state_mut().ui.status.clear(); h.run_steps(3); diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs index a03ee0b2f4..7ce05d641a 100644 --- a/crates/vector/src/edit.rs +++ b/crates/vector/src/edit.rs @@ -122,6 +122,35 @@ pub fn move_anchors(path: &mut Path, anchors: &[[usize; 2]], d: [f64; 2]) -> Res Ok(()) } +/// Add Anchor Point's ⌥-drag on a segment, as in Photoshop: the subpaths holding `anchors` are +/// copied to the end of the path, in order, and the copies move by `d`; the originals stay. A copy +/// keeps its source's operation, as measured in the reference (#13211: a copy of the first +/// subpath, stored Exclude, stays Exclude). A copy of a joined subpath takes its component's +/// stored operation instead, so it stands on its own rather than joining whichever component is +/// last. Returns the copies' anchors. +pub fn duplicate_subpaths(path: &mut Path, anchors: &[[usize; 2]], d: [f64; 2]) -> Result, String> { + let mut subs = Vec::with_capacity(anchors.len()); + for &[s, k] in anchors { + path.subpaths.get(s).and_then(|sp| sp.knots.get(k)).ok_or_else(|| format!("no knot {k} in subpath {s}"))?; + subs.push(s); + } + subs.sort_unstable(); + subs.dedup(); + let mut copies = Vec::new(); + for s in subs { + let Some(mut sp) = path.subpaths.get(s).cloned() else { continue }; + if sp.op == PathOp::Join { + // The operation stored on the component's first subpath (`Path::components`). + sp.op = path.subpaths.get(..s).unwrap_or_default().iter().rev().map(|h| h.op).find(|&op| op != PathOp::Join).unwrap_or(PathOp::Combine); + } + let at = path.subpaths.len(); + copies.extend((0..sp.knots.len()).map(|k| [at, k])); + path.subpaths.push(sp); + } + move_anchors(path, &copies, d)?; + Ok(copies) +} + /// The Curvature Pen's anchor drag: moves the anchors like [`move_anchors`], then recomputes the /// handles of every smooth knot in the subpaths it touched with [`curvature_knots`], so the curve /// keeps flowing smoothly through all its anchors, as Photoshop does. Corner knots keep their own @@ -924,6 +953,29 @@ mod tests { assert_eq!(subpath_anchors(&p, 0), vec![[0, 0], [0, 1], [0, 2]]); assert!(subpath_anchors(&p, 4).is_empty()); } + + #[test] + fn duplicated_subpaths_go_to_the_end_and_a_joined_one_stands_alone() { + // Subpath 0 stores Exclude (being first, it draws as Combine); 1 joins it; 2 subtracts, 3 joins 2. + let mut p = tri(); + p.subpaths[0].op = PathOp::Exclude; + let joined = Subpath { op: PathOp::Join, ..p.subpaths[0].clone() }; + p.subpaths.push(joined.clone()); + p.subpaths.push(Subpath { op: PathOp::Subtract, ..p.subpaths[0].clone() }); + p.subpaths.push(joined); + let before = p.clone(); + let copies = duplicate_subpaths(&mut p, &[[1, 0], [1, 2]], [5.0, -5.0]).unwrap(); + assert_eq!(copies, vec![[4, 0], [4, 1], [4, 2]]); + assert_eq!(p.subpaths[..4], before.subpaths[..], "the originals stay"); + assert_eq!(p.subpaths[4].op, PathOp::Exclude, "a joined subpath's copy takes its component's stored operation"); + assert_eq!(p.subpaths[4].knots[0].anchor, add(before.subpaths[1].knots[0].anchor, [5.0, -5.0])); + duplicate_subpaths(&mut p, &[[0, 0]], [5.0, 0.0]).unwrap(); + assert_eq!(p.subpaths[5].op, PathOp::Exclude, "a copy of the first subpath keeps its stored operation, as measured (#13211)"); + duplicate_subpaths(&mut p, &[[3, 1]], [5.0, 0.0]).unwrap(); + assert_eq!(p.subpaths[6].op, PathOp::Subtract, "a later joined subpath takes its component's operation"); + assert!(duplicate_subpaths(&mut p, &[[9, 0]], [1.0, 1.0]).is_err()); + assert_eq!(p.subpaths.len(), 7, "a bad anchor copies nothing"); + } } #[cfg(test)] diff --git a/docs/development.md b/docs/development.md index 6c43c8dac2..b6093f21b2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -191,7 +191,7 @@ A file dragged in from the desktop logs two lines at `info` (`file_open.rs`; fil |---|---| | `PHOTOCRAFT_GPU=1` (or `=0`) | Headless CLI: prefer GPU composition and flat export (0 to disable, empty to unset). Explicit `--gpu`/`--no-gpu` CLI flags override this variable. `file.export.quickExport` composites and encodes inside the engine, which has no renderer, so it always runs on the CPU; `run --gpu` prints a one-time warning when a step uses it | | `PHOTOCRAFT_CONTROL_PORT` | Same as `--control `; also the port for `photocraft-cli serve --port` and `mcp --bridge` when the flag is absent. Empty is unset | -| `PHOTOCRAFT_NO_PRINT` | Set to anything but `0`: `file.print` / `file.printOneCopy` refuse to spool (`dryRun` still works). CI sets it, with `LPDEST=photocraft-no-such-printer` as a second net; set both when running the panic hunt or fuzzers locally | +| `PHOTOCRAFT_NO_PRINT` | Set to a non-empty value other than `0` (empty counts as unset): `file.print` / `file.printOneCopy` refuse to spool (`dryRun` still works) and `file.print.page` asks no printer driver. CI sets it, with `LPDEST=photocraft-no-such-printer` as a second net; set both when running the panic hunt or fuzzers locally | | `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) | | `PHOTOCRAFT_CONTROL_TOKEN` | 64-hex bearer token for control TCP (avoid on shared systems where environment inspection is possible) | | `PHOTOCRAFT_CONTROL_TOKEN_FILE` | Read, or create for a server, the control bearer-token file |