From db03b87aba0834289978978a589428e84c333b3e Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 24 Nov 2026 01:02:02 +0000 Subject: [PATCH] Engine split step 8: core tests that run vector commands move to the top crate's tests/it (move_tests.py output) --- .config/ci-test-times.tsv | 36 +-- .../engine-core/src/actions_record/tests.rs | 36 --- crates/engine-core/src/cmd/atn_cmds/tests.rs | 74 ------- .../src/cmd/automate_cmds/tests.rs | 79 ------- .../engine-core/src/cmd/count_resize_tests.rs | 65 +----- .../cmd/file_cmds/load_stack_name_tests.rs | 20 +- .../src/cmd/layer_copy_cmds/tests.rs | 163 -------------- .../src/cmd/type_extra_cmds/tests.rs | 62 ------ .../src/cmd/type_indexed_mode_tests.rs | 110 +--------- crates/engine-core/src/cmd/type_spell_cmds.rs | 10 - .../cmd/type_vertical_history_name_tests.rs | 24 -- crates/engine-core/src/param_schema/tests.rs | 29 --- crates/engine/tests/it/main.rs | 11 + .../tests/it/vector_in_actions_record.rs | 57 +++++ crates/engine/tests/it/vector_in_atn_cmds.rs | 118 ++++++++++ .../tests/it/vector_in_automate_cmds.rs | 96 ++++++++ .../engine/tests/it/vector_in_count_resize.rs | 88 ++++++++ crates/engine/tests/it/vector_in_file_cmds.rs | 51 +++++ .../tests/it/vector_in_layer_copy_cmds.rs | 207 ++++++++++++++++++ .../engine/tests/it/vector_in_param_schema.rs | 43 ++++ .../tests/it/vector_in_type_extra_cmds.rs | 98 +++++++++ .../tests/it/vector_in_type_indexed_mode.rs | 198 +++++++++++++++++ .../tests/it/vector_in_type_spell_cmds.rs | 25 +++ .../vector_in_type_vertical_history_name.rs | 44 ++++ 24 files changed, 1058 insertions(+), 686 deletions(-) create mode 100644 crates/engine/tests/it/vector_in_actions_record.rs create mode 100644 crates/engine/tests/it/vector_in_atn_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_automate_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_count_resize.rs create mode 100644 crates/engine/tests/it/vector_in_file_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_layer_copy_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_param_schema.rs create mode 100644 crates/engine/tests/it/vector_in_type_extra_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_type_indexed_mode.rs create mode 100644 crates/engine/tests/it/vector_in_type_spell_cmds.rs create mode 100644 crates/engine/tests/it/vector_in_type_vertical_history_name.rs diff --git a/.config/ci-test-times.tsv b/.config/ci-test-times.tsv index c7e9c77aff..5241c7ecce 100644 --- a/.config/ci-test-times.tsv +++ b/.config/ci-test-times.tsv @@ -14,10 +14,11 @@ bin linux photocraft-color 37 1.67 bin linux photocraft-compose 536 61.79 bin linux photocraft-compose::it 9 0.33 bin linux photocraft-doc 85 1.85 -bin linux photocraft-engine-core 3408 522.15 +bin linux photocraft-engine-core 3180 494.40 +bin linux photocraft-engine-vector 205 25.68 bin linux photocraft-engine-paint 612 444.97 bin linux photocraft-engine::global_state 27 18.61 -bin linux photocraft-engine::it 1169 486.72 +bin linux photocraft-engine::it 1192 488.79 bin linux photocraft-engine::panic_hunt 2 12.37 bin linux photocraft-format 93 2.35 bin linux photocraft-format::it 131 37.47 @@ -162,9 +163,9 @@ test linux photocraft-compose 4.89 tests::one_colour_areas_reduce_like_composite test linux photocraft-compose 1.25 tests::shapeless_effects_render_the_same_in_bands_and_parts test linux photocraft-compose 1.46 viewport::tests::reduced_pages_match_averaging_every_composited_pixel test linux photocraft-doc 1.10 slices::tests::nested_slices_resolve_in_bounded_work -test linux photocraft-engine-core 1.17 cmd::align_cmds::tests::auto_align_keeps_a_locked_layer_as_the_reference -test linux photocraft-engine-core 5.04 cmd::align_cmds::tests::auto_align_registers_a_smooth_bracket_by_intensity -test linux photocraft-engine-core 1.29 cmd::align_cmds::tests::auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose +test linux photocraft-engine-vector 1.17 cmd::align_cmds::tests::auto_align_keeps_a_locked_layer_as_the_reference +test linux photocraft-engine-vector 5.04 cmd::align_cmds::tests::auto_align_registers_a_smooth_bracket_by_intensity +test linux photocraft-engine-vector 1.29 cmd::align_cmds::tests::auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose test linux photocraft-engine-core 1.24 cmd::artboard_cmds::include_name_tests::a_name_taller_than_the_border_never_draws_over_the_board test linux photocraft-engine-core 1.23 cmd::artboard_cmds::include_name_tests::bad_name_options_never_panic test linux photocraft-engine::it 1.04 paint_in_atn_cmds::render_tests::render_actions_match_direct_filters_and_undo @@ -799,10 +800,11 @@ bin windows photocraft-color 37 5.25 bin windows photocraft-compose 536 125.58 bin windows photocraft-compose::it 9 0.26 bin windows photocraft-doc 85 26.11 -bin windows photocraft-engine-core 3394 904.41 +bin windows photocraft-engine-core 3166 838.77 +bin windows photocraft-engine-vector 205 61.62 bin windows photocraft-engine-paint 612 613.52 bin windows photocraft-engine::global_state 26 31.36 -bin windows photocraft-engine::it 1169 795.43 +bin windows photocraft-engine::it 1192 799.45 bin windows photocraft-engine::panic_hunt 2 26.00 bin windows photocraft-format 85 5.33 bin windows photocraft-format::it 124 121.15 @@ -1020,10 +1022,10 @@ test windows photocraft-engine-core 1.03 canvas_geom::tests::turns_at_every_dept test windows photocraft-engine-core 1.30 cmd::actions_cmds::history::tests::generic_preference_updates_cannot_change_a_paused_history_policy test windows photocraft-engine-core 1.22 cmd::actions_cmds::history::tests::history_policy_stays_fixed_until_all_paused_continuations_are_released test windows photocraft-engine-core 1.50 cmd::actions_cmds::tests::playback_stops_when_a_nested_batch_cannot_write_its_error_log -test windows photocraft-engine-core 1.39 cmd::align_cmds::tests::auto_align_keeps_a_locked_layer_as_the_reference -test windows photocraft-engine-core 1.24 cmd::align_cmds::tests::auto_align_moves_the_background_as_a_normal_layer -test windows photocraft-engine-core 10.49 cmd::align_cmds::tests::auto_align_registers_a_smooth_bracket_by_intensity -test windows photocraft-engine-core 3.92 cmd::align_cmds::tests::auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose +test windows photocraft-engine-vector 1.39 cmd::align_cmds::tests::auto_align_keeps_a_locked_layer_as_the_reference +test windows photocraft-engine-vector 1.24 cmd::align_cmds::tests::auto_align_moves_the_background_as_a_normal_layer +test windows photocraft-engine-vector 10.49 cmd::align_cmds::tests::auto_align_registers_a_smooth_bracket_by_intensity +test windows photocraft-engine-vector 3.92 cmd::align_cmds::tests::auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose test windows photocraft-engine-core 1.03 cmd::analysis_cmds::tests::place_scale_marker_on_a_short_document_errors_without_panicking test windows photocraft-engine-core 1.07 cmd::artboard_cmds::export_options_tests::include_icc_profile_reaches_the_file test windows photocraft-engine-core 1.50 cmd::artboard_cmds::include_name_tests::a_name_taller_than_the_border_never_draws_over_the_board @@ -1146,9 +1148,9 @@ test windows photocraft-engine-core 1.89 cmd::smart_cmds::tests::selection::sele test windows photocraft-engine-core 2.39 cmd::smart_cmds::tests::source_flatten::effects_across_block_edges_match test windows photocraft-engine-core 3.36 cmd::smart_cmds::tests::svg_profile::svg_smart_contents_and_stack_open_many_shapes_as_layers test windows photocraft-engine-core 3.49 cmd::smart_cmds::tests::svg_profile::svg_warp_frame_uses_bounded_bounds -test windows photocraft-engine-core 1.69 cmd::smart_svg_cmds::tests::embedded_pdf_ai_and_eps_update_shared_instances_without_reading_linked_paths -test windows photocraft-engine-core 2.61 cmd::smart_svg_cmds::tests::original_vector_formats_save_atomically_and_survive_undo_and_persistence -test windows photocraft-engine-core 1.23 cmd::smart_svg_cmds::tests::valid_updates_repeat_at_all_depths_and_roundtrip_original_svg +test windows photocraft-engine-vector 1.69 cmd::smart_svg_cmds::tests::embedded_pdf_ai_and_eps_update_shared_instances_without_reading_linked_paths +test windows photocraft-engine-vector 2.61 cmd::smart_svg_cmds::tests::original_vector_formats_save_atomically_and_survive_undo_and_persistence +test windows photocraft-engine-vector 1.23 cmd::smart_svg_cmds::tests::valid_updates_repeat_at_all_depths_and_roundtrip_original_svg test windows photocraft-engine-core 1.02 cmd::smartselect_cmds::object_hard_edge_tests::a_wrong_type_hard_edge_is_the_default test windows photocraft-engine-core 1.42 cmd::smartselect_cmds::object_hard_edge_tests::hard_edge_off_matches_the_reference_rectangle test windows photocraft-engine-core 2.63 cmd::smartselect_cmds::object_hard_edge_tests::hard_edge_off_on_the_reference_disc @@ -1158,9 +1160,9 @@ test windows photocraft-engine-core 1.08 cmd::smartselect_cmds::tests::object_se test windows photocraft-engine-core 7.25 cmd::smartselect_cmds::tests::refine_edge_accepts_huge_sparse_and_solid_selections test windows photocraft-engine-core 2.63 cmd::smartselect_cmds::tests::refine_edge_edits_object_and_subject test windows photocraft-engine-core 1.54 cmd::smartselect_cmds::tests::select_subject_repeat_reuses_the_mask_until_pixels_change -test windows photocraft-engine-core 1.29 cmd::type_area_cmds::tests::a_resolution_change_keeps_area_type_wrapping_where_it_was -test windows photocraft-engine-core 2.68 cmd::type_area_cmds::tests::area_type_saves_to_psd_as_paragraph_text_with_a_warning -test windows photocraft-engine-core 1.02 cmd::type_caret_cmds::tests::caret_midpoint_round_trips_for_point_paragraph_transformed_and_vertical +test windows photocraft-engine-vector 1.29 cmd::type_area_cmds::tests::a_resolution_change_keeps_area_type_wrapping_where_it_was +test windows photocraft-engine-vector 2.68 cmd::type_area_cmds::tests::area_type_saves_to_psd_as_paragraph_text_with_a_warning +test windows photocraft-engine-vector 1.02 cmd::type_caret_cmds::tests::caret_midpoint_round_trips_for_point_paragraph_transformed_and_vertical test windows photocraft-engine-core 1.10 cmd::type_cmds::tests::a_duplicated_type_layer_follows_its_new_text test windows photocraft-engine-core 1.01 cmd::type_spell_cmds::enabled_tests::enabled_with_type_layers_as_before test windows photocraft-engine-core 1.19 cmd::type_spell_cmds::order_tests::a_null_unknown_or_pixel_from_checks_top_to_bottom diff --git a/crates/engine-core/src/actions_record/tests.rs b/crates/engine-core/src/actions_record/tests.rs index bd64b1e37a..83a90a252c 100644 --- a/crates/engine-core/src/actions_record/tests.rs +++ b/crates/engine-core/src/actions_record/tests.rs @@ -96,42 +96,6 @@ fn a_background_job_journals_the_same_way() { assert_eq!(last(&s), &("filter.blur.gaussianBlur".into(), json!({"radius": 2}))); } -#[test] -fn selection_actions_keep_the_active_layer_as_their_source() { - let mut s = session(); - let raster = new_layer(&mut s, "Pixels"); - s.execute("actions.record", json!({"name": "Load pixels"})).unwrap(); - s.execute("select.loadSelection", json!({"channel": "transparency", "layer": raster})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let steps = s.execute("actions.get", json!({"action": "Load pixels"})).unwrap()["steps"].clone(); - assert_eq!(steps[0][1]["layer"], json!({"name": "Pixels"}), "missing layer loads merged pixels instead"); - s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); - new_layer(&mut s, "Pixels"); - let played = s.execute("actions.play", json!({"action": "Load pixels"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - assert_eq!( - s.active().unwrap().doc.selection.as_ref().map(|mask| mask.content_bounds()).unwrap_or(photocraft_geom::Rect::EMPTY), - photocraft_geom::Rect::EMPTY, - "the empty source layer must not load the opaque merged document" - ); - - let type_id = s.execute("type.create", json!({"x": 2, "y": 20, "text": "I", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - let type_name = s.active().unwrap().doc.layer(LayerId(type_id)).unwrap().name.clone(); - s.execute("actions.record", json!({"name": "Mask text"})).unwrap(); - s.execute("type.createSelection", json!({"layer": type_id, "removeLayer": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let steps = s.execute("actions.get", json!({"action": "Mask text"})).unwrap()["steps"].clone(); - assert_eq!(steps[0][1]["layer"], type_name, "without the source, replay cannot remove that type layer"); - s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); - new_layer(&mut s, "Spare"); - let replay_type = s.execute("type.create", json!({"x": 2, "y": 20, "text": "I", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - assert_ne!(replay_type, type_id); - let played = s.execute("actions.play", json!({"action": "Mask text"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - assert!(s.active().unwrap().doc.selection.as_ref().is_some_and(|mask| !mask.content_bounds().is_empty()), "replay selects the glyphs"); - assert!(s.active().unwrap().doc.layer(LayerId(replay_type)).is_none(), "replay removed the named source type layer"); -} - #[test] fn named_nonactive_smart_layer_passes_admission_and_converts_to_layers() { let mut s = session(); diff --git a/crates/engine-core/src/cmd/atn_cmds/tests.rs b/crates/engine-core/src/cmd/atn_cmds/tests.rs index 63828d0e0d..809cf9c6df 100644 --- a/crates/engine-core/src/cmd/atn_cmds/tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/tests.rs @@ -296,40 +296,6 @@ fn sample() -> AtnFile { } } -#[test] -fn layer_comp_apply_imports_plays_and_undoes() { - let name = "合成 𠮷"; - let data = set_of("Comps", vec![("Apply", vec![item("applyComp", "Apply Layer Comp", Some(desc("null").with("null", name_ref("compsClass", name))))])]); - for depth in [8, 16, 32] { - let mut s = crate::session(); - let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); - assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("layerComp.apply", json!({"comp": name}))]); - - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - s.execute("layerComp.new", json!({"name": "Other"})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let played = s.execute("actions.play", json!({"action": "Apply"})).unwrap(); - assert_eq!(played["ran"], 0, "{played}"); - assert!(played["failed"]["error"].as_str().unwrap().contains(name), "{played}"); - assert_eq!(*s.active().unwrap().doc, *before, "a missing comp must not apply another comp"); - - let comp = s.execute("layerComp.new", json!({"name": name})).unwrap()["comp"].clone(); - let layer = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"visible": false})).unwrap(); - s.execute("layerComp.new", json!({"name": "Hidden"})).unwrap(); - let played = s.execute("actions.play", json!({"action": "Apply"})).unwrap(); - assert_eq!(played["ran"], 1, "{played}"); - assert!(played.get("failed").is_none(), "{played}"); - assert!(s.active().unwrap().doc.layer(layer).unwrap().visible); - assert_eq!(json!(s.active().unwrap().doc.last_applied_comp), comp); - assert!(s.undo()); - assert!(!s.active().unwrap().doc.layer(layer).unwrap().visible); - assert!(s.redo()); - assert!(s.active().unwrap().doc.layer(layer).unwrap().visible); - } -} - #[test] fn layer_comp_apply_round_trips_by_name() { for name in ["Comp 1", "合成 𠮷"] { @@ -354,46 +320,6 @@ fn layer_comp_apply_round_trips_by_name() { } } -#[test] -fn layer_comp_apply_unknown_references_are_kept_and_stop_playback() { - let references = [ - None, - Some(D::Integer(1)), - Some(D::Reference(vec![])), - Some(name_ref("Lyr ", "Comp 1")), - Some(class_ref("compsClass")), - Some(D::Reference(vec![ReferenceItem::Offset { class: class("compsClass"), offset: 1 }])), - Some(D::Reference(vec![ReferenceItem::Enumerated { class: class("compsClass"), type_id: code("Ordn"), value: code("unsupported") }])), - Some(D::Reference(vec![ - ReferenceItem::Name { class: class("compsClass"), name: UnicodeString::new_nul("Comp 1") }, - ReferenceItem::Name { class: class("Dcmn"), name: UnicodeString::new_nul("Other") }, - ])), - ]; - let items: Vec<_> = - references.into_iter().map(|reference| item("applyComp", "Apply Layer Comp", reference.map(|r| desc("null").with("null", r)))).collect(); - let data = set_of("Comps", vec![("Unknown", items.clone())]); - let mut s = crate::session(); - let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); - assert_eq!(loaded["unsupported"].as_array().unwrap().len(), items.len()); - assert!(s.actions().list.actions()[0].steps.iter().all(|st| st.command == PHOTOSHOP_STEP)); - assert!(s.actions().list.actions()[0].disabled.is_empty()); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layerComp.new", json!({"name": "Comp 1"})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let played = s.execute("actions.play", json!({"action": "Unknown"})).unwrap(); - assert_eq!(played["ran"], 0, "{played}"); - assert!(played["failed"]["error"].as_str().unwrap().contains("Apply Layer Comp"), "{played}"); - assert_eq!(*s.active().unwrap().doc, *before); - let saved = s.execute("actions.save", json!({"set": "Comps"})).unwrap(); - let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); - let file = atn::parse(&bytes).unwrap(); - assert_eq!(file.actions[0].items.len(), items.len()); - for (saved, original) in file.actions[0].items.iter().zip(&items) { - assert_eq!(saved.event, original.event); - assert_eq!(saved.descriptor, original.descriptor); - } -} - #[test] fn load_maps_events_keeps_flags_and_plays() { let mut s = crate::session(); diff --git a/crates/engine-core/src/cmd/automate_cmds/tests.rs b/crates/engine-core/src/cmd/automate_cmds/tests.rs index 104137c6c8..904f250294 100644 --- a/crates/engine-core/src/cmd/automate_cmds/tests.rs +++ b/crates/engine-core/src/cmd/automate_cmds/tests.rs @@ -598,43 +598,6 @@ fn statistics_makes_a_stack_mode_smart_object() { assert!(s.execute("file.scripts.statistics", json!({"mode": "average", "input": dir})).is_err()); } -#[test] -fn stacked_smart_object_holds_the_loaded_layers_at_its_top_level() { - // Like Photoshop, Load Files into Stack › Create Smart Object (Statistics without alignment) and - // Statistics with alignment embed one layer per file, bottom to top, with no wrapper group. - let dir = tmp("stack-top"); - let mut s = crate::session(); - s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap(); - s.edit("texture", |doc, active| { - let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; - for k in 0..40 { - let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); - surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); - } - Ok(()) - }) - .unwrap(); - let source = photocraft_compose::flatten(&s.active().unwrap().doc); - let files: Vec = (0..3) - .map(|i| { - let path = format!("{dir}/img{i}.png"); - crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap(); - path - }) - .collect(); - for align in [false, true] { - let mut s = crate::session(); - s.execute("file.scripts.statistics", json!({"mode": "median", "input": files, "align": align})).unwrap(); - let d = &s.active().unwrap().doc; - let LayerContent::Smart(so) = &d.layers[0].content else { panic!("not a smart object") }; - let photocraft_doc::SmartSource::Embedded { file_name, bytes } = &so.source else { panic!("not embedded") }; - let inner = crate::smart_cmds::decode_source(file_name, bytes).unwrap(); - let names: Vec<&str> = inner.layers.iter().map(|l| l.name.as_str()).collect(); - assert_eq!(names, ["img0.png", "img1.png", "img2.png"], "align {align}"); - assert_eq!(photocraft_compose::flatten(d).px, source.px, "align {align}"); - } -} - #[test] fn contact_sheet_places_thumbnails_with_captions() { let dir = tmp("contact"); @@ -716,48 +679,6 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() { batch(&mut s, "Loop"); } -/// #4671: Load Files into Stack's Attempt to Automatically Align Source Images runs Auto-Align -/// Layers on the loaded layers, then (with Create Smart Object) puts them in one smart object; -/// without the smart object they stay loose layers, selected. -#[test] -fn load_files_into_stack_aligns_before_the_smart_object() { - let dir = tmp("stack-align"); - let mut s = crate::session(); - s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap(); - s.edit("texture", |doc, active| { - let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; - for k in 0..40 { - let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); - surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); - } - Ok(()) - }) - .unwrap(); - let files: Vec = (0..2) - .map(|i| { - let path = format!("{dir}/img{i}.png"); - crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap(); - path - }) - .collect(); - let mut s = crate::session(); - let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true})).unwrap(); - assert_eq!(r["layers"], 2); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), 2, "loose layers"); - assert!(st.doc.layers.iter().all(|l| matches!(l.content, LayerContent::Raster(_)))); - assert_eq!(st.selected_layers().len(), 2, "Auto-Align ran on them all"); - let mut s = crate::session(); - s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true, "createSmartObject": true})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 1); - let LayerContent::Smart(_) = &d.layers[0].content else { panic!("not a smart object") }; - // A single file has nothing to align with: it just loads. - let mut s = crate::session(); - s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [files[0].clone()], "align": true})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.len(), 1); -} - /// A script file of `lines` (one `file.scripts.browse` call per entry) in `dir`. fn script_calling(dir: &str, name: &str, callees: &[String]) -> String { let path = format!("{dir}/{name}.txt"); diff --git a/crates/engine-core/src/cmd/count_resize_tests.rs b/crates/engine-core/src/cmd/count_resize_tests.rs index 1b9a8346fd..289bafe3e0 100644 --- a/crates/engine-core/src/cmd/count_resize_tests.rs +++ b/crates/engine-core/src/cmd/count_resize_tests.rs @@ -2,7 +2,7 @@ //! Rotation (right angles, flips and arbitrary), also off the new canvas; other marks still follow //! the image, and Crop keeps today's behaviour. -use serde_json::{Value, json}; +use serde_json::{json}; use crate::Session; @@ -16,69 +16,6 @@ fn doc() -> Session { s } -fn count_point(s: &Session) -> [f64; 2] { - s.active().unwrap().doc.measurement.count_groups[0].points[0] -} - -fn note(s: &Session) -> [f64; 2] { - s.active().unwrap().doc.notes[0].position -} - -#[test] -fn count_points_keep_their_coordinates() { - // The note at [100, 100] on the 600×400 canvas, where each command moves it. - let steps: [(&str, Value, [f64; 2]); 8] = [ - ("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]), - ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]), - ("image.imageRotation.90cw", json!({}), [300.0, 100.0]), - ("image.imageRotation.90ccw", json!({}), [100.0, 500.0]), - ("image.imageRotation.180", json!({}), [500.0, 300.0]), - ("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]), - ("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]), - ("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]), - ]; - for (cmd, p, moved) in steps { - let mut s = doc(); - let before = note(&s); - s.execute(cmd, p).unwrap(); - assert_eq!(count_point(&s), POINT, "{cmd}"); - let n = note(&s); - assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}"); - s.undo(); - assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); - } -} - -#[test] -fn all_three_in_a_row_leave_the_point_where_it_was() { - let mut s = doc(); - s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap(); - s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap(); - s.execute("image.imageRotation.90cw", json!({})).unwrap(); - assert_eq!(count_point(&s), POINT); -} - -#[test] -fn crop_still_moves_count_points() { - let mut s = doc(); - s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); - assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); -} - -#[test] -fn ruler_straighten_with_crop_moves_count_points_with_the_image() { - let mut s = crate::session(); - s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); - s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); - s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); - // Straighten Layer is off for the Background (#12033). - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); - s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); - let (c, n) = (count_point(&s), note(&s)); - assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); -} - #[test] fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { let mut s = crate::session(); diff --git a/crates/engine-core/src/cmd/file_cmds/load_stack_name_tests.rs b/crates/engine-core/src/cmd/file_cmds/load_stack_name_tests.rs index 88498bf365..955b6b399f 100644 --- a/crates/engine-core/src/cmd/file_cmds/load_stack_name_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/load_stack_name_tests.rs @@ -2,7 +2,7 @@ //! document, not one named after the first file. use crate::EngineError; -use photocraft_doc::{Layer, LayerContent}; +use photocraft_doc::{Layer}; use serde_json::json; /// Two textured PNGs named a_base.png and b_shift.png (texture, so Auto-Align finds features). @@ -52,21 +52,3 @@ fn the_stack_takes_the_first_free_untitled_number() { s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files})).unwrap(); assert_eq!(s.active().unwrap().doc.name, "Untitled-3"); } - -/// The smart object keeps the first file's name with and without aligning; only the document's -/// name changes. -#[test] -fn the_smart_object_keeps_the_first_files_name() { - let dir = tempfile::tempdir().unwrap(); - let files = two_files(dir.path()).unwrap(); - for align in [false, true] { - let mut s = crate::session(); - s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": align, "createSmartObject": true})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.name, "Untitled-1", "align {align}"); - assert_eq!(st.path, None, "align {align}"); - assert_eq!(st.doc.layers.len(), 1, "align {align}"); - assert!(matches!(st.doc.layers[0].content, LayerContent::Smart(_)), "align {align}"); - assert_eq!(st.doc.layers[0].name, "a_base", "align {align}"); - } -} diff --git a/crates/engine-core/src/cmd/layer_copy_cmds/tests.rs b/crates/engine-core/src/cmd/layer_copy_cmds/tests.rs index 8499ec489a..ebb5d0a11c 100644 --- a/crates/engine-core/src/cmd/layer_copy_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_copy_cmds/tests.rs @@ -205,166 +205,3 @@ fn retargeting_type_survives_bad_resolutions() { crate::canvas_geom::retarget_type_resolution(&mut d, f32::MAX); assert!(size(&d).is_finite() && size(&d) > 0.0, "{}", size(&d)); } - -/// Document 0 at 72 ppi with "Hello" in Paragraph Style 1 (24 pt) and "He" also in Character -/// Style 1 (24 pt, underlined); document 1 at 300 ppi, its own styles made by `dest`. -fn styled_type_docs(dest: impl FnOnce(&mut Session)) -> (Session, LayerId) { - let mut s = crate::session(); - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 72})).unwrap(); - let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 100, "y": 100})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.paragraphStyle.new", json!({"attrs": {"size": 24}, "fromSelection": false, "apply": true, "layer": t})).unwrap(); - s.execute("type.characterStyle.new", json!({"attrs": {"size": 24, "underline": true}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]})) - .unwrap(); - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 300})).unwrap(); - dest(&mut s); - s.set_active(0); - s.execute("layer.select", json!({"layer": t})).unwrap(); - (s, LayerId(t)) -} - -/// The styles panel state of `range` in layer `id` of document 1. -fn styles_of(s: &mut Session, id: LayerId, range: [usize; 2]) -> (Value, Value) { - s.set_active(1); - let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": range})).unwrap(); - let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": range})).unwrap(); - (c, p) -} - -/// #10500: type copied to a document of another resolution brings the styles it uses, as in -/// the reference application (measured with Duplicate Layer from 72 to 300 ppi): a style the -/// destination lacks arrives under its name, scaled like the text (24 pt → 5.76 pt), so the -/// copy has no override; it never takes over an unrelated destination style with the same id. -#[test] -fn copied_type_brings_its_styles_scaled() { - for paste in [false, true] { - let (mut s, _) = styled_type_docs(|s| { - s.execute("type.characterStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap(); - s.execute("type.paragraphStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap(); - }); - let id = if paste { - s.execute("edit.copy", json!({})).unwrap(); - s.set_active(1); - LayerId(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap()["layer"].as_u64().unwrap()) - } else { - copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()) - }; - assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76), "paste {paste}"); - let (c, p) = styles_of(&mut s, id, [0, 2]); - let names = |v: &Value| v["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap().to_string()).collect::>(); - assert_eq!(names(&c), ["None", "Unrelated", "Character Style 1"], "paste {paste}"); - assert_eq!(names(&p), ["Basic Paragraph", "Unrelated", "Paragraph Style 1"], "paste {paste}"); - let (cs, ps) = (&c["styles"][2], &p["styles"][2]); - assert!(close(cs["attrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{cs}"); - assert!(close(ps["characterAttrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{ps}"); - assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&cs["id"], &json!(false)), "paste {paste}"); - assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&ps["id"], &json!(false)), "paste {paste}"); - // The source keeps its 24 pt styles. - assert_eq!(doc(&s, 0).text_styles.character[0].attrs["size_pt"], json!(24.0)); - } -} - -/// A destination that already has a style of the same name keeps its definition (24 pt), and -/// the copy, at 5.76 pt, shows a local override ("+"), as in the reference application. -#[test] -fn copied_type_uses_the_destinations_same_named_style() { - let (mut s, _) = styled_type_docs(|s| { - s.execute("type.characterStyle.new", json!({"name": "Filler", "fromSelection": false})).unwrap(); - s.execute("type.characterStyle.new", json!({"name": "Character Style 1", "attrs": {"size": 24, "underline": true}, "fromSelection": false})).unwrap(); - }); - let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()); - let (c, _) = styles_of(&mut s, id, [0, 2]); - assert_eq!(c["styles"].as_array().unwrap().len(), 3, "no second Character Style 1: {c}"); - let existing = &c["styles"][2]; - assert_eq!(existing["attrs"]["size_pt"], json!(24.0)); - assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&existing["id"], &json!(true))); - assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76)); -} - -/// Duplicate Layer › New Document brings the styles the type uses (at the same size). -#[test] -fn type_duplicated_to_a_new_document_keeps_its_styles() { - let (mut s, t) = styled_type_docs(|_| {}); - let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); - let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap())); - s.set_active(i); - let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); - let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); - assert_eq!(c["styles"][1]["name"], "Character Style 1"); - assert_eq!(c["styles"][1]["attrs"]["size_pt"], json!(24.0)); - assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&c["styles"][1]["id"], &json!(false))); - assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&p["styles"][1]["id"], &json!(false))); - assert_eq!(text(&s, i, id).runs, text(&s, 0, t).runs); -} - -/// Document 0 (RGB, 72 ppi) with "Hello" whose "He" is in Character Style 1 (red); document 1 -/// (CMYK, 72 ppi). The type layer is selected in document 0. -fn red_styled_type_docs() -> (Session, LayerId) { - let mut s = crate::session(); - s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); - let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.characterStyle.new", json!({"attrs": {"color": "#ff0000"}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]})).unwrap(); - s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72, "mode": "cmyk"})).unwrap(); - s.set_active(0); - s.execute("layer.select", json!({"layer": t})).unwrap(); - (s, LayerId(t)) -} - -/// The colour Character Style 1 of document `i` sets, and whether "He" of `id` overrides it. -fn style_color(s: &mut Session, i: usize, id: LayerId) -> (photocraft_color::Color, bool) { - s.set_active(i); - let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); - let style = c["styles"].as_array().unwrap().iter().find(|x| x["name"] == "Character Style 1").unwrap(); - (serde_json::from_value(style["attrs"]["color"].clone()).unwrap(), c["current"]["characterOverride"].as_bool().unwrap()) -} - -/// Type copied to a document of another colour mode converts its run colours, and the style it -/// brings converts with the same transform: the run matches its style (no override), so a later -/// change to the style's colour still reaches it. Converting the document itself (Image › Mode, -/// Convert to Profile with and without dither) keeps its styles in step the same way. -#[test] -fn copied_type_styles_convert_their_colours_with_the_type() { - let (mut s, _) = red_styled_type_docs(); - let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()); - let run = text(&s, 1, id).runs[0].style.color; - assert_eq!(run.mode, ColorMode::Cmyk, "the run converted"); - let (style, over) = style_color(&mut s, 1, id); - assert_eq!(style, run, "the copied style converted with the run"); - assert!(!over, "no false override"); - for (cmd, p) in [ - ("image.mode.cmyk", json!({})), - ("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": false})), - ("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": true})), - ("edit.convertToProfile", json!({"profile": "lab-d50"})), - ] { - let (mut s, t) = red_styled_type_docs(); - s.execute(cmd, p.clone()).unwrap(); - let run = text(&s, 0, t).runs[0].style.color; - assert_ne!(run.mode, ColorMode::Rgb, "{cmd} {p}: the run converted"); - let (style, over) = style_color(&mut s, 0, t); - assert_eq!(style, run, "{cmd} {p}: the style converted with the run"); - assert!(!over, "{cmd} {p}: no false override"); - } -} - -/// Duplicate Layer › New Document keeps the source's Basic Paragraph: type that inherits its -/// size from it has no override there, and Clear Override leaves it as it was. -#[test] -fn type_duplicated_to_a_new_document_keeps_the_sources_basic_paragraph() { - let mut s = crate::session(); - s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - let t = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap()); - s.execute("type.paragraphStyle.set", json!({"id": 0, "attrs": {"size": 30}})).unwrap(); - assert!(close(text(&s, 0, t).runs[0].style.size_pt, 30.0), "the type inherits Basic Paragraph"); - let basic = doc(&s, 0).text_styles.basic.clone(); - s.execute("layer.select", json!({"layer": t.0})).unwrap(); - let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); - let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap())); - assert_eq!(doc(&s, i).text_styles.basic, basic); - s.set_active(i); - let c = s.execute("type.characterStyle.list", json!({"layer": id.0})).unwrap(); - let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0})).unwrap(); - assert_eq!((&c["current"]["characterOverride"], &p["current"]["paragraphOverride"]), (&json!(false), &json!(false)), "{c} {p}"); - s.execute("type.paragraphStyle.clearOverride", json!({"layer": id.0})).unwrap(); - s.execute("type.characterStyle.clearOverride", json!({"layer": id.0})).unwrap(); - assert!(close(text(&s, i, id).runs[0].style.size_pt, 30.0), "{}", text(&s, i, id).runs[0].style.size_pt); -} diff --git a/crates/engine-core/src/cmd/type_extra_cmds/tests.rs b/crates/engine-core/src/cmd/type_extra_cmds/tests.rs index 1bea6cbee5..8e9bd20bf0 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds/tests.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds/tests.rs @@ -594,68 +594,6 @@ fn type_attaches_to_a_path_and_releases_it() { assert!(matches!(text(&s, id).shape, TextShape::Path { .. })); } -/// #9114: type on a path follows its own path when the path is edited (Direct Selection's -/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names -/// it, an edit is one undo step, and an edit that leaves no path is refused. -#[test] -fn type_follows_its_path_when_the_path_is_edited() { - let mut s = session(8); - let id = text_layer(&mut s, "Hello path"); - s.edit("path", |doc, _| { - doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); - Ok(()) - }) - .unwrap(); - s.execute("type.attachToPath", json!({"start": 4})).unwrap(); - // In document space, the type path is where the work path was. - let path = crate::type_extra_cmds::type_path(text(&s, id)).unwrap(); - let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); - assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}"); - let listed = s.execute("path.list", json!({})).unwrap(); - assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}"); - // Swing the path's end to the right: the type now runs down and to the right. - let before = ink(&s, id); - let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap(); - assert_eq!(r["name"], "layer"); - let after = ink(&s, id); - assert!(after.width() > before.width() + 20, "{before:?} → {after:?}"); - assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept"); - // The work path it came from is untouched; Undo puts the type path back. - assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0); - assert!(s.undo()); - assert_eq!(ink(&s, id), before); - // An edit that would leave fewer than two points is refused and changes nothing. - assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err()); - assert_eq!(ink(&s, id), before); -} - -/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main -/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both. -#[test] -fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { - let mut s = session(8); - let id = text_layer(&mut s, "Hello path"); - s.edit("path", |doc, _| { - doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); - Ok(()) - }) - .unwrap(); - s.execute("type.attachToPath", json!({})).unwrap(); - let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]}); - s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap(); - let listed = s.execute("path.list", json!({})).unwrap(); - assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}"); - let type_path = |s: &Session| crate::type_extra_cmds::type_path(text(s, id)).unwrap(); - let before = type_path(&s); - let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor; - s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap(); - assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved"); - assert_eq!(type_path(&s), before, "the Type Path stays"); - s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap(); - assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved"); - assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays"); -} - /// An edit can't grow the Type Path past the cap `type.attachToPath` keeps. #[test] fn an_edited_type_path_keeps_the_knot_cap() { diff --git a/crates/engine-core/src/cmd/type_indexed_mode_tests.rs b/crates/engine-core/src/cmd/type_indexed_mode_tests.rs index a7d2d515d5..82abc98332 100644 --- a/crates/engine-core/src/cmd/type_indexed_mode_tests.rs +++ b/crates/engine-core/src/cmd/type_indexed_mode_tests.rs @@ -20,7 +20,7 @@ //! and [`an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states`] what happens to the //! states when an edit outside the session's coalesce group comes between the typing and the commit. -use super::type_cmds::{commits_as_selection, name_selection_commit, new_text_layer}; +use super::type_cmds::{commits_as_selection, new_text_layer}; use super::*; use photocraft_doc::text::{Orientation, TextShape}; @@ -63,14 +63,6 @@ fn mode(s: &Session) -> ColorMode { s.active().unwrap().doc.mode } -/// The Type tool's commit of the session's working layer in a document [`commits_as_selection`] -/// names: the Type Mask tools' conversion, in the session's one step, which keeps the name the step -/// was opened with. -fn commit(s: &mut Session, layer: u64) { - s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).unwrap(); - name_selection_commit(s); -} - fn text_layers(s: &Session) -> usize { s.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).count() } @@ -79,24 +71,6 @@ fn layers(s: &Session) -> usize { s.active().unwrap().doc.walk().len() } -/// The selection's coverage over the whole canvas, in document pixels. -fn coverage(s: &Session) -> Vec { - let d = s.active().unwrap().doc.clone(); - let b = d.bounds(); - let mut out = Vec::new(); - for y in b.y0..b.y1 { - for x in b.x0..b.x1 { - out.push(d.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))); - } - } - out -} - -/// The selection's bounds, as its corners. -fn selection_corners(s: &Session) -> Option<[i32; 4]> { - s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()).map(|r| [r.x0, r.y0, r.x1, r.y1]) -} - /// Every layer's pixels, quantised: what the commit must leave exactly as it was. fn pixels(s: &Session) -> Vec { let d = s.active().unwrap().doc.clone(); @@ -117,55 +91,6 @@ fn history(s: &Session) -> Vec { s.active().unwrap().history.entries() } -#[test] -fn committing_in_indexed_color_or_bitmap_leaves_the_glyphs_selected_and_no_layer() { - for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { - let mut s = make(); - let (steps, layers_before, pixels_before) = (history(&s).len(), layers(&s), pixels(&s)); - - // The tool's session: a type layer to edit and show while typing, as measured. - let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(text_layers(&s), 1, "{name}: typing happens on a layer the tool can show"); - - commit(&mut s, layer); - - assert_eq!(text_layers(&s), 0, "{name}: committing leaves no type layer"); - assert_eq!(layers(&s), layers_before, "{name}: the working layer went with it"); - assert!(s.active().unwrap().doc.selection.is_some(), "{name}: the glyphs are selected"); - let selected = s.active().unwrap().doc.selection.as_ref().unwrap(); - assert!(!selected.content_bounds().is_empty(), "{name}: the selection has a shape"); - assert!(coverage(&s).iter().any(|v| *v > 0.0), "{name}: the selected pixels are the glyphs'"); - assert_eq!(pixels(&s), pixels_before, "{name}: the commit paints nothing"); - - // One step for the whole session, named as Photoshop names it. - let h = history(&s); - assert_eq!(h.len(), steps + 1, "{name}: the session is one history state: {h:?}"); - assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: its name"); - - // And undoing that one state gives the document back as it was. - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none(), "{name}: undo takes the selection"); - assert_eq!(layers(&s), layers_before, "{name}: undo takes the whole session"); - assert_eq!(pixels(&s), pixels_before, "{name}: nothing else was changed"); - } -} - -#[test] -fn the_selection_is_the_glyph_shape_the_type_mask_of_the_same_text_makes() { - for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { - let mut s = make(); - let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); - commit(&mut s, layer); - let (got, got_bounds) = (coverage(&s), selection_corners(&s)); - - // The pin: the same text straight through the Type Mask command. - let mut pin = make(); - pin.execute("type.createSelection", typed(false)).unwrap(); - assert_eq!(got_bounds, selection_corners(&pin), "{name}: same selection bounds"); - assert_eq!(got, coverage(&pin), "{name}: same selection coverage"); - } -} - #[test] fn rgb_grayscale_cmyk_and_lab_keep_making_type_layers_at_every_depth() { for (id, want) in [("rgb", ColorMode::Rgb), ("gray", ColorMode::Grayscale), ("cmyk", ColorMode::Cmyk), ("lab", ColorMode::Lab)] { @@ -252,36 +177,3 @@ fn only_the_measured_horizontal_point_text_converts_in_these_modes() { assert!(!commits_as_selection(mode, &vertical), "{mode:?}: vertical text keeps its type layer"); } } - -/// An edit that does not carry the session's `coalesce` key ends its coalesce group - in the tool -/// that is the deliberately per-press Alt+arrow kerning step. The commit then makes a state of its -/// own, which is what the Type Mask tools' commit and the plain layer's rename do in the same -/// situation today; nothing is mis-named and nothing else moves. -#[test] -fn an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states() { - for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { - let mut s = make(); - let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); - // The stand-in for that kerning press: a real edit under no coalesce key. - s.execute("type.edit", json!({"layer": layer, "antialias": "sharp"})).unwrap(); - let before = history(&s); - assert_eq!(before.last().map(String::as_str), Some("Edit Type"), "{name}: the unkeyed edit is a state of its own"); - - commit(&mut s, layer); - - let h = history(&s); - assert_eq!(h.len(), before.len() + 1, "{name}: the commit is a further state once the group ended: {h:?}"); - assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: named for the type layer either way"); - assert_eq!(h[h.len() - 2].as_str(), "Edit Type", "{name}: the edit between them keeps its own name"); - assert_eq!(text_layers(&s), 0, "{name}: still no type layer is left"); - assert!(s.active().unwrap().doc.selection.is_some(), "{name}: still the glyphs are selected"); - - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none(), "{name}: one undo takes the conversion"); - assert_eq!(text_layers(&s), 1, "{name}: which brings the working layer back, as the mask tools' undo does"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(text_layers(&s), 1, "{name}: the next undo takes the unkeyed edit, not the session"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(text_layers(&s), 0, "{name}: and the third one takes the typing session"); - } -} diff --git a/crates/engine-core/src/cmd/type_spell_cmds.rs b/crates/engine-core/src/cmd/type_spell_cmds.rs index 70458c43ef..7540f21d9c 100644 --- a/crates/engine-core/src/cmd/type_spell_cmds.rs +++ b/crates/engine-core/src/cmd/type_spell_cmds.rs @@ -497,16 +497,6 @@ mod tests { assert_eq!(text_of(&s, id), "€b!"); assert!(s.execute("type.insertText", json!({"text": ""})).is_err()); } - - #[test] - fn insert_crlf_reports_caret_in_normalized_text() { - let (mut s, id) = session(""); - let inserted = s.execute("type.insertText", json!({"layer": id, "text": "x\r\ny"})).unwrap(); - - assert_eq!(inserted["caret"], 3); - assert_eq!(s.execute("type.info", json!({"layer": id})).unwrap()["text"], "x\ny"); - assert_eq!(s.execute("type.caret", json!({"layer": id, "index": inserted["caret"]})).unwrap()["index"], inserted["caret"]); - } } #[cfg(test)] diff --git a/crates/engine-core/src/cmd/type_vertical_history_name_tests.rs b/crates/engine-core/src/cmd/type_vertical_history_name_tests.rs index 8bec61111a..04ad1afa4e 100644 --- a/crates/engine-core/src/cmd/type_vertical_history_name_tests.rs +++ b/crates/engine-core/src/cmd/type_vertical_history_name_tests.rs @@ -45,27 +45,3 @@ fn horizontal_text_is_still_a_new_type_layer() { assert_eq!(create(params).0, ["New Type Layer"], "{what}"); } } - -/// The Type Mask tools' commands: a hidden working layer from `type.create`, then -/// `type.createSelection` removing it, all coalesced into the session's one step. -#[test] -fn a_type_mask_session_is_still_one_type_mask_state() { - for orientation in ["horizontal", "vertical"] { - let mut s = session(); - let before = entries(&s).len(); - let key = json!("type-mask-session"); - let created = json!({"text": "", "x": 150, "y": 40, "orientation": orientation, "coalesce": key}); - let layer = s.execute("type.create", created).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": layer, "visible": false, "coalesce": key})).unwrap(); - s.execute("type.edit", json!({"layer": layer, "text": "AB", "coalesce": key})).unwrap(); - s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "coalesce": key})).unwrap(); - assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}"); - } - // Without a layer, `type.createSelection` makes its text itself: the same one state. - for orientation in ["horizontal", "vertical"] { - let mut s = session(); - let before = entries(&s).len(); - s.execute("type.createSelection", json!({"text": "AB", "x": 150, "y": 40, "size": 48, "orientation": orientation})).unwrap(); - assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}, no layer"); - } -} diff --git a/crates/engine-core/src/param_schema/tests.rs b/crates/engine-core/src/param_schema/tests.rs index 2aee80015f..db0f96b363 100644 --- a/crates/engine-core/src/param_schema/tests.rs +++ b/crates/engine-core/src/param_schema/tests.rs @@ -20,35 +20,6 @@ fn keys(doc: &str) -> Vec { parse(doc).keys().into_iter().map(str::to_string).collect() } -/// The registry docs written in another notation (unquoted keys): not checked for unknown keys -/// until rewritten in the grammar. The list may only shrink. -const UNPARSED: &[&str] = &[ - "edit.presets.migratePresets", - "file.export.dataSetsAsFiles", - "file.import.variableDataSets", - "image.applyDataSet", - "image.trap", - "image.variables.dataSets", - "image.variables.define", - "timeline.create", - "timeline.setFrame", - "timeline.setProps", -]; - -#[test] -fn every_registry_doc_parses_and_renders_back_byte_for_byte() { - let mut unparsed = Vec::new(); - for c in specs() { - match Params::parse(c.params) { - Some(p) => assert_eq!(p.render(), c.params, "{}: the schema must reproduce the doc", c.id), - None => unparsed.push(c.id), - } - } - unparsed.sort_unstable(); - unparsed.dedup(); - assert_eq!(unparsed, UNPARSED); -} - #[test] fn no_registry_range_is_left_as_prose() { // A bound the parser didn't read would be prose a reader can't check (#7598). diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 68a071dd9d..8819224da2 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -192,6 +192,17 @@ mod type_postscript_font; mod undo_keeps_active_layer; mod unicode_colors; mod unsupported_smart_filters; +mod vector_in_actions_record; +mod vector_in_atn_cmds; +mod vector_in_automate_cmds; +mod vector_in_count_resize; +mod vector_in_file_cmds; +mod vector_in_layer_copy_cmds; +mod vector_in_param_schema; +mod vector_in_type_extra_cmds; +mod vector_in_type_indexed_mode; +mod vector_in_type_spell_cmds; +mod vector_in_type_vertical_history_name; mod vector_paste_options; mod wand_transparent_copy; mod working_rgb_profile; diff --git a/crates/engine/tests/it/vector_in_actions_record.rs b/crates/engine/tests/it/vector_in_actions_record.rs new file mode 100644 index 0000000000..ca3ccf2d06 --- /dev/null +++ b/crates/engine/tests/it/vector_in_actions_record.rs @@ -0,0 +1,57 @@ +//! Tests that run vector commands, moved from the engine-core `actions_record` tests: 1 test(s). + + +use photocraft_doc::LayerId; + +use serde_json::{json}; + +use photocraft_engine::{Session}; + + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + s +} + + +fn new_layer(s: &mut Session, name: &str) -> u64 { + s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap() +} + + +#[test] +fn selection_actions_keep_the_active_layer_as_their_source() { + let mut s = session(); + let raster = new_layer(&mut s, "Pixels"); + s.execute("actions.record", json!({"name": "Load pixels"})).unwrap(); + s.execute("select.loadSelection", json!({"channel": "transparency", "layer": raster})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let steps = s.execute("actions.get", json!({"action": "Load pixels"})).unwrap()["steps"].clone(); + assert_eq!(steps[0][1]["layer"], json!({"name": "Pixels"}), "missing layer loads merged pixels instead"); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + new_layer(&mut s, "Pixels"); + let played = s.execute("actions.play", json!({"action": "Load pixels"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!( + s.active().unwrap().doc.selection.as_ref().map(|mask| mask.content_bounds()).unwrap_or(photocraft_geom::Rect::EMPTY), + photocraft_geom::Rect::EMPTY, + "the empty source layer must not load the opaque merged document" + ); + + let type_id = s.execute("type.create", json!({"x": 2, "y": 20, "text": "I", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let type_name = s.active().unwrap().doc.layer(LayerId(type_id)).unwrap().name.clone(); + s.execute("actions.record", json!({"name": "Mask text"})).unwrap(); + s.execute("type.createSelection", json!({"layer": type_id, "removeLayer": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let steps = s.execute("actions.get", json!({"action": "Mask text"})).unwrap()["steps"].clone(); + assert_eq!(steps[0][1]["layer"], type_name, "without the source, replay cannot remove that type layer"); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "white"})).unwrap(); + new_layer(&mut s, "Spare"); + let replay_type = s.execute("type.create", json!({"x": 2, "y": 20, "text": "I", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + assert_ne!(replay_type, type_id); + let played = s.execute("actions.play", json!({"action": "Mask text"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(s.active().unwrap().doc.selection.as_ref().is_some_and(|mask| !mask.content_bounds().is_empty()), "replay selects the glyphs"); + assert!(s.active().unwrap().doc.layer(LayerId(replay_type)).is_none(), "replay removed the named source type layer"); +} diff --git a/crates/engine/tests/it/vector_in_atn_cmds.rs b/crates/engine/tests/it/vector_in_atn_cmds.rs new file mode 100644 index 0000000000..cc386a333b --- /dev/null +++ b/crates/engine/tests/it/vector_in_atn_cmds.rs @@ -0,0 +1,118 @@ +//! Tests that run vector commands, moved from the engine-core `atn_cmds` tests: 2 test(s). + +use craft_psd::atn::{self}; +use serde_json::{Value}; +use photocraft_engine::{Session}; +use photocraft_engine::atn_cmds::{PHOTOSHOP_STEP}; + +use photocraft_engine::actions_cmds::ActionStep; + +use photocraft_engine::actions_cmds::ActionsExt; + +use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + +use craft_psd::descriptor::{Descriptor, ReferenceItem, UnicodeString, Value as D}; + +use serde_json::json; + + +fn item(event: &str, label: &str, d: Option) -> AtnItem { + let event = match event.as_bytes() { + [a, b, c, dd] => AtnEvent::Code([*a, *b, *c, *dd]), + _ => AtnEvent::name(event), + }; + AtnItem { event, dictionary: label.as_bytes().to_vec(), descriptor: d, ..Default::default() } +} + + +fn b64(bytes: &[u8]) -> String { + photocraft_paint::tile::b64_encode(bytes) +} + + +#[test] +fn layer_comp_apply_imports_plays_and_undoes() { + let name = "合成 𠮷"; + let data = set_of("Comps", vec![("Apply", vec![item("applyComp", "Apply Layer Comp", Some(desc("null").with("null", name_ref("compsClass", name))))])]); + for depth in [8, 16, 32] { + let mut s = Session::new(); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("layerComp.apply", json!({"comp": name}))]); + + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("layerComp.new", json!({"name": "Other"})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let played = s.execute("actions.play", json!({"action": "Apply"})).unwrap(); + assert_eq!(played["ran"], 0, "{played}"); + assert!(played["failed"]["error"].as_str().unwrap().contains(name), "{played}"); + assert_eq!(*s.active().unwrap().doc, *before, "a missing comp must not apply another comp"); + + let comp = s.execute("layerComp.new", json!({"name": name})).unwrap()["comp"].clone(); + let layer = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"visible": false})).unwrap(); + s.execute("layerComp.new", json!({"name": "Hidden"})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Apply"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + assert!(s.active().unwrap().doc.layer(layer).unwrap().visible); + assert_eq!(json!(s.active().unwrap().doc.last_applied_comp), comp); + assert!(s.undo()); + assert!(!s.active().unwrap().doc.layer(layer).unwrap().visible); + assert!(s.redo()); + assert!(s.active().unwrap().doc.layer(layer).unwrap().visible); + } +} + + +#[test] +fn layer_comp_apply_unknown_references_are_kept_and_stop_playback() { + let references = [ + None, + Some(D::Integer(1)), + Some(D::Reference(vec![])), + Some(name_ref("Lyr ", "Comp 1")), + Some(class_ref("compsClass")), + Some(D::Reference(vec![ReferenceItem::Offset { class: class("compsClass"), offset: 1 }])), + Some(D::Reference(vec![ReferenceItem::Enumerated { class: class("compsClass"), type_id: code("Ordn"), value: code("unsupported") }])), + Some(D::Reference(vec![ + ReferenceItem::Name { class: class("compsClass"), name: UnicodeString::new_nul("Comp 1") }, + ReferenceItem::Name { class: class("Dcmn"), name: UnicodeString::new_nul("Other") }, + ])), + ]; + let items: Vec<_> = + references.into_iter().map(|reference| item("applyComp", "Apply Layer Comp", reference.map(|r| desc("null").with("null", r)))).collect(); + let data = set_of("Comps", vec![("Unknown", items.clone())]); + let mut s = Session::new(); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"].as_array().unwrap().len(), items.len()); + assert!(s.actions().list.actions()[0].steps.iter().all(|st| st.command == PHOTOSHOP_STEP)); + assert!(s.actions().list.actions()[0].disabled.is_empty()); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layerComp.new", json!({"name": "Comp 1"})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let played = s.execute("actions.play", json!({"action": "Unknown"})).unwrap(); + assert_eq!(played["ran"], 0, "{played}"); + assert!(played["failed"]["error"].as_str().unwrap().contains("Apply Layer Comp"), "{played}"); + assert_eq!(*s.active().unwrap().doc, *before); + let saved = s.execute("actions.save", json!({"set": "Comps"})).unwrap(); + let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let file = atn::parse(&bytes).unwrap(); + assert_eq!(file.actions[0].items.len(), items.len()); + for (saved, original) in file.actions[0].items.iter().zip(&items) { + assert_eq!(saved.event, original.event); + assert_eq!(saved.descriptor, original.descriptor); + } +} + + +fn set_of(name: &str, actions: Vec<(&str, Vec)>) -> String { + let file = AtnFile { + name: UnicodeString::new_nul(name), + expanded: false, + actions: actions.into_iter().map(|(n, items)| AtnAction { name: UnicodeString::new_nul(n), items, ..Default::default() }).collect(), + warnings: vec![], + ..Default::default() + }; + b64(&atn::write(&file).unwrap()) +} diff --git a/crates/engine/tests/it/vector_in_automate_cmds.rs b/crates/engine/tests/it/vector_in_automate_cmds.rs new file mode 100644 index 0000000000..5dbc657703 --- /dev/null +++ b/crates/engine/tests/it/vector_in_automate_cmds.rs @@ -0,0 +1,96 @@ +//! Tests that run vector commands, moved from the engine-core `automate_cmds` tests: 2 test(s). + +use photocraft_doc::{Layer, LayerContent}; +use serde_json::{json}; +use photocraft_engine::file_cmds::{file_name}; +use photocraft_engine::{EngineError, Session}; + + + +pub(super) fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-automate-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + + +#[test] +fn stacked_smart_object_holds_the_loaded_layers_at_its_top_level() { + // Like Photoshop, Load Files into Stack › Create Smart Object (Statistics without alignment) and + // Statistics with alignment embed one layer per file, bottom to top, with no wrapper group. + let dir = tmp("stack-top"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap(); + s.edit("texture", |doc, active| { + let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; + for k in 0..40 { + let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); + let source = photocraft_compose::flatten(&s.active().unwrap().doc); + let files: Vec = (0..3) + .map(|i| { + let path = format!("{dir}/img{i}.png"); + photocraft_engine::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap(); + path + }) + .collect(); + for align in [false, true] { + let mut s = Session::new(); + s.execute("file.scripts.statistics", json!({"mode": "median", "input": files, "align": align})).unwrap(); + let d = &s.active().unwrap().doc; + let LayerContent::Smart(so) = &d.layers[0].content else { panic!("not a smart object") }; + let photocraft_doc::SmartSource::Embedded { file_name, bytes } = &so.source else { panic!("not embedded") }; + let inner = photocraft_engine::smart_cmds::decode_source(file_name, bytes).unwrap(); + let names: Vec<&str> = inner.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["img0.png", "img1.png", "img2.png"], "align {align}"); + assert_eq!(photocraft_compose::flatten(d).px, source.px, "align {align}"); + } +} + + +/// #4671: Load Files into Stack's Attempt to Automatically Align Source Images runs Auto-Align +/// Layers on the loaded layers, then (with Create Smart Object) puts them in one smart object; +/// without the smart object they stay loose layers, selected. +#[test] +fn load_files_into_stack_aligns_before_the_smart_object() { + let dir = tmp("stack-align"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap(); + s.edit("texture", |doc, active| { + let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; + for k in 0..40 { + let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); + let files: Vec = (0..2) + .map(|i| { + let path = format!("{dir}/img{i}.png"); + photocraft_engine::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap(); + path + }) + .collect(); + let mut s = Session::new(); + let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true})).unwrap(); + assert_eq!(r["layers"], 2); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), 2, "loose layers"); + assert!(st.doc.layers.iter().all(|l| matches!(l.content, LayerContent::Raster(_)))); + assert_eq!(st.selected_layers().len(), 2, "Auto-Align ran on them all"); + let mut s = Session::new(); + s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true, "createSmartObject": true})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 1); + let LayerContent::Smart(_) = &d.layers[0].content else { panic!("not a smart object") }; + // A single file has nothing to align with: it just loads. + let mut s = Session::new(); + s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [files[0].clone()], "align": true})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); +} diff --git a/crates/engine/tests/it/vector_in_count_resize.rs b/crates/engine/tests/it/vector_in_count_resize.rs new file mode 100644 index 0000000000..3aef8fcf89 --- /dev/null +++ b/crates/engine/tests/it/vector_in_count_resize.rs @@ -0,0 +1,88 @@ +//! Tests that run vector commands, moved from the engine-core `count_resize` tests: 4 test(s). + + +use serde_json::{Value, json}; + + +use photocraft_engine::Session; + + +const POINT: [f64; 2] = [99.3, 99.7]; + + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": POINT[0], "y": POINT[1]})).unwrap(); + s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap(); + s +} + + +fn count_point(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.measurement.count_groups[0].points[0] +} + + +fn note(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.notes[0].position +} + + +#[test] +fn count_points_keep_their_coordinates() { + // The note at [100, 100] on the 600×400 canvas, where each command moves it. + let steps: [(&str, Value, [f64; 2]); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]), + ("image.imageRotation.90cw", json!({}), [300.0, 100.0]), + ("image.imageRotation.90ccw", json!({}), [100.0, 500.0]), + ("image.imageRotation.180", json!({}), [500.0, 300.0]), + ("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]), + ("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]), + ("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]), + ]; + for (cmd, p, moved) in steps { + let mut s = doc(); + let before = note(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(count_point(&s), POINT, "{cmd}"); + let n = note(&s); + assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}"); + s.undo(); + assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); + } +} + + +#[test] +fn all_three_in_a_row_leave_the_point_where_it_was() { + let mut s = doc(); + s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap(); + s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap(); + s.execute("image.imageRotation.90cw", json!({})).unwrap(); + assert_eq!(count_point(&s), POINT); +} + + +#[test] +fn crop_still_moves_count_points() { + let mut s = doc(); + s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); + assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); +} + + +#[test] +fn ruler_straighten_with_crop_moves_count_points_with_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + let (c, n) = (count_point(&s), note(&s)); + assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); +} diff --git a/crates/engine/tests/it/vector_in_file_cmds.rs b/crates/engine/tests/it/vector_in_file_cmds.rs new file mode 100644 index 0000000000..6a944a773c --- /dev/null +++ b/crates/engine/tests/it/vector_in_file_cmds.rs @@ -0,0 +1,51 @@ +//! Tests that run vector commands, moved from the engine-core `file_cmds` tests: 1 test(s). + +use photocraft_engine::Session; + +use photocraft_engine::EngineError; + +use photocraft_doc::{Layer, LayerContent}; + +use serde_json::json; + + +/// Two textured PNGs named a_base.png and b_shift.png (texture, so Auto-Align finds features). +fn two_files(dir: &std::path::Path) -> Result, Box> { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"}))?; + s.edit("texture", |doc, active| { + let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; + for k in 0..40 { + let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); + } + Ok(()) + })?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut paths = Vec::new(); + for name in ["a_base.png", "b_shift.png"] { + let path = dir.join(name).to_string_lossy().into_owned(); + photocraft_engine::file_cmds::save_doc(doc, &path, None)?; + paths.push(path); + } + Ok(paths) +} + + +/// The smart object keeps the first file's name with and without aligning; only the document's +/// name changes. +#[test] +fn the_smart_object_keeps_the_first_files_name() { + let dir = tempfile::tempdir().unwrap(); + let files = two_files(dir.path()).unwrap(); + for align in [false, true] { + let mut s = Session::new(); + s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": align, "createSmartObject": true})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.name, "Untitled-1", "align {align}"); + assert_eq!(st.path, None, "align {align}"); + assert_eq!(st.doc.layers.len(), 1, "align {align}"); + assert!(matches!(st.doc.layers[0].content, LayerContent::Smart(_)), "align {align}"); + assert_eq!(st.doc.layers[0].name, "a_base", "align {align}"); + } +} diff --git a/crates/engine/tests/it/vector_in_layer_copy_cmds.rs b/crates/engine/tests/it/vector_in_layer_copy_cmds.rs new file mode 100644 index 0000000000..a5722de57a --- /dev/null +++ b/crates/engine/tests/it/vector_in_layer_copy_cmds.rs @@ -0,0 +1,207 @@ +//! Tests that run vector commands, moved from the engine-core `layer_copy_cmds` tests: 5 test(s). + + +use photocraft_color::{ColorMode}; + +use photocraft_doc::{Document, LayerContent, LayerId}; + +use serde_json::{Value, json}; + + +use photocraft_engine::Session; + + +fn doc(s: &Session, i: usize) -> &Document { + &s.documents()[i].doc +} + + +fn copied(r: &Value) -> LayerId { + LayerId(r["layers"][0].as_u64().unwrap()) +} + + +/// The type layer `id` of document `i`. +fn text(s: &Session, i: usize, id: LayerId) -> &photocraft_doc::TextLayer { + match &doc(s, i).layer(id).unwrap().content { + LayerContent::Text(t) => t, + other => panic!("not type: {other:?}"), + } +} + + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() <= 1e-4 * b.abs().max(1.0) +} + + +/// Document 0 at 72 ppi with "Hello" in Paragraph Style 1 (24 pt) and "He" also in Character +/// Style 1 (24 pt, underlined); document 1 at 300 ppi, its own styles made by `dest`. +fn styled_type_docs(dest: impl FnOnce(&mut Session)) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 72})).unwrap(); + let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 100, "y": 100})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.paragraphStyle.new", json!({"attrs": {"size": 24}, "fromSelection": false, "apply": true, "layer": t})).unwrap(); + s.execute("type.characterStyle.new", json!({"attrs": {"size": 24, "underline": true}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]})) + .unwrap(); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 300})).unwrap(); + dest(&mut s); + s.set_active(0); + s.execute("layer.select", json!({"layer": t})).unwrap(); + (s, LayerId(t)) +} + + +/// The styles panel state of `range` in layer `id` of document 1. +fn styles_of(s: &mut Session, id: LayerId, range: [usize; 2]) -> (Value, Value) { + s.set_active(1); + let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": range})).unwrap(); + let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": range})).unwrap(); + (c, p) +} + + +/// #10500: type copied to a document of another resolution brings the styles it uses, as in +/// the reference application (measured with Duplicate Layer from 72 to 300 ppi): a style the +/// destination lacks arrives under its name, scaled like the text (24 pt → 5.76 pt), so the +/// copy has no override; it never takes over an unrelated destination style with the same id. +#[test] +fn copied_type_brings_its_styles_scaled() { + for paste in [false, true] { + let (mut s, _) = styled_type_docs(|s| { + s.execute("type.characterStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap(); + s.execute("type.paragraphStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap(); + }); + let id = if paste { + s.execute("edit.copy", json!({})).unwrap(); + s.set_active(1); + LayerId(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap()["layer"].as_u64().unwrap()) + } else { + copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()) + }; + assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76), "paste {paste}"); + let (c, p) = styles_of(&mut s, id, [0, 2]); + let names = |v: &Value| v["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap().to_string()).collect::>(); + assert_eq!(names(&c), ["None", "Unrelated", "Character Style 1"], "paste {paste}"); + assert_eq!(names(&p), ["Basic Paragraph", "Unrelated", "Paragraph Style 1"], "paste {paste}"); + let (cs, ps) = (&c["styles"][2], &p["styles"][2]); + assert!(close(cs["attrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{cs}"); + assert!(close(ps["characterAttrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{ps}"); + assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&cs["id"], &json!(false)), "paste {paste}"); + assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&ps["id"], &json!(false)), "paste {paste}"); + // The source keeps its 24 pt styles. + assert_eq!(doc(&s, 0).text_styles.character[0].attrs["size_pt"], json!(24.0)); + } +} + + +/// A destination that already has a style of the same name keeps its definition (24 pt), and +/// the copy, at 5.76 pt, shows a local override ("+"), as in the reference application. +#[test] +fn copied_type_uses_the_destinations_same_named_style() { + let (mut s, _) = styled_type_docs(|s| { + s.execute("type.characterStyle.new", json!({"name": "Filler", "fromSelection": false})).unwrap(); + s.execute("type.characterStyle.new", json!({"name": "Character Style 1", "attrs": {"size": 24, "underline": true}, "fromSelection": false})).unwrap(); + }); + let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()); + let (c, _) = styles_of(&mut s, id, [0, 2]); + assert_eq!(c["styles"].as_array().unwrap().len(), 3, "no second Character Style 1: {c}"); + let existing = &c["styles"][2]; + assert_eq!(existing["attrs"]["size_pt"], json!(24.0)); + assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&existing["id"], &json!(true))); + assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76)); +} + + +/// Duplicate Layer › New Document brings the styles the type uses (at the same size). +#[test] +fn type_duplicated_to_a_new_document_keeps_its_styles() { + let (mut s, t) = styled_type_docs(|_| {}); + let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap())); + s.set_active(i); + let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); + let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); + assert_eq!(c["styles"][1]["name"], "Character Style 1"); + assert_eq!(c["styles"][1]["attrs"]["size_pt"], json!(24.0)); + assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&c["styles"][1]["id"], &json!(false))); + assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&p["styles"][1]["id"], &json!(false))); + assert_eq!(text(&s, i, id).runs, text(&s, 0, t).runs); +} + + +/// Document 0 (RGB, 72 ppi) with "Hello" whose "He" is in Character Style 1 (red); document 1 +/// (CMYK, 72 ppi). The type layer is selected in document 0. +fn red_styled_type_docs() -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); + let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.characterStyle.new", json!({"attrs": {"color": "#ff0000"}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]})).unwrap(); + s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72, "mode": "cmyk"})).unwrap(); + s.set_active(0); + s.execute("layer.select", json!({"layer": t})).unwrap(); + (s, LayerId(t)) +} + + +/// The colour Character Style 1 of document `i` sets, and whether "He" of `id` overrides it. +fn style_color(s: &mut Session, i: usize, id: LayerId) -> (photocraft_color::Color, bool) { + s.set_active(i); + let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap(); + let style = c["styles"].as_array().unwrap().iter().find(|x| x["name"] == "Character Style 1").unwrap(); + (serde_json::from_value(style["attrs"]["color"].clone()).unwrap(), c["current"]["characterOverride"].as_bool().unwrap()) +} + + +/// Type copied to a document of another colour mode converts its run colours, and the style it +/// brings converts with the same transform: the run matches its style (no override), so a later +/// change to the style's colour still reaches it. Converting the document itself (Image › Mode, +/// Convert to Profile with and without dither) keeps its styles in step the same way. +#[test] +fn copied_type_styles_convert_their_colours_with_the_type() { + let (mut s, _) = red_styled_type_docs(); + let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap()); + let run = text(&s, 1, id).runs[0].style.color; + assert_eq!(run.mode, ColorMode::Cmyk, "the run converted"); + let (style, over) = style_color(&mut s, 1, id); + assert_eq!(style, run, "the copied style converted with the run"); + assert!(!over, "no false override"); + for (cmd, p) in [ + ("image.mode.cmyk", json!({})), + ("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": false})), + ("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": true})), + ("edit.convertToProfile", json!({"profile": "lab-d50"})), + ] { + let (mut s, t) = red_styled_type_docs(); + s.execute(cmd, p.clone()).unwrap(); + let run = text(&s, 0, t).runs[0].style.color; + assert_ne!(run.mode, ColorMode::Rgb, "{cmd} {p}: the run converted"); + let (style, over) = style_color(&mut s, 0, t); + assert_eq!(style, run, "{cmd} {p}: the style converted with the run"); + assert!(!over, "{cmd} {p}: no false override"); + } +} + + +/// Duplicate Layer › New Document keeps the source's Basic Paragraph: type that inherits its +/// size from it has no override there, and Clear Override leaves it as it was. +#[test] +fn type_duplicated_to_a_new_document_keeps_the_sources_basic_paragraph() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + let t = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap()); + s.execute("type.paragraphStyle.set", json!({"id": 0, "attrs": {"size": 30}})).unwrap(); + assert!(close(text(&s, 0, t).runs[0].style.size_pt, 30.0), "the type inherits Basic Paragraph"); + let basic = doc(&s, 0).text_styles.basic.clone(); + s.execute("layer.select", json!({"layer": t.0})).unwrap(); + let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap(); + let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap())); + assert_eq!(doc(&s, i).text_styles.basic, basic); + s.set_active(i); + let c = s.execute("type.characterStyle.list", json!({"layer": id.0})).unwrap(); + let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0})).unwrap(); + assert_eq!((&c["current"]["characterOverride"], &p["current"]["paragraphOverride"]), (&json!(false), &json!(false)), "{c} {p}"); + s.execute("type.paragraphStyle.clearOverride", json!({"layer": id.0})).unwrap(); + s.execute("type.characterStyle.clearOverride", json!({"layer": id.0})).unwrap(); + assert!(close(text(&s, i, id).runs[0].style.size_pt, 30.0), "{}", text(&s, i, id).runs[0].style.size_pt); +} diff --git a/crates/engine/tests/it/vector_in_param_schema.rs b/crates/engine/tests/it/vector_in_param_schema.rs new file mode 100644 index 0000000000..78bbedc352 --- /dev/null +++ b/crates/engine/tests/it/vector_in_param_schema.rs @@ -0,0 +1,43 @@ +//! Tests that run vector commands, moved from the engine-core `param_schema` tests: 1 test(s). + +use std::fmt::Write as _; + + +use photocraft_engine::param_schema::{Params}; + + +fn specs() -> &'static [photocraft_engine::commands::CommandSpec] { + photocraft_engine::install().unwrap(); + photocraft_engine::commands::command_specs() +} + + +/// The registry docs written in another notation (unquoted keys): not checked for unknown keys +/// until rewritten in the grammar. The list may only shrink. +const UNPARSED: &[&str] = &[ + "edit.presets.migratePresets", + "file.export.dataSetsAsFiles", + "file.import.variableDataSets", + "image.applyDataSet", + "image.trap", + "image.variables.dataSets", + "image.variables.define", + "timeline.create", + "timeline.setFrame", + "timeline.setProps", +]; + + +#[test] +fn every_registry_doc_parses_and_renders_back_byte_for_byte() { + let mut unparsed = Vec::new(); + for c in specs() { + match Params::parse(c.params) { + Some(p) => assert_eq!(p.render(), c.params, "{}: the schema must reproduce the doc", c.id), + None => unparsed.push(c.id), + } + } + unparsed.sort_unstable(); + unparsed.dedup(); + assert_eq!(unparsed, UNPARSED); +} diff --git a/crates/engine/tests/it/vector_in_type_extra_cmds.rs b/crates/engine/tests/it/vector_in_type_extra_cmds.rs new file mode 100644 index 0000000000..103b9222b2 --- /dev/null +++ b/crates/engine/tests/it/vector_in_type_extra_cmds.rs @@ -0,0 +1,98 @@ +//! Tests that run vector commands, moved from the engine-core `type_extra_cmds` tests: 2 test(s). + +use photocraft_doc::text::{TextShape}; +use photocraft_doc::vector::{Path, Subpath}; +use photocraft_doc::{LayerContent, LayerId, TextLayer}; +use serde_json::{json}; +use photocraft_engine::{Session}; +use photocraft_engine::type_extra_cmds::{type_path}; + + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 120, "depth": depth, "background": "white"})).unwrap(); + s +} + + +fn text_layer(s: &mut Session, text: &str) -> LayerId { + let r = s.execute("type.create", json!({"x": 20, "y": 70, "text": text, "size": 36, "color": "#000000"})).unwrap(); + LayerId(r["layer"].as_u64().unwrap()) +} + + +fn text(s: &Session, id: LayerId) -> &TextLayer { + match &s.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Text(t) => t, + c => panic!("not text: {}", c.kind_name()), + } +} + + +fn ink(s: &Session, id: LayerId) -> photocraft_geom::Rect { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds() +} + + +/// #9114: type on a path follows its own path when the path is edited (Direct Selection's +/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names +/// it, an edit is one undo step, and an edit that leaves no path is refused. +#[test] +fn type_follows_its_path_when_the_path_is_edited() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({"start": 4})).unwrap(); + // In document space, the type path is where the work path was. + let path = photocraft_engine::type_extra_cmds::type_path(text(&s, id)).unwrap(); + let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); + assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}"); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}"); + // Swing the path's end to the right: the type now runs down and to the right. + let before = ink(&s, id); + let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap(); + assert_eq!(r["name"], "layer"); + let after = ink(&s, id); + assert!(after.width() > before.width() + 20, "{before:?} → {after:?}"); + assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept"); + // The work path it came from is untouched; Undo puts the type path back. + assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0); + assert!(s.undo()); + assert_eq!(ink(&s, id), before); + // An edit that would leave fewer than two points is refused and changes nothing. + assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err()); + assert_eq!(ink(&s, id), before); +} + + +/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main +/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both. +#[test] +fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() { + let mut s = session(8); + let id = text_layer(&mut s, "Hello path"); + s.edit("path", |doc, _| { + doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])])); + Ok(()) + }) + .unwrap(); + s.execute("type.attachToPath", json!({})).unwrap(); + let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]}); + s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap(); + let listed = s.execute("path.list", json!({})).unwrap(); + assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}"); + let type_path = |s: &Session| photocraft_engine::type_extra_cmds::type_path(text(s, id)).unwrap(); + let before = type_path(&s); + let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor; + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap(); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved"); + assert_eq!(type_path(&s), before, "the Type Path stays"); + s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap(); + assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved"); + assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays"); +} diff --git a/crates/engine/tests/it/vector_in_type_indexed_mode.rs b/crates/engine/tests/it/vector_in_type_indexed_mode.rs new file mode 100644 index 0000000000..ac05bf0733 --- /dev/null +++ b/crates/engine/tests/it/vector_in_type_indexed_mode.rs @@ -0,0 +1,198 @@ +//! Tests that run vector commands, moved from the engine-core `type_indexed_mode` tests: 3 test(s). + +use photocraft_color::{ColorMode}; +use photocraft_doc::{LayerContent}; +use serde_json::{Value, json}; +use photocraft_engine::{Session}; +use photocraft_engine::cmd::{type_cmds::name_selection_commit}; + + +/// The typing session's coalesce key, as `ui-egui`'s `session_key` gives one. +const SESSION: &str = "type-session-12041"; + + +/// The text the tool commits, at a baseline inside every document used here. `coalesce` for the +/// tool's own calls (one step for the session), without it for a script's or the pin's. +fn typed(coalesce: bool) -> Value { + let mut p = json!({ "text": "Hi", "x": 20, "y": 80, "size": 48 }); + if coalesce { + p["coalesce"] = json!(SESSION); + } + p +} + + +/// A blank RGB document, to be converted to the mode under test. +fn blank() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 240, "height": 120, "background": "transparent"})).unwrap(); + s +} + + +fn indexed() -> Session { + let mut s = blank(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + assert_eq!(mode(&s), ColorMode::Indexed, "the setup made an Indexed Color document"); + s +} + + +fn bitmap() -> Session { + let mut s = blank(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({"method": "threshold", "frequency": 12, "shape": "diamond"})).unwrap(); + assert_eq!(mode(&s), ColorMode::Bitmap, "the setup made a Bitmap document"); + s +} + + +fn mode(s: &Session) -> ColorMode { + s.active().unwrap().doc.mode +} + + +/// The Type tool's commit of the session's working layer in a document [`commits_as_selection`] +/// names: the Type Mask tools' conversion, in the session's one step, which keeps the name the step +/// was opened with. +fn commit(s: &mut Session, layer: u64) { + s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).unwrap(); + name_selection_commit(s); +} + + +fn text_layers(s: &Session) -> usize { + s.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).count() +} + + +fn layers(s: &Session) -> usize { + s.active().unwrap().doc.walk().len() +} + + +/// The selection's coverage over the whole canvas, in document pixels. +fn coverage(s: &Session) -> Vec { + let d = s.active().unwrap().doc.clone(); + let b = d.bounds(); + let mut out = Vec::new(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + out.push(d.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))); + } + } + out +} + + +/// The selection's bounds, as its corners. +fn selection_corners(s: &Session) -> Option<[i32; 4]> { + s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()).map(|r| [r.x0, r.y0, r.x1, r.y1]) +} + + +/// Every layer's pixels, quantised: what the commit must leave exactly as it was. +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap().doc.clone(); + let b = d.bounds(); + let mut out = Vec::new(); + for (_, _, l) in d.walk() { + let Some(surface) = l.surface() else { continue }; + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + out.extend(surface.rgba(x, y).map(|v| (v * 255.0).round() as u8)); + } + } + } + out +} + + +fn history(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + + +#[test] +fn committing_in_indexed_color_or_bitmap_leaves_the_glyphs_selected_and_no_layer() { + for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { + let mut s = make(); + let (steps, layers_before, pixels_before) = (history(&s).len(), layers(&s), pixels(&s)); + + // The tool's session: a type layer to edit and show while typing, as measured. + let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(text_layers(&s), 1, "{name}: typing happens on a layer the tool can show"); + + commit(&mut s, layer); + + assert_eq!(text_layers(&s), 0, "{name}: committing leaves no type layer"); + assert_eq!(layers(&s), layers_before, "{name}: the working layer went with it"); + assert!(s.active().unwrap().doc.selection.is_some(), "{name}: the glyphs are selected"); + let selected = s.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(!selected.content_bounds().is_empty(), "{name}: the selection has a shape"); + assert!(coverage(&s).iter().any(|v| *v > 0.0), "{name}: the selected pixels are the glyphs'"); + assert_eq!(pixels(&s), pixels_before, "{name}: the commit paints nothing"); + + // One step for the whole session, named as Photoshop names it. + let h = history(&s); + assert_eq!(h.len(), steps + 1, "{name}: the session is one history state: {h:?}"); + assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: its name"); + + // And undoing that one state gives the document back as it was. + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none(), "{name}: undo takes the selection"); + assert_eq!(layers(&s), layers_before, "{name}: undo takes the whole session"); + assert_eq!(pixels(&s), pixels_before, "{name}: nothing else was changed"); + } +} + + +#[test] +fn the_selection_is_the_glyph_shape_the_type_mask_of_the_same_text_makes() { + for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { + let mut s = make(); + let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); + commit(&mut s, layer); + let (got, got_bounds) = (coverage(&s), selection_corners(&s)); + + // The pin: the same text straight through the Type Mask command. + let mut pin = make(); + pin.execute("type.createSelection", typed(false)).unwrap(); + assert_eq!(got_bounds, selection_corners(&pin), "{name}: same selection bounds"); + assert_eq!(got, coverage(&pin), "{name}: same selection coverage"); + } +} + + +/// An edit that does not carry the session's `coalesce` key ends its coalesce group - in the tool +/// that is the deliberately per-press Alt+arrow kerning step. The commit then makes a state of its +/// own, which is what the Type Mask tools' commit and the plain layer's rename do in the same +/// situation today; nothing is mis-named and nothing else moves. +#[test] +fn an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states() { + for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] { + let mut s = make(); + let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap(); + // The stand-in for that kerning press: a real edit under no coalesce key. + s.execute("type.edit", json!({"layer": layer, "antialias": "sharp"})).unwrap(); + let before = history(&s); + assert_eq!(before.last().map(String::as_str), Some("Edit Type"), "{name}: the unkeyed edit is a state of its own"); + + commit(&mut s, layer); + + let h = history(&s); + assert_eq!(h.len(), before.len() + 1, "{name}: the commit is a further state once the group ended: {h:?}"); + assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: named for the type layer either way"); + assert_eq!(h[h.len() - 2].as_str(), "Edit Type", "{name}: the edit between them keeps its own name"); + assert_eq!(text_layers(&s), 0, "{name}: still no type layer is left"); + assert!(s.active().unwrap().doc.selection.is_some(), "{name}: still the glyphs are selected"); + + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none(), "{name}: one undo takes the conversion"); + assert_eq!(text_layers(&s), 1, "{name}: which brings the working layer back, as the mask tools' undo does"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(text_layers(&s), 1, "{name}: the next undo takes the unkeyed edit, not the session"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(text_layers(&s), 0, "{name}: and the third one takes the typing session"); + } +} diff --git a/crates/engine/tests/it/vector_in_type_spell_cmds.rs b/crates/engine/tests/it/vector_in_type_spell_cmds.rs new file mode 100644 index 0000000000..49166036aa --- /dev/null +++ b/crates/engine/tests/it/vector_in_type_spell_cmds.rs @@ -0,0 +1,25 @@ +//! Tests that run vector commands, moved from the engine-core `type_spell_cmds` tests: 1 test(s). + +use serde_json::{json}; +use photocraft_engine::{Session}; + + use photocraft_engine::type_spell_cmds::{text}; + + + fn session(text: &str) -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 100, "background": "white"})).unwrap(); + let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": text, "size": 12})).unwrap(); + (s, r["layer"].as_u64().unwrap()) + } + + + #[test] + fn insert_crlf_reports_caret_in_normalized_text() { + let (mut s, id) = session(""); + let inserted = s.execute("type.insertText", json!({"layer": id, "text": "x\r\ny"})).unwrap(); + + assert_eq!(inserted["caret"], 3); + assert_eq!(s.execute("type.info", json!({"layer": id})).unwrap()["text"], "x\ny"); + assert_eq!(s.execute("type.caret", json!({"layer": id, "index": inserted["caret"]})).unwrap()["index"], inserted["caret"]); + } diff --git a/crates/engine/tests/it/vector_in_type_vertical_history_name.rs b/crates/engine/tests/it/vector_in_type_vertical_history_name.rs new file mode 100644 index 0000000000..48999cd577 --- /dev/null +++ b/crates/engine/tests/it/vector_in_type_vertical_history_name.rs @@ -0,0 +1,44 @@ +//! Tests that run vector commands, moved from the engine-core `type_vertical_history_name` tests: 1 test(s). + + +use serde_json::{json}; + + +use photocraft_engine::Session; + + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 300})).unwrap(); + s +} + + +fn entries(s: &Session) -> Vec { + s.active().unwrap().history.entries() +} + + +/// The Type Mask tools' commands: a hidden working layer from `type.create`, then +/// `type.createSelection` removing it, all coalesced into the session's one step. +#[test] +fn a_type_mask_session_is_still_one_type_mask_state() { + for orientation in ["horizontal", "vertical"] { + let mut s = session(); + let before = entries(&s).len(); + let key = json!("type-mask-session"); + let created = json!({"text": "", "x": 150, "y": 40, "orientation": orientation, "coalesce": key}); + let layer = s.execute("type.create", created).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": layer, "visible": false, "coalesce": key})).unwrap(); + s.execute("type.edit", json!({"layer": layer, "text": "AB", "coalesce": key})).unwrap(); + s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "coalesce": key})).unwrap(); + assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}"); + } + // Without a layer, `type.createSelection` makes its text itself: the same one state. + for orientation in ["horizontal", "vertical"] { + let mut s = session(); + let before = entries(&s).len(); + s.execute("type.createSelection", json!({"text": "AB", "x": 150, "y": 40, "size": 48, "orientation": orientation})).unwrap(); + assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}, no layer"); + } +}