From 3cbd7b155a2ac6833a4b33fca797e68898df33e4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 03:25:56 +0000 Subject: [PATCH] Engine split step 6: slot_access.py and its rewrite (slot fields to accessors, trait imports, doc links) scripts/engine_split/slot_access.py rewrites the slot fields to their accessors (Tracked presets deref through one more *), adds the trait imports, turns s.presets_changed() into presets::presets_changed(s) and points Session::method doc links at the trait methods. Its fix mode applies what cargo check reports; branch mode serves open branches and lists their edits to the moved methods. The definition-span helpers session_state.py uses move to rust_source.py so both scripts share them (session_state.py's output is unchanged). This commit is split plus the fix rounds against cargo check of engine-core, engine, ui-egui and automation (lib and tests). Part of #15710. --- apps/photocraft-cli/src/batch.rs | 3 +- apps/photocraft-web/src/preset_bridge.rs | 10 +- apps/photocraft-web/src/web.rs | 11 +- apps/photocraft/src/main.rs | 4 +- crates/automation/tests/it/agent_tasks.rs | 3 +- crates/automation/tests/it/read_roots.rs | 5 +- crates/automation/tests/it/renderer_save.rs | 1 + .../tests/it/smart_filter_authorization.rs | 3 +- crates/engine-core/src/action_history.rs | 5 +- crates/engine-core/src/cmd/actions_cmds.rs | 90 +-- .../src/cmd/actions_cmds/playback_tests.rs | 6 +- .../engine-core/src/cmd/actions_cmds/tests.rs | 266 ++++----- .../engine-core/src/cmd/actions_edit_cmds.rs | 84 +-- .../cmd/actions_edit_cmds/library_commands.rs | 29 +- .../library_commands/tests.rs | 72 +-- .../src/cmd/actions_edit_cmds/record_again.rs | 17 +- .../cmd/atn_cmds/artboard_section_tests.rs | 9 +- .../src/cmd/atn_cmds/automate_tests.rs | 11 +- crates/engine-core/src/cmd/atn_cmds/files.rs | 21 +- .../src/cmd/atn_cmds/frame_section_tests.rs | 9 +- .../src/cmd/atn_cmds/layer_list_tests.rs | 7 +- .../src/cmd/atn_cmds/layer_props_tests.rs | 3 +- .../src/cmd/atn_cmds/measurement_tests.rs | 9 +- .../src/cmd/atn_cmds/mode_change_tests.rs | 13 +- .../src/cmd/atn_cmds/path_tests.rs | 7 +- .../src/cmd/atn_cmds/recorded_tools_tests.rs | 17 +- .../src/cmd/atn_cmds/render_tests.rs | 7 +- .../src/cmd/atn_cmds/selection_tests.rs | 7 +- .../src/cmd/atn_cmds/stylize_tests.rs | 39 +- crates/engine-core/src/cmd/atn_cmds/tests.rs | 239 ++++---- crates/engine-core/src/cmd/automate_cmds.rs | 9 +- .../src/cmd/automate_cmds/tests.rs | 37 +- crates/engine-core/src/cmd/brush_cmds.rs | 3 +- .../engine-core/src/cmd/brush_preset_cmds.rs | 1 + .../engine-core/src/cmd/channel_cmds/tests.rs | 1 + crates/engine-core/src/cmd/color_cmds.rs | 109 ++-- .../engine-core/src/cmd/comps_cmds/tests.rs | 3 +- .../engine-core/src/cmd/contour_lib_cmds.rs | 58 +- .../src/cmd/document_preset_cmds.rs | 63 ++- crates/engine-core/src/cmd/edit_menu_cmds.rs | 11 +- .../src/cmd/edit_menu_cmds/presets.rs | 1 + .../src/cmd/edit_menu_cmds/tests.rs | 11 +- .../engine-core/src/cmd/export_preset_cmds.rs | 37 +- crates/engine-core/src/cmd/exr_cmds.rs | 1 + .../src/cmd/file_cmds/batch_run.rs | 39 +- crates/engine-core/src/cmd/file_cmds/open.rs | 3 +- .../src/cmd/file_cmds/open_as_smart_object.rs | 5 +- crates/engine-core/src/cmd/file_cmds/tests.rs | 82 +-- .../engine-core/src/cmd/gradient_fill_cmds.rs | 5 +- .../src/cmd/history_options_cmds.rs | 1 + crates/engine-core/src/cmd/layer_copy_cmds.rs | 3 +- .../cmd/layer_multi_cmds/tile_damage_tests.rs | 3 +- crates/engine-core/src/cmd/migrate_cmds.rs | 44 +- crates/engine-core/src/cmd/mode_cmds.rs | 5 +- crates/engine-core/src/cmd/mode_cmds/tests.rs | 7 +- .../engine-core/src/cmd/preset_import_cmds.rs | 31 +- crates/engine-core/src/cmd/print_cmds.rs | 18 +- .../engine-core/src/cmd/print_cmds/tests.rs | 26 +- crates/engine-core/src/cmd/retouch_cmds.rs | 1 + .../src/cmd/retouch_cmds/clone_sampling.rs | 6 +- .../retouch_cmds/clone_source_layer_tests.rs | 74 +-- .../engine-core/src/cmd/retouch_cmds/tests.rs | 13 +- crates/engine-core/src/cmd/selection_cmds.rs | 3 +- .../engine-core/src/cmd/smart_cmds/unpack.rs | 3 +- .../engine-core/src/cmd/smartselect_cmds.rs | 6 +- .../object_transparent_layer_tests.rs | 9 +- .../src/cmd/smartselect_cmds/tests.rs | 17 +- crates/engine-core/src/cmd/style_asl_cmds.rs | 38 +- crates/engine-core/src/cmd/swatch_cmds.rs | 82 +-- .../engine-core/src/cmd/swatch_cmds/tests.rs | 58 +- .../src/cmd/table/store/file_menu.rs | 3 +- .../src/cmd/transform_cmds/multi_tests.rs | 5 +- crates/engine-core/src/cmd/type_spell_cmds.rs | 9 +- crates/engine-core/src/display_color/tests.rs | 109 ++-- crates/engine-core/src/doc_path/tests.rs | 1 + crates/engine-core/src/doc_state.rs | 2 +- crates/engine-core/src/filters/tests.rs | 5 +- crates/engine-core/src/jobs.rs | 5 +- crates/engine-core/src/jobs/tests.rs | 3 +- crates/engine-core/src/layer_style.rs | 8 +- crates/engine-core/src/layer_style/tests.rs | 3 +- crates/engine-core/src/lib.rs | 4 +- crates/engine-core/src/prefs.rs | 9 +- crates/engine-core/src/prefs/cmds.rs | 21 +- crates/engine-core/src/prefs/saved.rs | 24 +- crates/engine-core/src/prefs/store.rs | 6 +- crates/engine-core/src/prefs/tests.rs | 14 +- crates/engine-core/src/preset_store.rs | 25 +- crates/engine-core/src/preset_store/tests.rs | 6 +- .../engine-core/src/presets/clone_source.rs | 27 +- crates/engine-core/src/presets/gradients.rs | 56 +- crates/engine-core/src/presets/patterns.rs | 30 +- crates/engine-core/src/presets/shapes.rs | 34 +- crates/engine-core/src/presets/shapes/csh.rs | 10 +- crates/engine-core/src/presets/styles.rs | 32 +- crates/engine-core/src/presets/swatches.rs | 12 +- crates/engine-core/src/presets/tests.rs | 108 ++-- crates/engine-core/src/presets/tools.rs | 26 +- crates/engine-core/src/proof_sim.rs | 36 +- .../examples/bench_content_aware_scale.rs | 1 + crates/engine/examples/bench_display.rs | 9 +- crates/engine/examples/content_aware_bench.rs | 1 + .../tests/global_state/spot_dot_gain.rs | 10 +- .../engine/tests/global_state/text_gamma.rs | 7 +- crates/engine/tests/it/actions_duplicate.rs | 45 +- crates/engine/tests/it/actions_panel_menu.rs | 43 +- .../engine/tests/it/actions_record_again.rs | 21 +- .../engine/tests/it/actions_single_history.rs | 48 +- .../tests/it/atn_adjustment_make_props.rs | 3 +- crates/engine/tests/it/atn_calculations.rs | 3 +- .../engine/tests/it/atn_classic_gradient.rs | 5 +- crates/engine/tests/it/atn_color_lookup.rs | 7 +- .../engine/tests/it/atn_content_aware_fill.rs | 11 +- .../tests/it/atn_crystallize_cell_size.rs | 9 +- crates/engine/tests/it/atn_dialog_filters.rs | 5 +- .../engine/tests/it/atn_direct_adjustments.rs | 21 +- crates/engine/tests/it/atn_layer_style.rs | 17 +- .../engine/tests/it/atn_mapped_identifiers.rs | 11 +- crates/engine/tests/it/atn_newer_events.rs | 31 +- .../engine/tests/it/atn_perspective_warp.rs | 5 +- crates/engine/tests/it/atn_reference_forms.rs | 11 +- .../engine/tests/it/atn_review_regressions.rs | 23 +- crates/engine/tests/it/atn_ripple_amount.rs | 9 +- crates/engine/tests/it/atn_selective_color.rs | 5 +- crates/engine/tests/it/atn_shape_blur.rs | 23 +- crates/engine/tests/it/atn_shear.rs | 3 +- crates/engine/tests/it/atn_stack_modes.rs | 5 +- crates/engine/tests/it/atn_stroke_width.rs | 9 +- crates/engine/tests/it/atn_type_path.rs | 7 +- crates/engine/tests/it/atn_v12.rs | 3 +- .../engine/tests/it/content_aware_fill_atn.rs | 13 +- crates/engine/tests/it/convert_profile_atn.rs | 17 +- crates/engine/tests/it/corpus_atn.rs | 7 +- .../tests/it/crop_delete_off_background.rs | 3 +- crates/engine/tests/it/csh_import.rs | 29 +- .../engine/tests/it/gaussian_edge_profile.rs | 3 +- .../tests/it/image_size_scale_styles_atn.rs | 11 +- crates/engine/tests/it/paste_style_options.rs | 11 +- .../engine/tests/it/vector_paste_options.rs | 15 +- crates/engine/tests/it/working_rgb_profile.rs | 28 +- crates/engine/tests/panic_hunt.rs | 3 +- crates/ui-egui/examples/camera_raw_bench.rs | 1 + crates/ui-egui/examples/flat_open_bench.rs | 3 +- crates/ui-egui/examples/interactive_bench.rs | 1 + crates/ui-egui/examples/large_file_bench.rs | 1 + crates/ui-egui/examples/large_image_bench.rs | 1 + crates/ui-egui/examples/lasso_bench.rs | 1 + crates/ui-egui/examples/layout_bench.rs | 1 + crates/ui-egui/examples/perf_scenarios.rs | 1 + crates/ui-egui/src/alt_click_tests.rs | 3 +- crates/ui-egui/src/app/clipboard_tests.rs | 3 +- crates/ui-egui/src/app/files.rs | 3 +- crates/ui-egui/src/app/framework.rs | 3 +- .../src/app/framework/catalog_tests.rs | 5 +- crates/ui-egui/src/canvas.rs | 5 +- .../ui-egui/src/canvas/background_redraw.rs | 3 +- .../src/canvas/background_redraw/gpu_tests.rs | 17 +- crates/ui-egui/src/canvas/channel_view.rs | 5 +- crates/ui-egui/src/canvas/display.rs | 13 +- crates/ui-egui/src/canvas/filter_preview.rs | 5 +- .../src/canvas/filter_preview/tests.rs | 5 +- crates/ui-egui/src/canvas/paint_mouse.rs | 1 + crates/ui-egui/src/canvas/strokes.rs | 5 +- crates/ui-egui/src/canvas/tabs_tests.rs | 3 +- crates/ui-egui/src/canvas/tests.rs | 16 +- crates/ui-egui/src/color_panel_tests.rs | 3 +- crates/ui-egui/src/control/tests.rs | 13 +- crates/ui-egui/src/dialogs/adjust_editors.rs | 3 +- .../src/dialogs/camera_raw_ui/convert.rs | 3 +- .../src/dialogs/camera_raw_ui/filmstrip.rs | 3 +- .../dialogs/camera_raw_ui/identity_tests.rs | 1 + .../ui-egui/src/dialogs/camera_raw_ui/open.rs | 1 + crates/ui-egui/src/dialogs/color_picker_ui.rs | 3 +- crates/ui-egui/src/dialogs/color_range_ui.rs | 7 +- .../dialogs/discard_ui/tests/jpeg_tests.rs | 3 +- crates/ui-egui/src/dialogs/export_dialog.rs | 8 +- .../src/dialogs/export_dialog/tests.rs | 1 + .../ui-egui/src/dialogs/file_forms/tests.rs | 5 +- .../src/dialogs/file_ui/custom_paper_tests.rs | 3 +- crates/ui-egui/src/dialogs/file_ui/tests.rs | 11 +- crates/ui-egui/src/dialogs/filter_dialog.rs | 9 +- .../ui-egui/src/dialogs/filter_dialog/rows.rs | 5 +- .../src/dialogs/filter_dialog/tests.rs | 21 +- crates/ui-egui/src/dialogs/layer_style.rs | 7 +- .../src/dialogs/layer_style/contour.rs | 5 +- .../ui-egui/src/dialogs/layer_style/tests.rs | 3 +- crates/ui-egui/src/dialogs/new_doc_ui.rs | 8 +- .../ui-egui/src/dialogs/new_doc_ui/tests.rs | 11 +- crates/ui-egui/src/dialogs/open_prompt.rs | 5 +- .../src/dialogs/preset_group_prompt.rs | 3 +- .../src/dialogs/preset_group_prompt/tests.rs | 7 +- crates/ui-egui/src/dialogs/screen_picker.rs | 3 +- crates/ui-egui/src/dock/tests.rs | 1 + crates/ui-egui/src/file_dialog/tests.rs | 7 +- crates/ui-egui/src/file_open/tests.rs | 5 +- crates/ui-egui/src/gpu_status.rs | 5 +- .../src/healing_indexed_alert_tests.rs | 3 +- crates/ui-egui/src/home_recent_ui.rs | 1 + crates/ui-egui/src/i18n/live_tests.rs | 1 + crates/ui-egui/src/input/shortcut_dispatch.rs | 5 +- .../src/input/shortcut_dispatch/tests.rs | 7 +- crates/ui-egui/src/jobs_ui/tests.rs | 1 + crates/ui-egui/src/last_brush.rs | 2 +- crates/ui-egui/src/marquee_tests.rs | 3 +- crates/ui-egui/src/menu_floor_trials.rs | 3 +- crates/ui-egui/src/menus/facts.rs | 9 +- crates/ui-egui/src/menus/state.rs | 3 +- crates/ui-egui/src/menus/tests.rs | 3 +- .../menus/view_cmds/fit_image_sticky_tests.rs | 1 + crates/ui-egui/src/menus/view_cmds/tests.rs | 13 +- crates/ui-egui/src/menus/workspace_ui.rs | 5 +- crates/ui-egui/src/monitor_status.rs | 51 +- crates/ui-egui/src/new_doc_remember_tests.rs | 12 +- crates/ui-egui/src/panels/actions.rs | 33 +- crates/ui-egui/src/panels/actions/dialogs.rs | 7 +- .../src/panels/actions/drag_drop_tests.rs | 9 +- crates/ui-egui/src/panels/actions/files.rs | 3 +- .../ui-egui/src/panels/actions/files_tests.rs | 13 +- crates/ui-egui/src/panels/actions/library.rs | 7 +- .../src/panels/actions/library_tests.rs | 5 +- crates/ui-egui/src/panels/actions/menu.rs | 7 +- .../ui-egui/src/panels/actions/menu_item.rs | 7 +- .../ui-egui/src/panels/actions/menu_tests.rs | 17 +- .../src/panels/actions/panel_menu_tests.rs | 13 +- crates/ui-egui/src/panels/actions/playback.rs | 5 +- .../src/panels/actions/playback_tests.rs | 9 +- .../src/panels/actions/record_again.rs | 5 +- .../src/panels/actions/record_again_tests.rs | 25 +- crates/ui-egui/src/panels/actions/runner.rs | 19 +- .../src/panels/actions/runner_tests.rs | 59 +- .../ui-egui/src/panels/actions/stop_tests.rs | 35 +- crates/ui-egui/src/panels/actions/tests.rs | 25 +- .../src/panels/channels_panel/tests.rs | 7 +- crates/ui-egui/src/panels/layers_tree.rs | 1 + crates/ui-egui/src/panels/preset_browser.rs | 17 +- .../src/panels/preset_browser/tests.rs | 3 +- .../src/panels/preset_panels/clone_offsets.rs | 3 +- .../preset_panels/clone_offsets/tests.rs | 17 +- .../src/panels/preset_panels/clone_source.rs | 3 +- .../src/panels/preset_panels/tool_presets.rs | 3 +- crates/ui-egui/src/panels/swatches_ui.rs | 36 +- .../src/panels/type_panels_ui/spelling.rs | 3 +- crates/ui-egui/src/prefs/prefs_ui/save.rs | 2 + .../prefs/prefs_ui/shortcut_capture_tests.rs | 1 + .../ui-egui/src/prefs/prefs_ui/shortcuts.rs | 3 +- crates/ui-egui/src/prefs/prefs_ui/startup.rs | 1 + crates/ui-egui/src/prefs/prefs_ui/tests.rs | 1 + crates/ui-egui/src/preset_files_ui.rs | 3 +- crates/ui-egui/src/profile_open_tests.rs | 5 +- .../src/toolbar_custom_group_layout_tests.rs | 1 + crates/ui-egui/src/tools/analysis/mod.rs | 3 +- crates/ui-egui/src/tools/analysis_ui.rs | 3 +- crates/ui-egui/src/tools/crop_presets.rs | 9 +- crates/ui-egui/src/tools/crop_ui/tests.rs | 3 +- crates/ui-egui/src/tools/gradient_ui/bar.rs | 3 +- .../ui-egui/src/tools/gradient_ui/editor.rs | 3 +- crates/ui-egui/src/tools/gradient_ui/tests.rs | 5 +- crates/ui-egui/src/tools/object_finder.rs | 7 +- crates/ui-egui/src/tools/retouch_ui.rs | 5 +- .../ui-egui/src/tools/retouch_ui/bar/heal.rs | 3 +- crates/ui-egui/src/tools/shape_options.rs | 7 +- .../ui-egui/src/tools/transform_tool/tests.rs | 11 +- .../src/tools/type_tool/canvas_tests.rs | 1 + .../type_tool/vertical_align_buttons_tests.rs | 1 + crates/ui-egui/src/tools/vector_ui/options.rs | 7 +- .../src/tools/vector_ui/paint_tests.rs | 3 +- .../src/tools/vector_ui/pen_resume_tests.rs | 13 +- crates/ui-egui/src/transform_fx_tests.rs | 3 +- crates/ui-egui/src/transform_undo_tests.rs | 5 +- crates/ui-egui/tests/it/actions_duplicate.rs | 13 +- crates/ui-egui/tests/it/actions_panel_menu.rs | 5 +- .../ui-egui/tests/it/gpu_tests/canvas_16f.rs | 1 + .../tests/it/gpu_tests/display_shadows.rs | 3 +- crates/ui-egui/tests/it/layout_perf.rs | 1 + crates/ui-egui/tests/it/tone_targets.rs | 7 +- crates/ui-egui/tests/it/workspace_presets.rs | 1 + scripts/engine_split/rust_source.py | 69 +++ scripts/engine_split/session_state.py | 63 +-- scripts/engine_split/slot_access.py | 525 ++++++++++++++++++ 279 files changed, 2791 insertions(+), 1924 deletions(-) create mode 100644 scripts/engine_split/slot_access.py diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index 1e7ba9ef6d..975e12b70c 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use std::io::Write; use std::path::{Path, PathBuf}; @@ -132,7 +133,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> } // Steps that play another action find it in the set; the session's playback stack // stops an action that calls itself. - h.session.actions.list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new())); + h.session.actions_mut().list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new())); h.open_with_approval(input, a.approve_high_memory)?; for (id, p) in &actions { if photocraft_engine::actions_cmds::shell_view_command(id) diff --git a/apps/photocraft-web/src/preset_bridge.rs b/apps/photocraft-web/src/preset_bridge.rs index 738489217b..bfebbce718 100644 --- a/apps/photocraft-web/src/preset_bridge.rs +++ b/apps/photocraft-web/src/preset_bridge.rs @@ -1,5 +1,9 @@ //! Synchronous engine boundary for asynchronous browser storage. No browser handles cross the //! engine's `Send` boundary. Byte buffers are shared with the single in-flight transaction. +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::preset_store::PresetStoreExt; +use photocraft_engine::actions_cmds::ActionsExt; use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex, MutexGuard}; @@ -534,7 +538,7 @@ mod tests { bridge.load_action_keys(2, keys.clone()); let (session, warnings) = session(bridge.clone()); assert!(!warnings.is_empty()); - assert!(session.actions.list.actions().is_empty()); + assert!(session.actions().list.actions().is_empty()); assert!(session.tools.presets.iter().any(|preset| preset.name == "Browser seam brush")); assert_eq!(bridge.committed_action_keys(), None); assert_eq!(bridge.read(ACTIONS_FILE, 1024).unwrap(), malformed); @@ -750,7 +754,7 @@ mod tests { let (mut loaded, _) = session(b); loaded.load_prefs_json(&prefs).unwrap(); assert_eq!(loaded.tools.presets, s.tools.presets); - assert_eq!(loaded.presets.gradients, s.presets.gradients); - assert!(loaded.presets.gradients.iter().any(|g| g.name == "Browser gradients")); + assert_eq!(loaded.presets().gradients, s.presets().gradients); + assert!(loaded.presets().gradients.iter().any(|g| g.name == "Browser gradients")); } } diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs index 3010fd0e2f..44d1b91b71 100644 --- a/apps/photocraft-web/src/web.rs +++ b/apps/photocraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The browser shell: web `Services`, drag-and-drop, and the eframe web runner. +use photocraft_engine::actions_cmds::ActionsExt; use std::cell::Cell; use std::collections::{HashMap, HashSet}; use std::rc::Rc; @@ -100,11 +101,11 @@ pub fn start() { let served: Served = Arc::default(); load_font_manifest(served.clone(), cc.egui_ctx.clone()); let (session, warnings) = crate::preset_bridge::session(presets.clone()); - let actions_revision = session.actions.list.revision(); + let actions_revision = session.actions().list.revision(); preset_warnings.extend(warnings); let drag = listen_drag(&pen_target); let mut services = services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag)); - let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.actions().is_empty())); + let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions().list.actions().is_empty())); services.load_prefs = Some(Box::new(move || initial.take().unwrap_or_else(stored_preferences))); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services); if !preset_warnings.is_empty() { @@ -381,11 +382,11 @@ struct WebShell { impl WebShell { fn save_presets(&mut self, ctx: &egui::Context) { let session = &self.app.session; - if self.actions_revision != session.actions.list.revision() { + if self.actions_revision != session.actions().list.revision() { // The engine can reject an oversized definition before calling the backend. // Never stage that edit's keys with the last successfully queued definitions. - self.presets.verify_action_definitions(&session.actions); - self.actions_revision = session.actions.list.revision(); + self.presets.verify_action_definitions(session.actions()); + self.actions_revision = session.actions().list.revision(); } let prefs_revision = session.prefs.rev(); if self.prefs_revision != Some(prefs_revision) { diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 845b94bdc0..cbe7460912 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -62,6 +62,8 @@ mod tablet; mod ui_state; mod window_frame; +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::print_cmds::PrintExt; use photocraft_engine::Session; use photocraft_ui_egui::PhotocraftApp; use photocraft_ui_egui::Prefix; @@ -575,7 +577,7 @@ fn main() -> eframe::Result { #[cfg(target_os = "linux")] let session = { let mut session = Session::new(); - session.print_spooler = print_portal::spooler(); + *session.print_spooler_mut() = print_portal::spooler(); session }; #[cfg(not(target_os = "linux"))] diff --git a/crates/automation/tests/it/agent_tasks.rs b/crates/automation/tests/it/agent_tasks.rs index c492506782..58d0823ad7 100644 --- a/crates/automation/tests/it/agent_tasks.rs +++ b/crates/automation/tests/it/agent_tasks.rs @@ -3,6 +3,7 @@ //! Each task uses only MCP tools (`doc_*`, `command_run`) the way an agent would, and checks the //! outcome through `doc_inspect`, `document.pixel` or the exported files, never engine internals. +use photocraft_engine::actions_cmds::ActionsExt; use std::io::Write; use photocraft_automation::{AuthorizedWorkspace, PhotocraftMcp}; @@ -330,7 +331,7 @@ async fn agent_play_refuses_a_recorded_file_open() { use photocraft_engine::actions_cmds::ActionStep; headless .session - .actions + .actions_mut() .list .push(photocraft_engine::actions_cmds::Action { name: "Open".into(), diff --git a/crates/automation/tests/it/read_roots.rs b/crates/automation/tests/it/read_roots.rs index 214891fea8..420bddc342 100644 --- a/crates/automation/tests/it/read_roots.rs +++ b/crates/automation/tests/it/read_roots.rs @@ -1,5 +1,6 @@ //! Real-document regressions for ordered read roots and independent write authority. +use photocraft_engine::actions_cmds::ActionsExt; use std::path::{Path, PathBuf}; use photocraft_automation::{AuthorizedWorkspace, Headless, files}; @@ -286,8 +287,8 @@ fn multiple_roots_do_not_grant_ambient_commands_or_nested_action_file_access() { let error = headless.command_run("file.saveACopy", json!({"path": target})).unwrap_err().to_string(); assert!(error.contains("ambient filesystem paths"), "{error}"); // A writable destination still cannot be reached through an ambient engine command. - headless.session.actions.list.push(Action::new("Write work", vec![ActionStep::new("file.saveACopy", json!({"path": target}))])).unwrap(); - headless.session.actions.list.push(Action::new("Nested write", vec![ActionStep::new("actions.play", json!({"action": "Write work"}))])).unwrap(); + headless.session.actions_mut().list.push(Action::new("Write work", vec![ActionStep::new("file.saveACopy", json!({"path": target}))])).unwrap(); + headless.session.actions_mut().list.push(Action::new("Nested write", vec![ActionStep::new("actions.play", json!({"action": "Write work"}))])).unwrap(); let played = headless.command_run("actions.play", json!({"action": "Nested write"})).unwrap(); assert!(played["failed"].to_string().contains("ambient filesystem paths"), "{played}"); assert_eq!(snapshot(&mut headless), before); diff --git a/crates/automation/tests/it/renderer_save.rs b/crates/automation/tests/it/renderer_save.rs index 7fef7793fa..3b9e2ba71b 100644 --- a/crates/automation/tests/it/renderer_save.rs +++ b/crates/automation/tests/it/renderer_save.rs @@ -1,6 +1,7 @@ //! A failed renderer-aware save must never replace the previous file, and closing a document //! must release its renderer caches. +use photocraft_engine::color_cmds::ColorExt; use std::fs; use std::sync::{Arc, Mutex}; diff --git a/crates/automation/tests/it/smart_filter_authorization.rs b/crates/automation/tests/it/smart_filter_authorization.rs index 2ad83f4bba..557d478039 100644 --- a/crates/automation/tests/it/smart_filter_authorization.rs +++ b/crates/automation/tests/it/smart_filter_authorization.rs @@ -1,4 +1,5 @@ //! Stored smart-filter parameters must not grant automation ambient filesystem access. +use photocraft_engine::actions_cmds::ActionsExt; use std::path::Path; use std::sync::Arc; @@ -44,7 +45,7 @@ fn action_playback_cannot_hide_a_smart_filter_path_edit() { let (mut h, layer) = f.setup(false); let doc = h.session.active().unwrap().doc.clone(); h.session - .actions + .actions_mut() .list .push(Action::new( "edit filter", diff --git a/crates/engine-core/src/action_history.rs b/crates/engine-core/src/action_history.rs index fafb80c7ba..2f5714884d 100644 --- a/crates/engine-core/src/action_history.rs +++ b/crates/engine-core/src/action_history.rs @@ -341,6 +341,7 @@ pub fn finish_pending_history(s: &mut Session) { #[cfg(test)] mod tests { + use crate::color_cmds::ColorExt; /// Batch 16 review: a kept clone can't reopen a scope its continuation already resumed and /// finished, even with the document and history unchanged. #[test] @@ -396,10 +397,10 @@ mod tests { json!({"path":"colorSettings.intent","value":"perceptual","values":{"actions.createSingleHistoryState":!single}}), ] { let before = s.prefs().clone(); - let color = s.color.settings.clone(); + let color = s.color().settings.clone(); assert!(s.execute("prefs.set", params).is_err()); assert_eq!(s.prefs(), &before); - assert_eq!(s.color.settings, color); + assert_eq!(s.color().settings, color); } for params in [json!({"path":"actions.createSingleHistoryState"}), json!({"path":"actions"}), json!({})] { assert_eq!(s.execute("prefs.reset", params).is_err(), !single); diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index 5815d7b2a3..66543cd1d6 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -47,7 +47,7 @@ pub(crate) fn list_error(cmd: &str, error: ActionListError) -> EngineError { pub(crate) fn note_automation_edit(s: &mut Session, idx: usize) { if s.authorize.is_some() { // An index past the end is a stale mark: there is no action to flag. - let _ = s.actions.list.set_automation(idx, true); + let _ = s.actions_mut().list.set_automation(idx, true); } } @@ -68,7 +68,7 @@ pub(crate) fn note_step_origin(s: &mut Session, automation: bool, id: &str, para && recorded(id, params) && let Some((_, idx)) = s.recording.target { - let _ = s.actions.list.set_automation(idx, true); + let _ = s.actions_mut().list.set_automation(idx, true); } } @@ -230,7 +230,7 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> { if s.recording.playing > 0 && s.recording.playback_stack.is_empty() { return Err(bad("actions.play", "an action is already playing")); } - let list = s.actions.playable(); + let list = s.actions().playable(); let idx = resolve(list.actions(), p, "actions.play")?; // Every stored step of the call is charged to the playback tree (run, disabled or skipped), // so refuse a call whose steps no longer fit before copying it: repeated calls to a large @@ -242,7 +242,7 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> { } let action = list.action(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; // The recording's index is into the user's list, which a Batch's called actions stand in for. - let records_it = s.actions.called.is_none() && s.recording.target.is_some_and(|(_, i)| i == idx); + let records_it = s.actions().called.is_none() && s.recording.target.is_some_and(|(_, i)| i == idx); if s.recording.playback_stack.iter().any(|name| name == &action.name) || records_it { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); } @@ -495,14 +495,14 @@ fn from_step(p: &Value, len: usize) -> Result { } fn list(s: &mut Session, _p: &Value) -> Result { - let actions: Vec = s.actions.list.actions().iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); - let recording = s.recording.target.and_then(|(_, i)| s.actions.list.action(i).map(|a| a.name.clone())); + let actions: Vec = s.actions().list.actions().iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); + let recording = s.recording.target.and_then(|(_, i)| s.actions().list.action(i).map(|a| a.name.clone())); Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording, "toolRecording": s.recording.record_tools})) } fn get(s: &mut Session, p: &Value) -> Result { - let idx = resolve(s.actions.list.actions(), p, "actions.get")?; - let action = &s.actions.list.actions()[idx]; + let idx = resolve(s.actions().list.actions(), p, "actions.get")?; + let action = &s.actions().list.actions()[idx]; let steps: Vec = action.steps.iter().map(|step| json!([step.command, step.params])).collect(); Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled, "dialogs": action.dialogs, "set": action.set, "color": action.color.name()})) } @@ -515,7 +515,7 @@ fn record(s: &mut Session, p: &Value) -> Result { return Err(bad("actions.record", "already recording; stop first")); } let idx = if p.get("action").is_some() { - resolve(s.actions.list.actions(), p, "actions.record")? + resolve(s.actions().list.actions(), p, "actions.record")? } else { let name = match p.get("name") { None | Some(Value::Null) => None, @@ -531,14 +531,14 @@ fn record(s: &mut Session, p: &Value) -> Result { Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), }; - let name = name.unwrap_or_else(|| s.actions.list.unique_name("")); + let name = name.unwrap_or_else(|| s.actions().list.unique_name("")); // `push`, not `new_action`: an existing set keeps its exact name, which `new_action` would trim. - s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }).map_err(|e| list_error("actions.record", e))? + s.actions_mut().list.push(Action { set, ..Action::new(name, Vec::new()) }).map_err(|e| list_error("actions.record", e))? }; s.recording.target = Some((s.journal.len(), idx)); note_automation_edit(s, idx); s.recording.take = s.recording.take.wrapping_add(1); - let name = s.actions.list.action(idx).map(|a| a.name.clone()).unwrap_or_default(); + let name = s.actions().list.action(idx).map(|a| a.name.clone()).unwrap_or_default(); Ok(json!({"action": name, "index": idx})) } @@ -559,19 +559,19 @@ pub fn pending_steps(s: &Session, action: usize) -> impl Iterator Result<()> { let Some((_, idx)) = s.recording.target else { return Ok(()) }; - if s.actions.list.action(idx).is_none() { + if s.actions().list.action(idx).is_none() { return Err(bad("actions.stop", "the action being recorded no longer exists")); } let steps = fold_recorded_nudges(pending_steps(s, idx).cloned()); s.recording.target = Some((s.journal.len(), idx)); if !steps.is_empty() { - let first = s.actions.list.step_count(idx); + let first = s.actions().list.step_count(idx); let with_dialog: Vec = steps.iter().enumerate().filter(|(_, (id, _))| RECORDED_WITH_DIALOG.contains(&id.as_str())).map(|(i, _)| first + i).collect(); let stop = |e: ActionListError| list_error("actions.stop", e); - s.actions.list.append_recorded(idx, steps.into_iter().map(ActionStep::from)).map_err(stop)?; + s.actions_mut().list.append_recorded(idx, steps.into_iter().map(ActionStep::from)).map_err(stop)?; for step in with_dialog { - s.actions.list.set_dialog(idx, step, true).map_err(stop)?; + s.actions_mut().list.set_dialog(idx, step, true).map_err(stop)?; } } Ok(()) @@ -634,7 +634,7 @@ fn stop(s: &mut Session, _p: &Value) -> Result { }; flush_recording(s)?; s.recording.target = None; - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; Ok(json!({"action": action.name, "steps": action.steps.len()})) } @@ -858,7 +858,7 @@ pub(crate) fn not_playing(s: &Session, cmd: &str) -> Result<()> { /// Move to a final zero-based index, either in an action's steps or in the action list. fn move_item(s: &mut Session, p: &Value) -> Result { not_playing(s, "actions.move")?; - let idx = resolve(s.actions.list.actions(), p, "actions.move")?; + let idx = resolve(s.actions().list.actions(), p, "actions.move")?; let index = |key: &str| -> Result { p.get(key) .and_then(Value::as_u64) @@ -868,20 +868,20 @@ fn move_item(s: &mut Session, p: &Value) -> Result { let to = index("to")?; if p.get("step").is_some() { let step = index("step")?; - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); if step >= len || to >= len { return Err(bad("actions.move", "step or destination is out of range")); } if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } - s.actions.list.move_step(idx, step, idx, to).map_err(|e| list_error("actions.move", e))?; - let result = json!({"action": s.actions.list.actions()[idx].name, "step": to}); + s.actions_mut().list.move_step(idx, step, idx, to).map_err(|e| list_error("actions.move", e))?; + let result = json!({"action": s.actions().list.actions()[idx].name, "step": to}); note_automation_edit(s, idx); Ok(result) } else { - let name = s.actions.list.actions()[idx].name.clone(); - s.actions.list.move_action(idx, to).map_err(|e| list_error("actions.move", e))?; + let name = s.actions().list.actions()[idx].name.clone(); + s.actions_mut().list.move_action(idx, to).map_err(|e| list_error("actions.move", e))?; if let Some((_, recording)) = s.recording.target.as_mut() { *recording = moved_index(*recording, idx, to); } @@ -893,10 +893,10 @@ fn move_item(s: &mut Session, p: &Value) -> Result { /// as automation's when an automation gate is installed). fn delete(s: &mut Session, p: &Value) -> Result { not_playing(s, "actions.delete")?; - let idx = resolve(s.actions.list.actions(), p, "actions.delete")?; + let idx = resolve(s.actions().list.actions(), p, "actions.delete")?; if let Some(step) = p.get("step") { let step = step.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("actions.delete", "step must be a non-negative integer"))?; - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); if step >= len { return Err(bad("actions.delete", "step is out of range")); } @@ -905,8 +905,8 @@ fn delete(s: &mut Session, p: &Value) -> Result { if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } - s.actions.list.delete_step(idx, step).map_err(|e| list_error("actions.delete", e))?; - let action = &s.actions.list.actions()[idx]; + s.actions_mut().list.delete_step(idx, step).map_err(|e| list_error("actions.delete", e))?; + let action = &s.actions().list.actions()[idx]; let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()}); note_automation_edit(s, idx); return Ok(result); @@ -914,7 +914,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { if s.recording.target.is_some() { return Err(bad("actions.delete", "stop recording before deleting an action")); } - let name = s.actions.list.delete_action(idx).map_err(|e| list_error("actions.delete", e))?.name; + let name = s.actions_mut().list.delete_action(idx).map_err(|e| list_error("actions.delete", e))?.name; // Its function keys go with it, or the next action given the same name would inherit them. remove_shortcuts(s, std::iter::once(name.as_str())); Ok(json!({"deleted": name})) @@ -925,7 +925,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { fn toggle(s: &mut Session, p: &Value) -> Result { let cmd = "actions.toggle"; not_playing(s, cmd)?; - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; let enabled = match p.get("enabled") { None | Some(Value::Null) => None, Some(Value::Bool(b)) => Some(*b), @@ -935,26 +935,26 @@ fn toggle(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "step must be a non-negative integer"))?), }; - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); if step.is_some_and(|step| step >= len) { return Err(bad(cmd, "step is out of range")); } if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; let edit = match step { Some(step) => { let on = enabled.unwrap_or(!action.step_enabled(step)); - s.actions.list.set_step(idx, step, on) + s.actions_mut().list.set_step(idx, step, on) } None => { let on = enabled.unwrap_or(!action.disabled.is_empty()); - s.actions.list.set_all(idx, on) + s.actions_mut().list.set_all(idx, on) } }; edit.map_err(|e| list_error(cmd, e))?; - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; let result = json!({"action": action.name, "disabled": action.disabled}); note_automation_edit(s, idx); Ok(result) @@ -1063,22 +1063,22 @@ pub(crate) fn name_id_shortcuts(s: &mut Session, ids: &[(String, String)]) { /// stops working. fn rename(s: &mut Session, p: &Value) -> Result { not_playing(s, "actions.rename")?; - let idx = resolve(s.actions.list.actions(), p, "actions.rename")?; + let idx = resolve(s.actions().list.actions(), p, "actions.rename")?; let name = match p.get("name") { Some(Value::String(n)) if !n.trim().is_empty() => n.clone(), Some(Value::String(_)) => return Err(bad("actions.rename", "\"name\" is empty")), Some(_) => return Err(bad("actions.rename", "\"name\" must be a string")), None => return Err(bad("actions.rename", "needs \"name\"")), }; - let old = s.actions.list.action(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?; + let old = s.actions().list.action(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?; let pending = s.recording.target.map_or(s.journal.len(), |(start, _)| start); // Names are list-wide, so a call naming `old` reaches this action; a named Batch is checked // against the list before the rename because its set can still refuse it. - let before = s.actions.list.actions().to_vec(); + let before = s.actions().list.actions().to_vec(); let follow = |id: &str, params: &mut Value, old: &str, new: &str| rename_call(&before, idx, id, params, old, new); - s.actions.list.rename(idx, &name, |step, old, new| follow(&step.command, &mut step.params, old, new)).map_err(|e| list_error("actions.rename", e))?; + s.actions_mut().list.rename(idx, &name, |step, old, new| follow(&step.command, &mut step.params, old, new)).map_err(|e| list_error("actions.rename", e))?; // The list renames its own steps; the journal entries not yet recorded are the engine's. - let name = s.actions.list.actions()[idx].name.clone(); + let name = s.actions().list.actions()[idx].name.clone(); if old == name { return Ok(json!({"action": name, "index": idx})); } @@ -1120,7 +1120,7 @@ fn rename_call(before: &[Action], idx: usize, id: &str, params: &mut Value, old: fn set_color(s: &mut Session, p: &Value) -> Result { let cmd = "actions.setColor"; not_playing(s, cmd)?; - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; let Some(color) = p.get("color").and_then(Value::as_str) else { return Err(bad(cmd, "needs \"color\"")); }; @@ -1128,8 +1128,8 @@ fn set_color(s: &mut Session, p: &Value) -> Result { let Some(chosen) = ActionColor::ALL.into_iter().find(|each| each.name() == color) else { return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, or gray")); }; - s.actions.list.set_color(idx, chosen).map_err(|e| list_error(cmd, e))?; - let name = s.actions.list.actions()[idx].name.clone(); + s.actions_mut().list.set_color(idx, chosen).map_err(|e| list_error(cmd, e))?; + let name = s.actions().list.actions()[idx].name.clone(); Ok(json!({"action": name, "color": color})) } @@ -1336,7 +1336,7 @@ mod security_tests { fn a_nested_batch_input_does_not_reset_the_shared_playback_count() { let mut session = crate::session(); session.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({}))])).unwrap(); + session.actions_mut().list.push(Action::new("A", vec![ActionStep::new("select.all", json!({}))])).unwrap(); session.recording.budget_shared = true; session.recording.playback_steps = MAX_PLAYBACK_STEPS; let r = session.execute("actions.play", json!({"action": "A"})); @@ -1356,8 +1356,8 @@ mod security_tests { child.disabled = (0..1000).collect(); let calls = MAX_PLAYBACK_STEPS as usize / 1000 * 2; let parent = Action::new("Parent", (0..calls).map(|_| ActionStep::new("actions.play", json!({"action": "Child"}))).collect()); - session.actions.list.push(child).unwrap(); - session.actions.list.push(parent).unwrap(); + session.actions_mut().list.push(child).unwrap(); + session.actions_mut().list.push(parent).unwrap(); let r = session.execute("actions.play", json!({"action": "Parent"})).unwrap(); let failed = r["failed"]["error"].as_str().unwrap(); assert!(failed.contains("step limit"), "{failed}"); diff --git a/crates/engine-core/src/cmd/actions_cmds/playback_tests.rs b/crates/engine-core/src/cmd/actions_cmds/playback_tests.rs index ff652ced8a..40d60950a2 100644 --- a/crates/engine-core/src/cmd/actions_cmds/playback_tests.rs +++ b/crates/engine-core/src/cmd/actions_cmds/playback_tests.rs @@ -1,4 +1,6 @@ //! Playback Options (`actions.setPlayback`): validation, preferences and headless playback. +use crate::prefs::SavedPrefsExt; +use crate::actions_cmds::ActionsExt; use super::*; use serde_json::json; @@ -76,7 +78,7 @@ fn older_or_hand_edited_preferences_load_within_range() { fn set_playback_keeps_the_history_policy_of_a_running_play() { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.actions.list.push(Action::new("Change", vec![ActionStep::new("actions.setPlayback", json!({"singleState": false}))])).unwrap(); + s.actions_mut().list.push(Action::new("Change", vec![ActionStep::new("actions.setPlayback", json!({"singleState": false}))])).unwrap(); let played = s.execute("actions.play", json!({"action": "Change"})).unwrap(); assert!(played.get("failed").is_some(), "an action can't change Playback Options while it plays: {played}"); assert!(s.prefs().actions.create_single_history_state); @@ -92,7 +94,7 @@ fn headless_play_runs_the_whole_action_in_every_mode() { s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); s.execute("actions.setPlayback", json!({"performance": performance, "seconds": 60, "singleState": single})).unwrap(); let steps = ["A", "B", "C"].map(|n| ActionStep::new("layer.new.layer", json!({"name": n}))).to_vec(); - s.actions.list.push(Action::new("Three", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Three", steps)).unwrap(); let layers = s.active().unwrap().doc.layers.len(); let past = s.active().unwrap().history.past_len(); let t0 = std::time::Instant::now(); diff --git a/crates/engine-core/src/cmd/actions_cmds/tests.rs b/crates/engine-core/src/cmd/actions_cmds/tests.rs index 42c9f0bb39..14a5c40bf9 100644 --- a/crates/engine-core/src/cmd/actions_cmds/tests.rs +++ b/crates/engine-core/src/cmd/actions_cmds/tests.rs @@ -1,3 +1,5 @@ +use crate::preset_store::PresetStoreExt; +use crate::actions_cmds::ActionsExt; use super::*; use serde_json::json; @@ -26,7 +28,7 @@ fn save_in_edit_contents_updates_the_smart_object() { s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); s.execute("layer.smartObjects.editContents", json!({})).unwrap(); let steps = vec![ActionStep::new("edit.fill", json!({"contents": "color", "color": "#0000ff"})), ActionStep::new("file.save", json!({}))]; - s.actions.list.push(Action::new("Edit and save", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Edit and save", steps)).unwrap(); let played = s.execute("actions.play", json!({"action": "Edit and save"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); s.set_active(0); @@ -35,7 +37,7 @@ fn save_in_edit_contents_updates_the_smart_object() { let p = flat.pixel(2, 2); assert!(p[0] < 0.01 && p[2] > 0.99, "the smart object shows the saved contents: {p:?}"); // With no Edit Contents document, Save stays the shell's (it needs the document's file). - s.actions.list.push(Action::new("Save", vec![ActionStep::new("file.save", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Save", vec![ActionStep::new("file.save", json!({}))])).unwrap(); assert!(s.execute("actions.play", json!({"action": "Save"})).unwrap().get("failed").is_some()); } @@ -54,7 +56,7 @@ fn deselect_with_nothing_selected_is_a_noop_in_playback() { assert_eq!(s.active().unwrap().history.past_len(), before, "no history step"); let steps = vec![ActionStep::new("select.deselect", json!({})), ActionStep::new("layer.new.layer", json!({"name": "A"}))]; - s.actions.list.push(Action::new("Clear", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Clear", steps)).unwrap(); let played = s.execute("actions.play", json!({"action": 0})).unwrap(); assert_eq!(played["ran"], 2, "{played}"); assert_eq!(s.active().unwrap().doc.layers.last().unwrap().name, "A"); @@ -65,7 +67,7 @@ fn unchecked_steps_are_skipped_and_follow_move_and_delete() { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let step = |name: &str| ActionStep::new("layer.new.layer", json!({"name": name})); - s.actions.list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])).unwrap(); + s.actions_mut().list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])).unwrap(); let names = |s: &Session| s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect::>(); assert_eq!(s.execute("actions.toggle", json!({"action": "Three", "step": 1})).unwrap()["disabled"], json!([1])); @@ -76,19 +78,19 @@ fn unchecked_steps_are_skipped_and_follow_move_and_delete() { // Moving step 3 to the top keeps B (now step 2) unchecked; deleting the moved step shifts it to 1. s.execute("actions.move", json!({"action": 0, "step": 2, "to": 0})).unwrap(); - let ids: Vec<_> = s.actions.list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect(); - assert_eq!((ids, s.actions.list.actions()[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); + let ids: Vec<_> = s.actions().list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect(); + assert_eq!((ids, s.actions().list.actions()[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, [step("A"), step("B")], "deleting removes only that step"); - assert_eq!(s.actions.list.actions()[0].disabled.iter().copied().collect::>(), [1]); + assert_eq!(s.actions().list.actions()[0].steps, [step("A"), step("B")], "deleting removes only that step"); + assert_eq!(s.actions().list.actions()[0].disabled.iter().copied().collect::>(), [1]); // The action's own check: all on unless all already are. s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert!(s.actions.list.actions()[0].disabled.is_empty()); + assert!(s.actions().list.actions()[0].disabled.is_empty()); s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[0].disabled.len(), 2); + assert_eq!(s.actions().list.actions()[0].disabled.len(), 2); s.execute("actions.toggle", json!({"action": 0, "step": 0, "enabled": true})).unwrap(); - assert_eq!(s.actions.list.actions()[0].disabled.iter().copied().collect::>(), [1]); + assert_eq!(s.actions().list.actions()[0].disabled.iter().copied().collect::>(), [1]); for bad in [ json!({"action": 0, "step": 2}), @@ -100,7 +102,7 @@ fn unchecked_steps_are_skipped_and_follow_move_and_delete() { ] { assert!(s.execute("actions.toggle", bad.clone()).is_err(), "{bad}"); } - assert_eq!(s.actions.list.actions()[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); + assert_eq!(s.actions().list.actions()[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); } #[test] @@ -148,7 +150,7 @@ fn recorded_thumbnail_click_on_another_layer_saves_and_replays_by_name() { s.execute("select.loadSelection", json!({"channel": "transparency", "layer": source, "operation": "new"})).unwrap(); s.execute("select.loadSelection", json!({"channel": "transparency", "layer": background, "operation": "new"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let action = s.actions.list.actions().iter().find(|a| a.name == "Load").unwrap().clone(); + let action = s.actions().list.actions().iter().find(|a| a.name == "Load").unwrap().clone(); assert_eq!( action.steps, vec![ @@ -169,7 +171,7 @@ fn recorded_thumbnail_click_on_another_layer_saves_and_replays_by_name() { #[test] fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { let mut s = crate::session(); - s.actions + s.actions_mut() .list .push(Action { name: "Action 1".into(), @@ -178,7 +180,7 @@ fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { ..Default::default() }) .unwrap(); - s.actions + s.actions_mut() .list .push(Action { name: "Caller".into(), @@ -190,7 +192,7 @@ fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into())); assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia"); assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["name"], "Sepia"); - assert_eq!(s.actions.list.actions()[1].steps[0].params["action"], "Sepia"); + assert_eq!(s.actions().list.actions()[1].steps[0].params["action"], "Sepia"); assert_eq!(s.prefs().shortcuts.get("actions.play:Sepia").map(String::as_str), Some("F2")); assert!(!s.prefs().shortcuts.contains_key("actions.play:Action 1")); for bad in [ @@ -203,7 +205,7 @@ fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { ] { assert!(s.execute("actions.rename", bad.clone()).is_err(), "{bad}"); } - assert_eq!(s.actions.list.actions()[0].name, "Sepia"); + assert_eq!(s.actions().list.actions()[0].name, "Sepia"); } #[test] @@ -211,9 +213,9 @@ fn rename_follows_conditional_branches() { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); for name in ["B", "Other"] { - s.actions.list.push(Action { name: name.into(), steps: vec![ActionStep::new("layer.new.layer", json!({}))], ..Default::default() }).unwrap(); + s.actions_mut().list.push(Action { name: name.into(), steps: vec![ActionStep::new("layer.new.layer", json!({}))], ..Default::default() }).unwrap(); } - s.actions + s.actions_mut() .list .push(Action { name: "Main".into(), @@ -225,7 +227,7 @@ fn rename_follows_conditional_branches() { }) .unwrap(); s.execute("actions.rename", json!({"action": "B", "name": "C"})).unwrap(); - let steps = &s.actions.list.actions()[2].steps; + let steps = &s.actions().list.actions()[2].steps; assert_eq!(steps[0].params, json!({"if": "always", "then": "C", "else": "Other"})); assert_eq!(steps[1].params, json!({"if": "never", "then": "Other", "else": "C"})); let r = s.execute("actions.play", json!({"action": "Main"})).unwrap(); @@ -236,7 +238,7 @@ fn rename_follows_conditional_branches() { fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { let mut s = crate::session(); let key = format!("{PLAY_SHORTCUT_PREFIX}Action 1"); - s.actions.list.push(Action::new("Action 1", vec![ActionStep::new("layer.new.layer", json!({})), ActionStep::new("layer.new.layer", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Action 1", vec![ActionStep::new("layer.new.layer", json!({})), ActionStep::new("layer.new.layer", json!({}))])).unwrap(); s.edit_prefs(|p| p.shortcuts.insert(key.clone(), "F2".into())); s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F2"), "deleting a step keeps the key"); @@ -244,7 +246,7 @@ fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { assert!(!s.prefs().shortcuts.contains_key(&key), "the deleted action's function key is gone"); s.execute("actions.record", json!({})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].name, "Action 1"); + assert_eq!(s.actions().list.actions()[0].name, "Action 1"); assert!(!s.prefs().shortcuts.contains_key(&key), "a new action with the same name starts unbound"); } @@ -318,7 +320,7 @@ fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { let got = s.execute("actions.get", json!({"action": "Step"})).unwrap(); let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper"); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); // A new session has no transform to repeat: the concrete steps still play. let mut fresh = crate::session(); @@ -329,7 +331,7 @@ fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { Ok(()) }) .unwrap(); - fresh.actions.list.push(action).unwrap(); + fresh.actions_mut().list.push(action).unwrap(); let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap(); assert!(played.get("failed").is_none(), "depth {depth}: {played}"); assert_eq!(played["ran"], 2, "depth {depth}"); @@ -410,7 +412,7 @@ fn recording_folds_one_run_of_move_tool_nudges() { s.execute("layer.translate", json!({"dx": dx, "dy": dy, "coalesce": run})).unwrap(); } s.execute("actions.stop", json!({})).unwrap(); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps, &[ActionStep::new("layer.translate", json!({"dx": 3.0, "dy": 10.0})), ActionStep::new("layer.translate", json!({"dx": 0.0, "dy": 1.0}))]); } @@ -426,7 +428,7 @@ fn recording_folds_wrapped_move_tool_nudges() { } s.execute("actions.stop", json!({})).unwrap(); assert_eq!( - s.actions.list.actions()[0].steps, + s.actions().list.actions()[0].steps, [ ActionStep::new("layer.translate", json!({"dx": 3.0, "dy": 0.0, "wrap": true})), ActionStep::new("layer.translate", json!({"dx": 1.0, "dy": 0.0, "wrap": false})) @@ -445,7 +447,7 @@ fn folded_nudges_add_whole_pixel_steps() { s.execute("layer.translate", json!({"dx": 0.6, "dy": 0.0, "coalesce": "nudge:1"})).unwrap(); } s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("layer.translate", json!({"dx": 2.0, "dy": 0.0}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("layer.translate", json!({"dx": 2.0, "dy": 0.0}))]); } #[test] @@ -457,7 +459,7 @@ fn recording_document_activation_uses_opening_order_offset() { s.execute("actions.record", json!({"name": "Switch"})).unwrap(); s.execute("document.activate", json!({"document": 0})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("document.activate", json!({"offset": -1}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("document.activate", json!({"offset": -1}))]); } #[test] @@ -467,8 +469,8 @@ fn recorded_point_text_position_scales_with_the_playback_canvas() { s.execute("actions.record", json!({"name": "Caption"})).unwrap(); s.execute("type.create", json!({"x": 20, "y": 30, "text": "Hi", "size": 12})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params["xPercent"], json!(20.0)); - assert_eq!(s.actions.list.actions()[0].steps[0].params["yPercent"], json!(30.0)); + assert_eq!(s.actions().list.actions()[0].steps[0].params["xPercent"], json!(20.0)); + assert_eq!(s.actions().list.actions()[0].steps[0].params["yPercent"], json!(30.0)); s.execute("file.new", json!({"width": 200, "height": 300, "background": "transparent"})).unwrap(); let played = s.execute("actions.play", json!({"action": "Caption"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); @@ -626,11 +628,11 @@ fn recorded_layer_selection_replays_by_name_on_another_document() { s.execute("layer.setProps", json!({"name": "Retouched"})).unwrap(); s.execute("layer.duplicate", json!({})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"name":"Photo", "mode":"replace"})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"name":"Photo", "mode":"replace"})); // Persisted actions must work in an entirely different session too. - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); replay.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); replay.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); let target = replay.active().unwrap().active_layer.unwrap(); @@ -667,11 +669,11 @@ fn recorded_mask_drop_replays_on_another_document() { s.execute("actions.record", json!({"name": "Mask to shadow"})).unwrap(); s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": shadow, "copy": false})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"layer": "Photo", "to": "Shadow", "copy": false})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"layer": "Photo", "to": "Shadow", "copy": false})); // Another document: an extra layer between them, so the recorded id is a different layer. - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); masked(&mut replay, "Photo"); replay.execute("layer.new.layer", json!({"name": "Extra"})).unwrap(); @@ -704,11 +706,11 @@ fn recorded_mask_drop_onto_a_duplicate_name_replays_on_the_same_layer() { s.execute("actions.record", json!({"name": "Copy mask"})).unwrap(); s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": lower, "copy": true})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"layer": "Photo", "to": "Twin", "toOccurrence": 0, "copy": true})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"layer": "Photo", "to": "Twin", "toOccurrence": 0, "copy": true})); assert!(mask_on(&s, lower) && !mask_on(&s, upper)); - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); let (photo2, lower2, upper2) = build(&mut replay, true); assert_ne!((photo, lower, upper), (photo2, lower2, upper2), "the ids differ"); let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); @@ -742,13 +744,13 @@ fn recorded_layer_drag_replays_on_another_document() { let copy = s.active().unwrap().active_layer.unwrap(); s.execute("layer.moveTo", json!({"layer": copy.0, "target": layer2.0, "position": "above"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let ActionStep { command: id, params: step } = s.actions.list.actions()[0].steps.last().unwrap(); + let ActionStep { command: id, params: step } = s.actions().list.actions()[0].steps.last().unwrap(); assert_eq!((id.as_str(), step), ("layer.moveTo", &json!({"target": "Layer 1 copy", "position": "above"}))); let names = |s: &Session| s.active().unwrap().doc.layers.iter().rev().map(|l| l.name.clone()).collect::>(); let recorded = names(&s); - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); replay.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); assert!(result.get("failed").is_none(), "{depth}: {result}"); @@ -765,7 +767,7 @@ fn recorded_layer_drag_replays_on_another_document() { s.execute("actions.record", json!({"name": "Drop"})).unwrap(); s.execute("layer.moveTo", json!({"layer": mover.0, "target": upper.0, "position": "below"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); // The moved layer shares the target's name: the occurrence counts the other "Twin"s only, // so it means the same layer before the move (on replay) as after it (when recorded). let build = |s: &mut Session| { @@ -781,12 +783,12 @@ fn recorded_layer_drag_replays_on_another_document() { s.execute("actions.record", json!({"name": "Twins"})).unwrap(); s.execute("layer.moveTo", json!({"layer": top.0, "target": lowest.0, "position": "below"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); let order = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); let want: Vec<_> = order(&s).iter().map(|id| ids.iter().position(|x| x == id).unwrap()).collect(); - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); let ids2 = build(&mut replay); let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); @@ -810,10 +812,10 @@ fn recorded_layer_drag_replays_on_another_document() { g.execute("actions.record", json!({"name": "Group"})).unwrap(); g.execute("layer.moveTo", json!({"layer": group.0, "target": top.0, "position": "above"})).unwrap(); g.execute("actions.stop", json!({})).unwrap(); - let recorded = g.actions.list.actions()[0].steps[0].params.clone(); - let saved = g.actions.list.to_file().to_json().unwrap(); + let recorded = g.actions().list.actions()[0].steps[0].params.clone(); + let saved = g.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); let (group2, _) = build_group(&mut replay); let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); assert!(result.get("failed").is_none(), "{recorded}: {result}"); @@ -835,10 +837,10 @@ fn recorded_layer_drag_replays_on_another_document() { c.execute("actions.record", json!({"name": "Copy"})).unwrap(); c.execute("layer.moveTo", json!({"layer": src.0, "target": src.0, "position": "above", "copy": true})).unwrap(); c.execute("actions.stop", json!({})).unwrap(); - assert_eq!(c.actions.list.actions()[0].steps[0].params, json!({"target": "Solo", "position": "above", "copy": true})); - let saved = c.actions.list.to_file().to_json().unwrap(); + assert_eq!(c.actions().list.actions()[0].steps[0].params, json!({"target": "Solo", "position": "above", "copy": true})); + let saved = c.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); replay.execute("layer.new.layer", json!({"name": "Solo"})).unwrap(); let before = replay.active().unwrap().doc.layers.len(); @@ -863,9 +865,9 @@ fn recorded_layer_drag_replays_on_another_document() { // Below `a`: the copy's "Twin" then comes before `a` in document order. gc.execute("layer.moveTo", json!({"layer": group.0, "target": a.0, "position": "below", "copy": true})).unwrap(); gc.execute("actions.stop", json!({})).unwrap(); - let saved = gc.actions.list.to_file().to_json().unwrap(); + let saved = gc.actions().list.to_file().to_json().unwrap(); let mut replay = crate::session(); - replay.actions.list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); + replay.actions_mut().list = ActionList::from_file(ActionsFile::from_json(&saved).unwrap()); let (_, a2, _) = build_copy(&mut replay); let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); @@ -877,7 +879,7 @@ fn recorded_layer_drag_replays_on_another_document() { s.execute("actions.record", json!({"name": "Several"})).unwrap(); s.execute("layer.moveTo", json!({"layers": [ids[2].0, ids[3].0], "target": ids[1].0, "position": "above"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[1].steps[0].params["target"], json!(ids[1].0)); + assert_eq!(s.actions().list.actions()[1].steps[0].params["target"], json!(ids[1].0)); // Bad targets are errors, not panics. for bad in [ json!({"target": "Nobody"}), @@ -904,10 +906,10 @@ fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { s.execute("actions.record", json!({"name": "Board copy"})).unwrap(); s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("layer.duplicate", json!({}))]); - assert_eq!(s.actions.list.actions()[1].steps, vec![ActionStep::new("layer.duplicate", json!({"inPlace": true}))]); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list.actions()[0]], &[], false).is_ok()); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list.actions()[1]], &[], false).is_err()); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("layer.duplicate", json!({}))]); + assert_eq!(s.actions().list.actions()[1].steps, vec![ActionStep::new("layer.duplicate", json!({"inPlace": true}))]); + assert!(crate::atn_cmds::export("Audit", &[&s.actions().list.actions()[0]], &[], false).is_ok()); + assert!(crate::atn_cmds::export("Audit", &[&s.actions().list.actions()[1]], &[], false).is_err()); // Several selected layers are copied together: one artboard among them keeps `inPlace`. let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); @@ -923,8 +925,8 @@ fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { s.execute("actions.record", json!({"name": "Mixed copy"})).unwrap(); s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("layer.duplicate", json!({}))]); - assert_eq!(s.actions.list.actions()[1].steps, vec![ActionStep::new("layer.duplicate", json!({"inPlace": true}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("layer.duplicate", json!({}))]); + assert_eq!(s.actions().list.actions()[1].steps, vec![ActionStep::new("layer.duplicate", json!({"inPlace": true}))]); } #[test] @@ -950,8 +952,8 @@ fn named_selection_preserves_modes_and_duplicate_occurrences() { s.execute("layer.select", json!({"layer":first.0})).unwrap(); s.execute("layer.select", json!({"layer":second.0,"mode":"add"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"name":"Photo","occurrence":0})); - assert_eq!(s.actions.list.actions()[0].steps[1].params, json!({"name":"Photo","occurrence":1,"mode":"add"})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"name":"Photo","occurrence":0})); + assert_eq!(s.actions().list.actions()[0].steps[1].params, json!({"name":"Photo","occurrence":1,"mode":"add"})); s.execute("layer.select", json!({"layer":first.0})).unwrap(); let r = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(r.get("failed").is_none(), "{r}"); @@ -984,7 +986,7 @@ fn named_selection_preserves_modes_and_duplicate_occurrences() { assert!(s.execute("layer.select", p.clone()).is_err(), "{p}"); assert_eq!(s.active().unwrap().selected_layers(), before); } - s.actions + s.actions_mut() .list .push(Action { name: "Missing".into(), @@ -1007,8 +1009,8 @@ fn play_stops_at_the_failing_step_and_reports_it() { s.execute("actions.record", json!({})).unwrap(); s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let at = s.actions.list.step_count(0); - s.actions.list.insert_step(0, at, ActionStep::new("not.a.command", json!({}))).unwrap(); + let at = s.actions().list.step_count(0); + s.actions_mut().list.insert_step(0, at, ActionStep::new("not.a.command", json!({}))).unwrap(); s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap(); assert_eq!(r["ran"], 1); @@ -1024,7 +1026,7 @@ fn play_stops_at_the_failing_step_and_reports_it() { #[test] fn play_refuses_recursion() { let mut s = crate::session(); - s.actions + s.actions_mut() .list .push(Action { name: "Loop".into(), @@ -1048,7 +1050,7 @@ fn play_checks_each_step_with_the_authorize_hook() { } let mut s = crate::session(); s.authorize = Some(deny_file); - s.actions + s.actions_mut() .list .push(Action { name: "Open".into(), @@ -1077,8 +1079,8 @@ fn actions_automation_wrote_keep_its_gate_when_the_user_plays_them() { let open = || ActionStep::new("file.openAs", json!({"path": "/outside/secret.png"})); let mut s = crate::session(); s.automation_gate = Some(deny_file); - s.actions.list.push(Action::new("Mine", vec![open()])).unwrap(); - s.actions.list.push(Action::new("Edited", vec![ActionStep::new("layer.new.layer", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Mine", vec![open()])).unwrap(); + s.actions_mut().list.push(Action::new("Edited", vec![ActionStep::new("layer.new.layer", json!({}))])).unwrap(); let (atn, _) = crate::atn_cmds::export("Set", &[&Action::new("Planted", vec![open()])], &[], false).unwrap(); let data = photocraft_paint::tile::b64_encode(&atn); @@ -1087,7 +1089,7 @@ fn actions_automation_wrote_keep_its_gate_when_the_user_plays_them() { s.execute("actions.load", json!({"data": data})).unwrap(); s.execute("actions.insert", json!({"action": "Edited", "id": "file.openAs", "params": {"path": "/outside/secret.png"}, "at": 0})).unwrap(); s.authorize = None; - assert!(!s.actions.list.actions()[0].automation, "the user's own action is not marked"); + assert!(!s.actions().list.actions()[0].automation, "the user's own action is not marked"); for name in ["Planted", "Edited"] { let r = s.execute("actions.play", json!({"action": name})).unwrap(); @@ -1096,7 +1098,7 @@ fn actions_automation_wrote_keep_its_gate_when_the_user_plays_them() { assert!(s.authorize.is_none(), "{name}: the kept gate is removed after playback"); } // Nested: the user's action calling a planted one still meets the gate. - s.actions.list.push(Action::new("Caller", vec![ActionStep::new("actions.play", json!({"action": "Planted"}))])).unwrap(); + s.actions_mut().list.push(Action::new("Caller", vec![ActionStep::new("actions.play", json!({"action": "Planted"}))])).unwrap(); let r = s.execute("actions.play", json!({"action": "Caller"})).unwrap(); assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); @@ -1105,7 +1107,7 @@ fn actions_automation_wrote_keep_its_gate_when_the_user_plays_them() { assert!(!r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); // A set the user loads is theirs. s.execute("actions.load", json!({"data": data, "set": "Loaded by the user"})).unwrap(); - let loaded = s.actions.list.actions().last().unwrap(); + let loaded = s.actions().list.actions().last().unwrap(); assert_eq!(loaded.name, "Planted 2", "names are unique across the list, so the second load renames its action"); assert!(!loaded.automation); } @@ -1130,7 +1132,7 @@ fn a_step_automation_runs_into_the_users_recording_keeps_its_gate() { s.execute("actions.record", json!({"name": "Mine"})).unwrap(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert!(!s.actions.list.actions()[0].automation, "the user's own recording is not marked"); + assert!(!s.actions().list.actions()[0].automation, "the user's own recording is not marked"); // The user records again; a control client runs a `file.` command meanwhile. s.execute("actions.record", json!({"name": "Shared"})).unwrap(); @@ -1139,7 +1141,7 @@ fn a_step_automation_runs_into_the_users_recording_keeps_its_gate() { s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); s.authorize = None; s.execute("actions.stop", json!({})).unwrap(); - let shared = &s.actions.list.actions()[1]; + let shared = &s.actions().list.actions()[1]; assert!(shared.steps.iter().any(|st| st.command == "file.new"), "the client's step is recorded: {:?}", shared.steps); assert!(shared.automation, "a step the client ran marks the recorded action"); // Played ungated (the user's key or the panel), the client's step meets automation's gate. @@ -1157,7 +1159,7 @@ fn a_step_automation_runs_into_the_users_recording_keeps_its_gate() { s.execute("actions.play", json!({"action": "Mine"})).unwrap(); s.authorize = None; s.execute("actions.stop", json!({})).unwrap(); - let caller = &s.actions.list.actions()[2]; + let caller = &s.actions().list.actions()[2]; assert_eq!(caller.steps.first().map(|st| st.command.as_str()), Some("actions.play"), "{:?}", caller.steps); assert!(caller.automation, "a call the client played marks the recorded action"); } @@ -1182,7 +1184,7 @@ fn append_delete_and_from_step() { assert_eq!(r["ran"], 1); assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow"); - assert!(s.actions.list.actions().is_empty()); + assert!(s.actions().list.actions().is_empty()); assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err()); } @@ -1194,11 +1196,11 @@ fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap(); s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap(); let journal = s.journal.clone(); - let rev = s.actions.list.revision(); - let before = (s.actions.clone(), s.recording.clone()); + let rev = s.actions().list.revision(); + let before = (s.actions().clone(), s.recording.clone()); for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] { assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err()); - assert_eq!((s.actions.clone(), s.recording.clone()), before, "invalid deletion is atomic"); + assert_eq!((s.actions().clone(), s.recording.clone()), before, "invalid deletion is atomic"); } assert_eq!(pending_steps(&s, 0).count(), 2); let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap(); @@ -1206,27 +1208,27 @@ fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands"); assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits"); assert!(s.recording.target.is_some()); - assert!(s.actions.list.revision() > rev); + assert!(s.actions().list.revision() > rev); s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); + assert_eq!(s.actions().list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params["name"], "After"); - let saved = s.actions.list.to_file().to_json().unwrap(); - s.actions.list.replace(ActionList::from_file(ActionsFile::from_json(&saved).unwrap())); + assert_eq!(s.actions().list.actions()[0].steps[0].params["name"], "After"); + let saved = s.actions().list.to_file().to_json().unwrap(); + s.actions_mut().list.replace(ActionList::from_file(ActionsFile::from_json(&saved).unwrap())); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1); assert_eq!(s.active().unwrap().doc.layers[1].name, "After"); s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list.actions().len(), 1, "an empty action still exists"); - assert!(s.actions.list.actions()[0].steps.is_empty()); + assert_eq!(s.actions().list.actions().len(), 1, "an empty action still exists"); + assert!(s.actions().list.actions()[0].steps.is_empty()); } #[test] fn nested_call_records_one_named_step_and_tracks_child_edits() { let mut s = crate::session(); s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.actions + s.actions_mut() .list .push(Action { name: "Child".into(), @@ -1242,14 +1244,14 @@ fn nested_call_records_one_named_step_and_tracks_child_edits() { s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); assert_eq!( - s.actions.list.actions()[1].steps.iter().map(|st| st.command.as_str()).collect::>(), + s.actions().list.actions()[1].steps.iter().map(|st| st.command.as_str()).collect::>(), ["layer.new.layer", "actions.play", "layer.new.layer"] ); - let at = s.actions.list.step_count(0); - s.actions.list.insert_step(0, at, ActionStep::new("layer.new.layer", json!({"name": "Added later"}))).unwrap(); + let at = s.actions().list.step_count(0); + s.actions_mut().list.insert_step(0, at, ActionStep::new("layer.new.layer", json!({"name": "Added later"}))).unwrap(); s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap(); - let saved = s.actions.list.to_file().to_json().unwrap(); - s.actions.list.replace(ActionList::from_file(ActionsFile::from_json(&saved).unwrap())); + let saved = s.actions().list.to_file().to_json().unwrap(); + s.actions_mut().list.replace(ActionList::from_file(ActionsFile::from_json(&saved).unwrap())); s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); @@ -1260,7 +1262,7 @@ fn nested_call_records_one_named_step_and_tracks_child_edits() { #[test] fn nested_failure_cycles_depth_and_authorization_stop_parent() { let mut s = crate::session(); - s.actions + s.actions_mut() .list .push(Action { name: "A".into(), @@ -1269,7 +1271,7 @@ fn nested_failure_cycles_depth_and_authorization_stop_parent() { ..Default::default() }) .unwrap(); - s.actions + s.actions_mut() .list .push(Action { name: "B".into(), @@ -1281,15 +1283,15 @@ fn nested_failure_cycles_depth_and_authorization_stop_parent() { let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert!(r["failed"]["error"].as_str().unwrap().contains("recursive")); assert!(s.documents().is_empty()); - s.actions.list.replace_step(1, 0, ActionStep::new("file.new", json!({"width": 2,"height": 2}))).unwrap(); + s.actions_mut().list.replace_step(1, 0, ActionStep::new("file.new", json!({"width": 2,"height": 2}))).unwrap(); s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) }); let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file")); assert!(s.documents().is_empty()); s.authorize = None; - s.actions.list.replace(ActionList::new()); + s.actions_mut().list.replace(ActionList::new()); for i in 0..17 { - s.actions + s.actions_mut() .list .push(Action { name: format!("N{i}"), @@ -1303,7 +1305,7 @@ fn nested_failure_cycles_depth_and_authorization_stop_parent() { assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels")); assert_eq!(s.recording.playing, 0); assert!(s.recording.playback_stack.is_empty()); - s.actions.list.delete_step(15, 0).unwrap(); + s.actions_mut().list.delete_step(15, 0).unwrap(); assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); } @@ -1315,7 +1317,7 @@ fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { for name in ["One", "Two", "Three"] { s.execute("layer.new.layer", json!({"name": name})).unwrap(); } - let before = (s.actions.clone(), s.recording.clone()); + let before = (s.actions().clone(), s.recording.clone()); for params in [ json!({"action":0,"step":0,"to":3}), json!({"action":0,"step":99,"to":0}), @@ -1324,7 +1326,7 @@ fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { json!({"action":0,"to":null}), ] { assert!(s.execute("actions.move", params).is_err()); - assert_eq!((s.actions.clone(), s.recording.clone()), before); + assert_eq!((s.actions().clone(), s.recording.clone()), before); } let journal = s.journal.clone(); s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap(); @@ -1332,7 +1334,7 @@ fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { assert_eq!(s.journal, journal); s.execute("layer.new.layer", json!({"name":"Four"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); + assert_eq!(s.actions().list.actions()[0].steps.iter().map(|st| st.params["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); s.execute("file.new", json!({"width":4,"height":4})).unwrap(); s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Three", "Two", "One", "Four"]); @@ -1341,7 +1343,7 @@ fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { #[test] fn new_names_do_not_collide_with_named_calls() { let mut s = crate::session(); - s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }).unwrap(); + s.actions_mut().list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }).unwrap(); assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3"); s.execute("actions.stop", json!({})).unwrap(); assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err()); @@ -1353,7 +1355,7 @@ fn moving_action_keeps_recording_attached_to_it() { let mut s = crate::session(); s.execute("file.new", json!({"width":4,"height":4})).unwrap(); for name in ["A", "B", "C"] { - s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }).unwrap(); + s.actions_mut().list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }).unwrap(); } s.execute("actions.record", json!({"action":"B"})).unwrap(); s.execute("layer.new.layer", json!({"name":"before"})).unwrap(); @@ -1361,8 +1363,8 @@ fn moving_action_keeps_recording_attached_to_it() { s.execute("actions.move", json!({"action":"A","to":2})).unwrap(); s.execute("layer.new.layer", json!({"name":"after"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[1].name, "B"); - assert_eq!(s.actions.list.actions()[1].steps.len(), 2); + assert_eq!(s.actions().list.actions()[1].name, "B"); + assert_eq!(s.actions().list.actions()[1].steps.len(), 2); } #[test] @@ -1419,14 +1421,14 @@ fn actions_persist_with_the_preset_store() { early.execute("actions.record", json!({"name": "Early"})).unwrap(); early.execute("actions.stop", json!({})).unwrap(); early.attach_preset_store(crate::preset_store::open_dir(&dir)); - let names: Vec = early.actions.list.actions().iter().map(|a| a.name.clone()).collect(); + let names: Vec = early.actions().list.actions().iter().map(|a| a.name.clone()).collect(); assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}"); std::fs::write(dir.join("actions.json"), b"{").unwrap(); let mut bad = crate::session(); let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir)); assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}"); - assert!(bad.actions.list.actions().is_empty()); + assert!(bad.actions().list.actions().is_empty()); let _ = std::fs::remove_dir_all(&dir); } @@ -1477,17 +1479,17 @@ fn button_color_is_one_of_the_photoshop_swatches() { s.execute("actions.stop", json!({})).unwrap(); let set = s.execute("actions.setColor", json!({"action": "Print", "color": "blue"})).unwrap(); assert_eq!(set["color"], "blue"); - assert_eq!(s.actions.list.actions()[0].color, ActionColor::Blue); + assert_eq!(s.actions().list.actions()[0].color, ActionColor::Blue); assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["color"], "blue"); - let saved = s.actions.list.to_file().to_json().unwrap(); + let saved = s.actions().list.to_file().to_json().unwrap(); assert!(saved.contains("blue")); s.execute("actions.setColor", json!({"action": 0, "color": ""})).unwrap(); - assert_eq!(s.actions.list.actions()[0].color, ActionColor::None); - assert!(!s.actions.list.to_file().to_json().unwrap().contains("color"), "an empty colour is omitted"); + assert_eq!(s.actions().list.actions()[0].color, ActionColor::None); + assert!(!s.actions().list.to_file().to_json().unwrap().contains("color"), "an empty colour is omitted"); for bad in [json!({"action": 0, "color": "pink"}), json!({"action": 0}), json!({"action": 4, "color": "red"}), json!({"color": "red"})] { assert!(s.execute("actions.setColor", bad).is_err()); } - assert_eq!(s.actions.list.actions()[0].color, ActionColor::None, "rejected colours change nothing"); + assert_eq!(s.actions().list.actions()[0].color, ActionColor::None, "rejected colours change nothing"); } #[test] @@ -1503,7 +1505,7 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { ActionStep::new("layer.arrange.bringToFront", json!({})), ActionStep::new("layer.new.layer", json!({"name": "After"})), ]; - s.actions.list.push(Action::new("Repro", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Repro", steps)).unwrap(); let before = s.active().unwrap().history.past_len(); let played = s.execute("actions.play", json!({"action": 0})).unwrap(); assert_eq!(played["ran"], 3, "{played}"); @@ -1541,7 +1543,7 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { // Arranging the Background still stops playback: Photoshop refuses it too. let bg = bg.unwrap(); - s.actions.list.push(Action::new("Bg", vec![ActionStep::new("layer.arrange.bringToFront", json!({"layer": bg.0}))])).unwrap(); + s.actions_mut().list.push(Action::new("Bg", vec![ActionStep::new("layer.arrange.bringToFront", json!({"layer": bg.0}))])).unwrap(); let played = s.execute("actions.play", json!({"action": 1})).unwrap(); assert_eq!(played["ran"], 0, "{played}"); assert!(played["failed"].is_object(), "{played}"); @@ -1615,7 +1617,7 @@ fn scoped_source_slots_do_not_bind_previously_missing_references() { assert!(resolve(&called, &called[0].steps[0].params, "actions.play").is_err(), "the ordinary source still has a missing target"); let mut session = crate::session(); session.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - session.actions.list = list_of(called); + session.actions_mut().list = list_of(called); let (id, params) = steps.last().unwrap(); let result = session.execute(id, params.clone()).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); @@ -1627,10 +1629,10 @@ fn scoped_source_slots_do_not_bind_previously_missing_references() { #[test] fn record_keeps_an_existing_sets_exact_name() { let mut s = crate::session(); - s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }).unwrap(); + s.actions_mut().list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }).unwrap(); s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let set_of = |s: &Session, n: &str| s.actions.list.actions().iter().find(|a| a.name == n).and_then(|a| a.set.clone()); + let set_of = |s: &Session, n: &str| s.actions().list.actions().iter().find(|a| a.name == n).and_then(|a| a.set.clone()); assert_eq!(set_of(&s, "New").as_deref(), Some(" Web "), "the existing set"); s.execute("actions.record", json!({"name": "Fresh", "set": " Print "})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); @@ -1642,13 +1644,13 @@ fn record_keeps_an_existing_sets_exact_name() { #[test] fn record_keeps_an_empty_loaded_sets_exact_name() { let mut src = crate::session(); - src.actions.list.replace(ActionList::from_file(ActionsFile::new(Vec::new(), vec![" Web ".into()]))); + src.actions_mut().list.replace(ActionList::from_file(ActionsFile::new(Vec::new(), vec![" Web ".into()]))); let saved = src.execute("actions.save", json!({"set": " Web "})).unwrap(); let mut s = crate::session(); assert_eq!(s.execute("actions.load", json!({"data": saved["data"]})).unwrap()["set"], " Web "); s.execute("actions.record", json!({"name": "First", "set": " Web "})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let set = s.actions.list.actions().iter().find(|a| a.name == "First").and_then(|a| a.set.clone()); + let set = s.actions().list.actions().iter().find(|a| a.name == "First").and_then(|a| a.set.clone()); assert_eq!(set.as_deref(), Some(" Web ")); assert_eq!(crate::actions_edit_cmds::set_names(&s), [" Web "], "one folder, not a trimmed second one"); assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"])); @@ -1657,7 +1659,7 @@ fn record_keeps_an_empty_loaded_sets_exact_name() { #[test] fn skipped_steps_count_against_the_script_limit() { let mut s = crate::session(); - s.actions.list.push(Action::new("A", (0..3).map(|_| ActionStep::new("select.all", json!({}))).collect())).unwrap(); + s.actions_mut().list.push(Action::new("A", (0..3).map(|_| ActionStep::new("select.all", json!({}))).collect())).unwrap(); s.recording.script_depth = 1; s.recording.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; let e = s.execute("actions.play", json!({"action": "A", "from": 3})).err().map(|e| e.to_string()); @@ -1724,24 +1726,24 @@ fn rename_leaves_calls_that_reach_another_sets_action_alone() { .into_iter() .chain([Action::new("Caller", calls())]) .collect(); - s.actions.list = ActionList::from_file(ActionsFile::new(file, Vec::new())); - assert_eq!(s.actions.list.actions()[1].name, "Target 2", "the load renamed the repeat"); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(file, Vec::new())); + assert_eq!(s.actions().list.actions()[1].name, "Target 2", "the load renamed the repeat"); s }; let mut s = session(); s.execute("actions.rename", json!({"action": 1, "name": "Renamed"})).unwrap(); - let caller = &s.actions.list.actions()[2].steps; + let caller = &s.actions().list.actions()[2].steps; assert_eq!(caller[0].params["action"], "Target", "a Batch naming set A's action stays"); assert_eq!(caller[1].params["action"], "Renamed", "the Batch naming set B's action follows"); assert_eq!(caller[2].params["action"], "Target 2", "explicit steps are left alone"); assert_eq!(caller[3].params["action"], "Target", "a nested Play reaches set A's action"); assert_eq!((&caller[4].params["then"], &caller[4].params["else"]), (&json!("Target"), &json!("Target"))); - assert_eq!(crate::file_cmds::batch_action(s.actions.list.actions(), &caller[0].params).unwrap(), 0); - assert_eq!(crate::file_cmds::batch_action(s.actions.list.actions(), &caller[1].params).unwrap(), 1); + assert_eq!(crate::file_cmds::batch_action(s.actions().list.actions(), &caller[0].params).unwrap(), 0); + assert_eq!(crate::file_cmds::batch_action(s.actions().list.actions(), &caller[1].params).unwrap(), 1); let mut s = session(); s.execute("actions.rename", json!({"action": 0, "name": "Renamed"})).unwrap(); - let caller = &s.actions.list.actions()[2].steps; + let caller = &s.actions().list.actions()[2].steps; assert_eq!(caller[0].params["action"], "Renamed"); assert_eq!(caller[1].params["action"], "Target 2", "the Batch naming B's action stays"); assert_eq!(caller[3].params["action"], "Renamed"); @@ -1755,7 +1757,7 @@ fn rename_follows_named_batch_steps_in_their_set() { let mut s = crate::session(); let mut target = Action::new("Target", vec![ActionStep::new("image.adjustments.invert", json!({}))]); target.set = Some("S".into()); - s.actions.list.push(target).unwrap(); + s.actions_mut().list.push(target).unwrap(); let steps = vec![ ActionStep::new("file.automate.batch", json!({"action": "Target", "input": [], "output": "/out"})), ActionStep::new("file.automate.batch", json!({"action": "Target", "set": "S", "input": [], "output": "/out"})), @@ -1763,12 +1765,12 @@ fn rename_follows_named_batch_steps_in_their_set() { ActionStep::new("file.automate.batch", json!({"action": "Target", "set": "Other", "input": [], "output": "/out"})), ActionStep::new("file.automate.batch", json!({"action": [["actions.play", {"action": "Target"}]], "input": [], "output": "/out"})), ]; - s.actions.list.push(Action::new("Caller", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Caller", steps)).unwrap(); s.execute("actions.rename", json!({"action": "Target", "name": "Renamed"})).unwrap(); - let caller = &s.actions.list.actions()[1].steps; + let caller = &s.actions().list.actions()[1].steps; for step in &caller[..3] { assert_eq!(step.params["action"], "Renamed", "{}", step.params); - assert_eq!(crate::file_cmds::batch_action(s.actions.list.actions(), &step.params).unwrap(), 0, "{}", step.params); + assert_eq!(crate::file_cmds::batch_action(s.actions().list.actions(), &step.params).unwrap(), 0, "{}", step.params); } assert_eq!(caller[1].params["set"], "S"); assert_eq!(caller[3].params["action"], "Target", "a Batch in another set names a different action"); @@ -1787,7 +1789,7 @@ fn playback_stops_when_a_nested_batch_cannot_write_its_error_log() { s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); // A folder as the log path: the log write fails while every file succeeds. let batch = json!({"source": "open", "steps": [], "output": format!("{dir}/out"), "format": "png", "errorLog": dir}); - s.actions.list.push(Action::new("Run", vec![ActionStep::new("file.automate.batch", batch), ActionStep::new("layer.new.layer", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Run", vec![ActionStep::new("file.automate.batch", batch), ActionStep::new("layer.new.layer", json!({}))])).unwrap(); let layers = s.active().unwrap().doc.layers.len(); let played = s.execute("actions.play", json!({"action": "Run"})).unwrap(); let failed = &played["failed"]; diff --git a/crates/engine-core/src/cmd/actions_edit_cmds.rs b/crates/engine-core/src/cmd/actions_edit_cmds.rs index ef2cfed208..d3d7b28259 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds.rs @@ -7,6 +7,7 @@ //! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like //! `actions.move` and `actions.delete`. +use crate::actions_cmds::ActionsExt; use serde_json::{Value, json}; use crate::actions_cmds::{ActionStep, flush_recording, list_error, not_playing, note_automation_edit, pending_steps, resolve, shift_action_calls}; @@ -78,7 +79,7 @@ fn is_step_command(id: &str) -> bool { fn insert(s: &mut Session, p: &Value) -> Result { let cmd = "actions.insert"; not_playing(s, cmd)?; - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; let id = match p.get("id") { Some(Value::String(id)) if !id.trim().is_empty() => id.trim().to_string(), _ => return Err(bad(cmd, "needs `id`, the command the step runs")), @@ -94,12 +95,12 @@ fn insert(s: &mut Session, p: &Value) -> Result { if id == "actions.play" { // Refuse the one cycle visible here; deeper ones are caught at playback. let target = params.get("action"); - let is_self = target.and_then(Value::as_str) == Some(s.actions.list.actions()[idx].name.as_str()) || target.and_then(Value::as_u64) == Some(idx as u64); + let is_self = target.and_then(Value::as_str) == Some(s.actions().list.actions()[idx].name.as_str()) || target.and_then(Value::as_u64) == Some(idx as u64); if is_self { return Err(bad(cmd, "an action cannot play itself")); } } - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); let at = index(p, "at", cmd)?.unwrap_or(len); if at > len { return Err(bad(cmd, format!("`at` {at} is past the last step ({len})"))); @@ -108,10 +109,10 @@ fn insert(s: &mut Session, p: &Value) -> Result { flush_recording(s)?; } let is_stop = id == crate::atn_cmds::STOP_MESSAGE; - s.actions.list.insert_step(idx, at, ActionStep::new(id, params)).map_err(|e| list_error(cmd, e))?; + s.actions_mut().list.insert_step(idx, at, ActionStep::new(id, params)).map_err(|e| list_error(cmd, e))?; // A newly inserted Stop shows its message in the app. Duplicates keep their own flags. if is_stop { - s.actions.list.set_dialog(idx, at, true).map_err(|e| list_error(cmd, e))?; + s.actions_mut().list.set_dialog(idx, at, true).map_err(|e| list_error(cmd, e))?; } note_automation_edit(s, idx); Ok(step_result(s, idx, at)) @@ -119,7 +120,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { /// The result of an insert or a step duplicate: step `at` of action `idx` as it now stands. fn step_result(s: &Session, idx: usize, at: usize) -> Value { - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; json!({"action": action.name, "step": at, "id": action.steps[at].command, "steps": action.steps.len()}) } @@ -133,16 +134,16 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { } return duplicate_set(s, set.as_str().ok_or_else(|| bad(cmd, "set must be a name"))?); } - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; if let Some(step) = index(p, "step", cmd)? { - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); if step >= len { return Err(bad(cmd, "step is out of range")); } if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } - s.actions.list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?; + s.actions_mut().list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?; note_automation_edit(s, idx); let mut result = step_result(s, idx, step + 1); result["index"] = json!(idx); @@ -151,8 +152,8 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { if s.recording.target.is_some() { return Err(bad(cmd, "stop recording before duplicating an action")); } - let at = s.actions.list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?; - let copy = &s.actions.list.actions()[at]; + let at = s.actions_mut().list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?; + let copy = &s.actions().list.actions()[at]; Ok(json!({"action": copy.name, "index": at, "steps": copy.steps.len()})) } @@ -166,9 +167,9 @@ fn duplicate_set(s: &mut Session, source: &str) -> Result { if !sets.iter().any(|name| name == source) { return Err(bad(cmd, "the selected set no longer exists")); } - let name = s.actions.list.duplicate_set(source, shift_action_calls).map_err(|e| list_error(cmd, e))?; - let copies = s.actions.list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count(); - match s.actions.list.actions().iter().position(|action| action.set.as_deref() == Some(name.as_str())) { + let name = s.actions_mut().list.duplicate_set(source, shift_action_calls).map_err(|e| list_error(cmd, e))?; + let copies = s.actions().list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count(); + match s.actions().list.actions().iter().position(|action| action.set.as_deref() == Some(name.as_str())) { Some(at) => Ok(json!({"set": name, "index": at, "actions": copies})), None => Ok(json!({"set": name, "actions": 0})), } @@ -179,21 +180,21 @@ fn duplicate_set(s: &mut Session, source: &str) -> Result { fn dialog(s: &mut Session, p: &Value) -> Result { let cmd = "actions.dialog"; not_playing(s, cmd)?; - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; let enabled = match p.get("enabled") { None | Some(Value::Null) => None, Some(Value::Bool(b)) => Some(*b), Some(_) => return Err(bad(cmd, "`enabled` must be true or false")), }; let step = index(p, "step", cmd)?; - let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count()); + let len = s.actions().list.step_count(idx).saturating_add(pending_steps(s, idx).count()); if step.is_some_and(|step| step >= len) { return Err(bad(cmd, "step is out of range")); } if s.recording.target.is_some_and(|(_, i)| i == idx) { flush_recording(s)?; } - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; // One step, or every step: on unless all already are. let edits: Vec<(usize, bool)> = match step { Some(step) => vec![(step, enabled.unwrap_or(!action.dialogs.contains(&step)))], @@ -203,31 +204,31 @@ fn dialog(s: &mut Session, p: &Value) -> Result { } }; for (step, on) in edits { - s.actions.list.set_dialog(idx, step, on).map_err(|e| list_error(cmd, e))?; + s.actions_mut().list.set_dialog(idx, step, on).map_err(|e| list_error(cmd, e))?; } - let action = &s.actions.list.actions()[idx]; + let action = &s.actions().list.actions()[idx]; Ok(json!({"action": action.name, "dialogs": action.dialogs})) } fn assign_set(s: &mut Session, p: &Value) -> Result { let cmd = "actions.assignSet"; not_playing(s, cmd)?; - let idx = resolve(s.actions.list.actions(), p, cmd)?; + let idx = resolve(s.actions().list.actions(), p, cmd)?; let set = match p.get("set") { None | Some(Value::Null) => None, Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(Value::String(_)) => return Err(bad(cmd, "`set` is empty; pass null to take the action out of its set")), Some(_) => return Err(bad(cmd, "`set` must be a name or null")), }; - s.actions.list.assign_set(idx, set).map_err(|e| list_error(cmd, e))?; - let action = &s.actions.list.actions()[idx]; + s.actions_mut().list.assign_set(idx, set).map_err(|e| list_error(cmd, e))?; + let action = &s.actions().list.actions()[idx]; Ok(json!({"action": action.name, "set": action.set})) } /// Every set name, in the Actions panel's order: the sets of the actions as they first appear, /// then the empty ones New Set made. pub fn set_names(s: &Session) -> Vec { - s.actions.list.sets().into_iter().map(str::to_owned).collect() + s.actions().list.sets().into_iter().map(str::to_owned).collect() } /// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New @@ -245,7 +246,7 @@ fn new_set(s: &mut Session, p: &Value) -> Result { if names.contains(&name) { return Err(bad(cmd, format!("a set named `{name}` already exists"))); } - s.actions.list.new_set(&name).map_err(|e| list_error(cmd, e))?; + s.actions_mut().list.new_set(&name).map_err(|e| list_error(cmd, e))?; Ok(json!({"set": name})) } @@ -503,13 +504,14 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::Action; fn session_with(steps: &[&str]) -> Session { let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.actions.list.push(Action::new("A", steps.iter().map(|id| ActionStep::new(*id, json!({}))).collect())).unwrap(); + s.actions_mut().list.push(Action::new("A", steps.iter().map(|id| ActionStep::new(*id, json!({}))).collect())).unwrap(); s } @@ -522,14 +524,14 @@ mod tests { .execute("actions.insert", json!({"action": "A", "at": 1, "id": "actions.stopMessage", "params": {"message": "Check", "allowContinue": true}})) .unwrap(); assert_eq!((r["step"].as_u64(), r["steps"].as_u64()), (Some(1), Some(4))); - let a = &s.actions.list.actions()[0]; + let a = &s.actions().list.actions()[0]; assert_eq!(a.steps[1], ActionStep::new("actions.stopMessage", json!({"message": "Check", "allowContinue": true}))); assert_eq!(a.disabled.iter().copied().collect::>(), [2], "the switched-off step moved down one"); assert_eq!(a.dialogs.iter().copied().collect::>(), [1, 3], "the inserted Stop's dialog is on; the old toggle moved down one"); // Default position: the end. A bare id works for a parameterless command. let r = s.execute("actions.insert", json!({"action": 0, "id": "layer.new.layer"})).unwrap(); assert_eq!(r["step"], 4); - assert_eq!(s.actions.list.actions()[0].steps[4].command, "layer.new.layer"); + assert_eq!(s.actions().list.actions()[0].steps[4].command, "layer.new.layer"); // Playback runs the inserted stop and continues past it. let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert_eq!(played["ran"], 4, "{played}"); @@ -544,7 +546,7 @@ mod tests { s.execute("actions.insert", json!({"action": "A", "at": 0, "id": "select.all"})).unwrap(); s.execute("layer.new.layer", json!({"name": "Two"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect(); + let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect(); assert_eq!(ids, ["select.all", "layer.new.layer", "layer.new.layer"]); } @@ -560,14 +562,14 @@ mod tests { assert_eq!(s.execute("actions.get", json!({"action": "A"})).unwrap()["dialogs"], json!([0, 1])); // Deleting a step keeps the flags of the others in place. s.execute("actions.delete", json!({"action": "A", "step": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[0].dialogs.iter().copied().collect::>(), [0]); + assert_eq!(s.actions().list.actions()[0].dialogs.iter().copied().collect::>(), [0]); } #[test] fn conditional_tests_the_document_and_plays_a_branch() { let mut s = session_with(&[]); - s.actions.list.push(Action::new("Yes", vec![ActionStep::new("layer.new.layer", json!({"name": "yes"}))])).unwrap(); - s.actions.list.push(Action::new("No", vec![ActionStep::new("layer.new.layer", json!({"name": "no"}))])).unwrap(); + s.actions_mut().list.push(Action::new("Yes", vec![ActionStep::new("layer.new.layer", json!({"name": "yes"}))])).unwrap(); + s.actions_mut().list.push(Action::new("No", vec![ActionStep::new("layer.new.layer", json!({"name": "no"}))])).unwrap(); let names = |s: &Session| s.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).collect::>(); // 8 × 8: square, not landscape; one Background: no layers yet. for (cond, expect) in [ @@ -601,11 +603,11 @@ mod tests { let r = s.execute("actions.conditional", json!({"if": "landscape", "then": "Yes"})).unwrap(); assert!(r["played"].is_null()); // A failing branch reports like a nested Play, and stops a calling action. - s.actions.list.push(Action::new("Bad", vec![ActionStep::new("layer.delete", json!({"layer": 999}))])).unwrap(); + s.actions_mut().list.push(Action::new("Bad", vec![ActionStep::new("layer.delete", json!({"layer": 999}))])).unwrap(); let r = s.execute("actions.conditional", json!({"if": "always", "then": "Bad"})).unwrap(); assert!(r["failed"].is_object(), "{r}"); assert!(crate::actions_cmds::nested_failure("actions.conditional", &r).is_some()); - s.actions + s.actions_mut() .list .push(Action::new( "Caller", @@ -648,7 +650,7 @@ mod tests { let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); let i = r["index"].as_u64().unwrap() as usize; - assert_eq!(s.actions.list.actions()[i].set.as_deref(), Some("Retouch")); + assert_eq!(s.actions().list.actions()[i].set.as_deref(), Some("Retouch")); assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action"); assert!(s.execute("actions.record", json!({"set": 3})).is_err()); } @@ -657,16 +659,16 @@ mod tests { fn assign_set_moves_an_action_between_folders() { let mut s = session_with(&["select.all"]); assert_eq!(s.execute("actions.assignSet", json!({"action": "A", "set": " Retouch "})).unwrap()["set"], "Retouch"); - assert_eq!(s.actions.list.actions()[0].set.as_deref(), Some("Retouch")); + assert_eq!(s.actions().list.actions()[0].set.as_deref(), Some("Retouch")); assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["set"], "Retouch"); assert_eq!(s.execute("actions.assignSet", json!({"action": 0, "set": null})).unwrap()["set"], Value::Null); - assert_eq!(s.actions.list.actions()[0].set, None); + assert_eq!(s.actions().list.actions()[0].set, None); } #[test] fn bad_params_fail_gracefully() { let mut s = session_with(&["select.all"]); - let before = s.actions.list.clone(); + let before = s.actions().list.clone(); for p in [ json!({}), json!({"action": "A"}), @@ -689,9 +691,9 @@ mod tests { for p in [json!({}), json!({"action": "A", "set": ""}), json!({"action": "A", "set": 7}), json!({"action": "B", "set": "S"})] { assert!(s.execute("actions.assignSet", p.clone()).is_err(), "{p}"); } - assert_eq!(s.actions.list, before, "rejected edits change nothing"); + assert_eq!(s.actions().list, before, "rejected edits change nothing"); // Nothing edits during playback. - s.actions.list.push(Action::new("Loop", vec![ActionStep::new("actions.insert", json!({"action": "A", "id": "select.all"}))])).unwrap(); + s.actions_mut().list.push(Action::new("Loop", vec![ActionStep::new("actions.insert", json!({"action": "A", "id": "select.all"}))])).unwrap(); let played = s.execute("actions.play", json!({"action": "Loop"})).unwrap(); assert!(played["failed"]["error"].as_str().unwrap().contains("playback"), "{played}"); } @@ -699,7 +701,7 @@ mod tests { fn record_conditional(width: u32, height: u32) -> (Session, usize) { let mut s = crate::session(); s.execute("file.new", json!({"width": width, "height": height})).unwrap(); - s.actions.list.push(Action::new("Tall", vec![ActionStep::new("layer.new.layer", json!({"name": "Tall"}))])).unwrap(); + s.actions_mut().list.push(Action::new("Tall", vec![ActionStep::new("layer.new.layer", json!({"name": "Tall"}))])).unwrap(); let layers = s.active().unwrap().doc.walk().len(); s.execute("actions.record", json!({"name": "Parent"})).unwrap(); s.execute("actions.conditional", json!({"if": "portrait", "then": "Tall", "else": null})).unwrap(); @@ -708,7 +710,7 @@ mod tests { } fn parent_steps(s: &Session) -> Vec { - s.actions.list.actions().iter().find(|a| a.name == "Parent").unwrap().steps.clone() + s.actions().list.actions().iter().find(|a| a.name == "Parent").unwrap().steps.clone() } #[test] diff --git a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs index 27a86f1f28..3fdbdf2e82 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands.rs @@ -5,6 +5,7 @@ //! The engine keeps what lies outside the list: the action shortcuts before and after, and where //! each document's history stood, so Edit › Undo offers the library undo only while no document //! edit came after it. +use crate::actions_cmds::ActionsExt; use std::collections::BTreeMap; use craft::automation::actions::{ActionList, ActionListError, LibraryEdit}; @@ -86,7 +87,7 @@ fn check_library_size(list: &ActionList, cmd: &str) -> Result<()> { /// save it, then makes it the list and keeps what its undo restores outside the list. /// `shortcuts` replaces every action shortcut (`None` keeps them). pub(crate) fn publish_library(s: &mut Session, cmd: &str, shortcuts: Option, edit: impl FnOnce(&mut ActionList) -> R) -> Result { - let mut list = s.actions.list.clone(); + let mut list = s.actions().list.clone(); let result = edit(&mut list); let kind = list.library_undo().ok_or_else(|| bad(cmd, "not an Actions library command"))?; check_library_size(&list, cmd)?; @@ -111,24 +112,24 @@ pub(crate) fn publish_library(s: &mut Session, cmd: &str, shortcuts: Option Result { const CMD: &str = "actions.clearAll"; confirmed_idle(s, p, CMD)?; - let count = s.actions.list.actions().len(); + let count = s.actions().list.actions().len(); let prefs = s.prefs(); let keys = prefs.shortcuts.keys().chain(prefs.alternate_shortcuts.keys()).any(|id| is_action_key(id)); // Before the store attaches, an empty list still clears the stored library. - if count != 0 || !s.actions.list.sets().is_empty() || keys || (s.preset_store().is_none() && !s.actions.replaced_before_attachment) { + if count != 0 || !s.actions().list.sets().is_empty() || keys || (s.preset_store().is_none() && !s.actions().replaced_before_attachment) { publish_library(s, CMD, Some(Shortcuts::new()), ActionList::clear_all)?; } Ok(json!({"cleared": count})) @@ -152,10 +153,10 @@ pub(super) fn reset(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(CMD, "`mode` must be append or replace")), }; // Appended beside a set of that name, the defaults get a set of their own (`PhotoCraft Basics 2`). - let set = if append { crate::preset_import_cmds::UniqueNames::new_exact(s.actions.list.sets()).unique(BASICS_SET) } else { BASICS_SET.to_owned() }; + let set = if append { crate::preset_import_cmds::UniqueNames::new_exact(s.actions().list.sets()).unique(BASICS_SET) } else { BASICS_SET.to_owned() }; let defaults = basics(&set); let merged = publish_library(s, CMD, (!append).then(Shortcuts::new), |list| list.reset(defaults, append, |_, _| {}))?; - let names: Vec<&str> = merged.added.iter().map(|&index| s.actions.list.actions()[index].name.as_str()).collect(); + let names: Vec<&str> = merged.added.iter().map(|&index| s.actions().list.actions()[index].name.as_str()).collect(); Ok(json!({"set": set, "appended": append, "actions": names})) } @@ -172,10 +173,10 @@ fn undo_state(s: &Session) -> Result<&LibraryUndo> { const CMD: &str = "actions.undoLibrary"; idle(s, CMD)?; let undo = s - .actions + .actions() .library_undo .as_deref() - .filter(|undo| s.actions.list.library_undo() == Some(undo.edit)) + .filter(|undo| s.actions().list.library_undo() == Some(undo.edit)) .ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?; if action_bindings(&s.prefs().shortcuts) != undo.after_shortcuts || action_bindings(&s.prefs().alternate_shortcuts) != undo.after_alternates { return Err(bad(CMD, "Actions shortcuts changed after the library edit")); @@ -203,10 +204,10 @@ pub(super) fn undo_enabled(s: &Session) -> std::result::Result<(), String> { pub(super) fn undo(s: &mut Session, _: &Value) -> Result { const CMD: &str = "actions.undoLibrary"; undo_state(s)?; - let undo = s.actions.library_undo.take().ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?; - s.actions.list.undo_library().map_err(|error| list_error(CMD, error))?; + let undo = s.actions_mut().library_undo.take().ok_or_else(|| list_error(CMD, ActionListError::NothingToUndo))?; + s.actions_mut().list.undo_library().map_err(|error| list_error(CMD, error))?; if s.preset_store().is_none() { - s.actions.replaced_before_attachment = undo.replaced_before_attachment; + s.actions_mut().replaced_before_attachment = undo.replaced_before_attachment; } replace_bindings(s, undo.shortcuts, undo.alternates); Ok(json!({"undone": true})) diff --git a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands/tests.rs b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands/tests.rs index 83786e1bf3..2b67adbc53 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds/library_commands/tests.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds/library_commands/tests.rs @@ -1,3 +1,5 @@ +use crate::preset_store::PresetStoreExt; +use crate::actions_cmds::ActionsExt; use crate::Session; use crate::actions_cmds::{Action, ActionStep, PLAY_SHORTCUT_PREFIX}; use crate::preset_store::{ACTIONS_FILE, MemBackend, PresetBackend, open}; @@ -6,7 +8,7 @@ use craft_psd::descriptor::UnicodeString; use serde_json::json; fn names(s: &Session) -> Vec<&str> { - s.actions.list.actions().iter().map(|action| action.name.as_str()).collect() + s.actions().list.actions().iter().map(|action| action.name.as_str()).collect() } fn b64(bytes: &[u8]) -> String { @@ -31,30 +33,30 @@ fn set(caption: &str, action: Option<(&str, u16)>) -> Vec { fn confirmed_clear_restores_both_shortcut_maps_without_document_history() { let mut s = crate::session(); s.execute("file.new", json!({"width":8,"height":8})).unwrap(); - s.actions.list.push(Action::new("Original", Vec::new())).unwrap(); - s.actions.list.new_set("Empty").unwrap(); + s.actions_mut().list.push(Action::new("Original", Vec::new())).unwrap(); + s.actions_mut().list.new_set("Empty").unwrap(); let shortcut = format!("{PLAY_SHORTCUT_PREFIX}Original"); s.edit_prefs(|prefs| { prefs.shortcuts.insert(shortcut.clone(), "F2".into()); prefs.alternate_shortcuts.insert(shortcut.clone(), vec!["F3".into()]); prefs.shortcuts.insert("file.save".into(), "Ctrl+S".into()); }); - let revision = s.actions.list.revision(); + let revision = s.actions().list.revision(); let history = s.active().unwrap().history.past_len(); assert!(s.execute("actions.clearAll", json!({"confirm":false})).is_err()); - assert_eq!(s.actions.list.revision(), revision); + assert_eq!(s.actions().list.revision(), revision); s.execute("actions.record", json!({"action":0})).unwrap(); assert!(s.execute("actions.clearAll", json!({"confirm":true})).is_err()); s.execute("actions.stop", json!({})).unwrap(); assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 1); - assert!(s.actions.list.actions().is_empty() && s.actions.list.sets().is_empty()); + assert!(s.actions().list.actions().is_empty() && s.actions().list.sets().is_empty()); assert!(!s.prefs().shortcuts.contains_key(&shortcut)); assert!(!s.prefs().alternate_shortcuts.contains_key(&shortcut)); assert_eq!(s.prefs().shortcuts["file.save"], "Ctrl+S"); assert_eq!(crate::actions_edit_cmds::undo_library_label(&s), Some("Undo Clear All Actions")); s.execute("actions.undoLibrary", json!({})).unwrap(); assert_eq!(names(&s), ["Original"]); - assert_eq!(s.actions.list.sets(), ["Empty"]); + assert_eq!(s.actions().list.sets(), ["Empty"]); assert_eq!(s.prefs().shortcuts[&shortcut], "F2"); assert_eq!(s.prefs().alternate_shortcuts[&shortcut], ["F3"]); assert_eq!(s.active().unwrap().history.past_len(), history); @@ -78,23 +80,23 @@ fn reset_appends_a_numbered_set_and_persists_it() { let store = MemBackend::default(); let mut s = crate::session(); s.attach_preset_store(open(Box::new(store.clone()))); - s.actions.list.new_set("Existing").unwrap(); + s.actions_mut().list.new_set("Existing").unwrap(); assert!(s.execute("actions.reset", json!({"confirm":true,"mode":"bad"})).is_err()); assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics"); assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics 2"); - assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics", "PhotoCraft Basics 2", "Existing"]); + assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics", "PhotoCraft Basics 2", "Existing"]); assert_eq!(names(&s), ["Invert Colors", "Desaturate", "Invert Colors 2", "Desaturate 2"]); - assert_eq!(s.actions.list.actions()[0].steps[0].command, "image.adjustments.invert"); - assert_eq!(s.actions.list.actions()[1].steps[0].command, "image.adjustments.desaturate"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, "image.adjustments.invert"); + assert_eq!(s.actions().list.actions()[1].steps[0].command, "image.adjustments.desaturate"); s.sync_preset_store(); let mut reopened = crate::session(); reopened.attach_preset_store(open(Box::new(store))); - assert_eq!(reopened.actions.list.actions(), s.actions.list.actions()); - assert_eq!(reopened.actions.list.sets(), s.actions.list.sets()); + assert_eq!(reopened.actions().list.actions(), s.actions().list.actions()); + assert_eq!(reopened.actions().list.sets(), s.actions().list.sets()); s.execute("actions.reset", json!({"confirm":true,"mode":"replace"})).unwrap(); - assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics"]); + assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics"]); s.execute("actions.undoLibrary", json!({})).unwrap(); - assert_eq!(s.actions.list.sets(), reopened.actions.list.sets()); + assert_eq!(s.actions().list.sets(), reopened.actions().list.sets()); assert!(s.execute("actions.undoLibrary", json!({})).is_err()); } @@ -102,7 +104,7 @@ fn reset_appends_a_numbered_set_and_persists_it() { fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() { let mut s = crate::session(); s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap(); - let prior = s.actions.list.actions().to_vec(); + let prior = s.actions().list.actions().to_vec(); let mut archive = set("Repeated", Some(("Action", 2))); archive.extend_from_slice(&set("Empty", None)[4..]); archive.extend_from_slice(&set("Repeated", Some(("Action", 3)))[4..]); @@ -110,10 +112,10 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() { bad.pop(); assert!(s.execute("actions.replace", json!({"confirm":true,"data":b64(&bad)})).is_err()); assert!(s.execute("actions.replace", json!({"data":b64(&archive)})).is_err()); - assert_eq!(s.actions.list.actions(), prior); + assert_eq!(s.actions().list.actions(), prior); let result = s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap(); assert_eq!(result["sets"], json!(["Repeated", "Empty", "Repeated 2"])); - assert_eq!(s.actions.list.sets(), ["Repeated", "Repeated 2", "Empty"]); + assert_eq!(s.actions().list.sets(), ["Repeated", "Repeated 2", "Empty"]); assert_eq!(names(&s), ["Action", "Action 2"]); assert_eq!(s.prefs().shortcuts[&format!("{PLAY_SHORTCUT_PREFIX}Action")], "F2"); assert_eq!(s.prefs().shortcuts[&format!("{PLAY_SHORTCUT_PREFIX}Action 2")], "F3"); @@ -123,7 +125,7 @@ fn whole_replace_validates_the_tail_and_keeps_every_set_in_order() { assert!(empty["actions"].as_array().unwrap().is_empty()); assert_eq!(crate::actions_edit_cmds::undo_library_label(&s), Some("Undo Replace Actions")); s.execute("actions.undoLibrary", json!({})).unwrap(); - assert_eq!(s.actions.list.actions(), prior); + assert_eq!(s.actions().list.actions(), prior); } // Two actions one set gives the same name keep their own function keys. @@ -147,7 +149,7 @@ fn whole_replace_resolves_unqualified_calls_in_their_own_set() { archive.extend_from_slice(&second[4..]); s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap(); assert_eq!(names(&s), ["Child", "Child 2", "Parent"]); - assert_eq!(s.actions.list.actions()[2].steps[0].params["action"], "Child 2"); + assert_eq!(s.actions().list.actions()[2].steps[0].params["action"], "Child 2"); } // A call that names its action's set reaches that set's action, renamed or not, and names the set @@ -169,7 +171,7 @@ fn whole_replace_follows_explicit_atn_set_scopes() { let mut s = crate::session(); let result = s.execute("actions.replace", json!({"confirm":true,"data":b64(&archive)})).unwrap(); assert_eq!(result["actions"], json!(["Target", "Target 2", "Caller"])); - let list = s.actions.list.actions(); + let list = s.actions().list.actions(); let calls: Vec<&serde_json::Value> = list[2].steps.iter().map(|step| &step.params).collect(); assert_eq!((calls[0]["action"].as_str(), calls[0]["set"].as_str()), (Some("Target 2"), Some("Second"))); assert_eq!(crate::file_cmds::batch_action(list, calls[0]).unwrap(), 1); @@ -212,7 +214,7 @@ fn shortcut_only_clear_restores_orphan_bindings_on_undo() { assert!(!s.prefs().alternate_shortcuts.contains_key(orphan)); assert_eq!(s.prefs().alternate_shortcuts["file.save"], ["F4"]); s.execute("actions.undoLibrary", json!({})).unwrap(); - assert!(s.actions.list.actions().is_empty()); + assert!(s.actions().list.actions().is_empty()); assert_eq!(s.prefs().shortcuts[orphan], "F2"); assert_eq!(s.prefs().alternate_shortcuts[orphan], ["F3"]); } @@ -223,7 +225,7 @@ fn pre_attachment_replacement_persists_without_reloading_disk_and_keeps_undo() { let store = MemBackend::default(); store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk","set":"Saved"}]}"#).unwrap(); let mut s = crate::session(); - s.actions.list.push(Action::new("Early", Vec::new())).unwrap(); + s.actions_mut().list.push(Action::new("Early", Vec::new())).unwrap(); s.execute("actions.reset", json!({"confirm":true,"mode":"replace"})).unwrap(); if undo_before_attachment { s.execute("actions.undoLibrary", json!({})).unwrap(); @@ -234,17 +236,17 @@ fn pre_attachment_replacement_persists_without_reloading_disk_and_keeps_undo() { continue; } - assert_eq!(s.actions.list.sets(), ["PhotoCraft Basics"]); + assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics"]); assert_eq!(names(&s), ["Invert Colors", "Desaturate"]); let mut reopened = crate::session(); assert!(reopened.attach_preset_store(open(Box::new(store.clone()))).is_empty()); - assert_eq!(reopened.actions.list.actions(), s.actions.list.actions()); + assert_eq!(reopened.actions().list.actions(), s.actions().list.actions()); s.execute("actions.undoLibrary", json!({})).unwrap(); assert_eq!(names(&s), ["Early"]); s.sync_preset_store(); let mut reopened = crate::session(); assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty()); - assert_eq!(reopened.actions.list.actions(), s.actions.list.actions()); + assert_eq!(reopened.actions().list.actions(), s.actions().list.actions()); } } @@ -253,16 +255,16 @@ fn pre_attachment_clear_remains_authoritative_after_an_ordinary_edit() { let store = MemBackend::default(); store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk"}]}"#).unwrap(); let mut s = crate::session(); - s.actions.list.push(Action::new("Early", Vec::new())).unwrap(); + s.actions_mut().list.push(Action::new("Early", Vec::new())).unwrap(); s.execute("actions.clearAll", json!({"confirm":true})).unwrap(); s.execute("actions.newSet", json!({"name":"New"})).unwrap(); assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty()); - assert!(s.actions.list.actions().is_empty()); - assert_eq!(s.actions.list.sets(), ["New"]); + assert!(s.actions().list.actions().is_empty()); + assert_eq!(s.actions().list.sets(), ["New"]); let mut reopened = crate::session(); assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty()); - assert!(reopened.actions.list.actions().is_empty()); - assert_eq!(reopened.actions.list.sets(), ["New"]); + assert!(reopened.actions().list.actions().is_empty()); + assert_eq!(reopened.actions().list.sets(), ["New"]); } #[test] @@ -272,16 +274,16 @@ fn empty_pre_attachment_clear_replaces_the_saved_library() { store.write(ACTIONS_FILE, br#"{"version":1,"actions":[{"name":"Disk"}]}"#).unwrap(); let mut s = crate::session(); assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 0); - let revision = s.actions.list.revision(); + let revision = s.actions().list.revision(); assert_eq!(s.execute("actions.clearAll", json!({"confirm":true})).unwrap()["cleared"], 0); - assert_eq!(s.actions.list.revision(), revision, "a second empty clear keeps the first undo"); + assert_eq!(s.actions().list.revision(), revision, "a second empty clear keeps the first undo"); if undo { s.execute("actions.undoLibrary", json!({})).unwrap(); } assert!(s.attach_preset_store(open(Box::new(store.clone()))).is_empty()); - assert_eq!(s.actions.list.actions().first().map(|action| action.name.as_str()), undo.then_some("Disk")); + assert_eq!(s.actions().list.actions().first().map(|action| action.name.as_str()), undo.then_some("Disk")); let mut reopened = crate::session(); assert!(reopened.attach_preset_store(open(Box::new(store))).is_empty()); - assert_eq!(reopened.actions.list.actions(), s.actions.list.actions()); + assert_eq!(reopened.actions().list.actions(), s.actions().list.actions()); } } diff --git a/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs b/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs index d68de77e4d..1ffba64a21 100644 --- a/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs +++ b/crates/engine-core/src/cmd/actions_edit_cmds/record_again.rs @@ -1,4 +1,5 @@ //! Record Again executes the selected command before replacing its stored settings. +use crate::actions_cmds::ActionsExt; use super::{Result, Session, Value, bad, index, json, not_playing, resolve}; use crate::actions_cmds::{ActionStep, list_error}; @@ -20,14 +21,14 @@ pub fn target(s: &Session, p: &Value) -> Result { } if let Some(revision) = p.get("revision") { let revision = revision.as_u64().ok_or_else(|| bad(COMMAND, "`revision` must be an unsigned integer"))?; - if revision != s.actions.list.revision() { + if revision != s.actions().list.revision() { return Err(bad(COMMAND, "the actions changed; select the step again")); } } - let action = resolve(s.actions.list.actions(), p, COMMAND)?; + let action = resolve(s.actions().list.actions(), p, COMMAND)?; let step = index(p, "step", COMMAND)?.ok_or_else(|| bad(COMMAND, "select a step"))?; let ActionStep { command: id, params } = - s.actions.list.action(action).and_then(|a| a.steps.get(step)).ok_or_else(|| bad(COMMAND, "step is out of range"))?; + s.actions().list.action(action).and_then(|a| a.steps.get(step)).ok_or_else(|| bad(COMMAND, "step is out of range"))?; let (command, params) = if id == crate::atn_cmds::MENU_ITEM { (crate::atn_cmds::menu_item_command(params)?.to_string(), json!({})) } else { (id.clone(), params.clone()) }; if command.starts_with("actions.") || !crate::commands::find(&command).is_some_and(|c| c.journal) { @@ -41,15 +42,15 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { let selected = target(s, p)?; let params = p.get("params").filter(|p| p.is_object()).cloned().ok_or_else(|| bad(COMMAND, "supply the step's new settings in `params`"))?; let original = - s.actions.list.action(selected.action).and_then(|a| a.steps.get(selected.step)).cloned().ok_or_else(|| bad(COMMAND, "step is out of range"))?; - let revision = s.actions.list.revision(); + s.actions().list.action(selected.action).and_then(|a| a.steps.get(selected.step)).cloned().ok_or_else(|| bad(COMMAND, "step is out of range"))?; + let revision = s.actions().list.revision(); // Resolve portable recorded targets for execution; keep their portable form in the step. let resolved = crate::actions_cmds::playback_params(s, &selected.command, ¶ms)?; let result = s.execute(&selected.command, resolved)?; - if s.actions.list.revision() != revision || s.actions.list.action(selected.action).and_then(|a| a.steps.get(selected.step)) != Some(&original) { + if s.actions().list.revision() != revision || s.actions().list.action(selected.action).and_then(|a| a.steps.get(selected.step)) != Some(&original) { return Err(bad(COMMAND, "the action changed during execution; its step was not overwritten")); } - s.actions.list.replace_step(selected.action, selected.step, ActionStep::new(selected.command.clone(), params)).map_err(|e| list_error(COMMAND, e))?; - let name = s.actions.list.actions()[selected.action].name.clone(); + s.actions_mut().list.replace_step(selected.action, selected.step, ActionStep::new(selected.command.clone(), params)).map_err(|e| list_error(COMMAND, e))?; + let name = s.actions().list.actions()[selected.action].name.clone(); Ok(json!({"action": name, "step": selected.step, "id": selected.command, "result": result})) } diff --git a/crates/engine-core/src/cmd/atn_cmds/artboard_section_tests.rs b/crates/engine-core/src/cmd/atn_cmds/artboard_section_tests.rs index e9005169a2..aff0189dea 100644 --- a/crates/engine-core/src/cmd/atn_cmds/artboard_section_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/artboard_section_tests.rs @@ -1,6 +1,7 @@ //! #10723: Layer › New › Artboard and Layer › New › Artboard from Layers, recorded as a Make of //! class `artboardSection` (`docs/atn.md`, "Recorded through the menus"). +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; use photocraft_doc::{Layer, LayerId}; @@ -121,7 +122,7 @@ fn recorded_steps_load_and_save_back_unchanged() { for (d, id, params) in cases { let (mut s, r) = load(vec![make_item(d.clone())]); assert_eq!(r["unsupported"], json!([]), "{r}"); - let ActionStep { command: got, params: p } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: got, params: p } = &s.actions().list.actions()[0].steps[0]; let mut p = p.clone(); p.as_object_mut().unwrap().remove(SOURCE); assert_eq!((got.as_str(), &p), (id, ¶ms)); @@ -198,7 +199,7 @@ fn native_steps_save_the_measured_keys() { for (id, p, d) in cases { assert_eq!(exported(id, &p).as_ref(), Some(&d), "{id} {p}"); let (s, _) = load(vec![make_item(d)]); - let ActionStep { command: got, params: back } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: got, params: back } = &s.actions().list.actions()[0].steps[0]; assert_eq!(got, id); assert!(back.get(SOURCE).is_none(), "{back}"); assert_eq!(exported(id, back).map(|d| d.to_bytes()), exported(id, &p).map(|d| d.to_bytes()), "{back}"); @@ -272,7 +273,7 @@ fn other_forms_keep_the_photoshop_step() { for d in forms { let (mut s, r) = load(vec![make_item(d.clone())]); assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes())); } } @@ -282,7 +283,7 @@ fn other_forms_keep_the_photoshop_step() { #[test] fn changed_or_damaged_steps_save_their_settings() { let (s, _) = load(vec![make_item(new_board("Hero", [20.0, 10.0, 70.0, 110.0])), make_item(from_layers("Cards"))]); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; let (mut board, mut cards) = (steps[0].params.clone(), steps[1].params.clone()); assert!(board.get(SOURCE).is_some() && cards.get(SOURCE).is_some(), "{board} {cards}"); board["rect"] = json!([0, 0, 10, 10]); diff --git a/crates/engine-core/src/cmd/atn_cmds/automate_tests.rs b/crates/engine-core/src/cmd/atn_cmds/automate_tests.rs index 9e4e438d3b..3f923a1ca7 100644 --- a/crates/engine-core/src/cmd/atn_cmds/automate_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/automate_tests.rs @@ -1,6 +1,7 @@ //! #10723: File › Automate › Fit Image steps, the script event measured in the reference //! application: class `cjsp`, then `Msge`, `Hght` and `Wdth` in pixels, `limit` (Don't Enlarge). +use crate::actions_cmds::ActionsExt; use super::steps_automate::{FIT_IMAGE, FIT_IMAGE_EVENT}; use super::*; use crate::actions_cmds::ActionStep; @@ -56,7 +57,7 @@ fn a_recorded_fit_image_step_loads_and_saves_back_unchanged() { ] { let (mut s, r) = load(vec![fit_item(d.clone())]); assert_eq!(r["unsupported"], json!([]), "{r}"); - let ActionStep { command: id, params: p } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: id, params: p } = &s.actions().list.actions()[0].steps[0]; assert_eq!(id, FIT_IMAGE); assert_eq!((p["width"].as_f64(), p["height"].as_f64(), &p["dontEnlarge"]), (Some(width), Some(height), &json!(dont_enlarge)), "{p}"); let back = saved(&mut s); @@ -72,7 +73,7 @@ fn a_recorded_fit_image_step_loads_and_saves_back_unchanged() { #[test] fn the_canonical_form_carries_only_the_settings() { let (s, _) = load(vec![fit_item(recorded("", 300.0, 200.0, false))]); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"width": 300, "height": 200, "dontEnlarge": false})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"width": 300, "height": 200, "dontEnlarge": false})); let item = export_item(FIT_IMAGE, &json!({"width": 300, "height": 200, "dontEnlarge": false}), "S").unwrap(); assert_eq!(item.descriptor.map(|d| d.to_bytes()), Some(recorded("", 300.0, 200.0, false).to_bytes())); } @@ -109,7 +110,7 @@ fn every_measured_message_form_maps_and_plays_alike() { { let (mut s, r) = load(vec![fit_item(d.clone())]); assert_eq!(r["unsupported"], json!([]), "{d:?}"); - let ActionStep { command: id, params: p } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: id, params: p } = &s.actions().list.actions()[0].steps[0]; assert_eq!((id.as_str(), p["width"].as_f64(), p["height"].as_f64(), &p["dontEnlarge"]), (FIT_IMAGE, Some(250.0), Some(180.0), &json!(true)), "{d:?}"); s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); @@ -176,7 +177,7 @@ fn other_forms_keep_the_photoshop_step() { for d in forms { let (mut s, r) = load(vec![fit_item(d.clone())]); assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); let back = saved(&mut s); assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::name(FIT_IMAGE_EVENT), Some(d.to_bytes()))); } @@ -223,7 +224,7 @@ fn changed_settings_save_with_the_recorded_message() { (other_class, changed_other_class), ] { let (s, _) = load(vec![fit_item(original.clone())]); - let mut p = s.actions.list.actions()[0].steps[0].params.clone(); + let mut p = s.actions().list.actions()[0].steps[0].params.clone(); assert!(p.get(SOURCE).is_some(), "{p}"); assert_eq!(export_item(FIT_IMAGE, &p, "S").and_then(|item| item.descriptor), Some(original)); p["width"] = json!(500); diff --git a/crates/engine-core/src/cmd/atn_cmds/files.rs b/crates/engine-core/src/cmd/atn_cmds/files.rs index f7cb0388a5..d7c76b6e4f 100644 --- a/crates/engine-core/src/cmd/atn_cmds/files.rs +++ b/crates/engine-core/src/cmd/atn_cmds/files.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::convert::{ReplacementSet, clip_name, export, import_first_with_keys}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; use crate::actions_cmds::ActionsFile; @@ -50,13 +51,13 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { // keeps it as an empty folder, like one New Set made, and `replace` drops the set's actions. if replace { // The function keys of the actions it replaces go with them. - let replaced: Vec = s.actions.list.actions().iter().filter(|a| a.set.as_deref() == Some(imp.set.as_str())).map(|a| a.name.clone()).collect(); + let replaced: Vec = s.actions().list.actions().iter().filter(|a| a.set.as_deref() == Some(imp.set.as_str())).map(|a| a.name.clone()).collect(); crate::actions_cmds::remove_shortcuts(s, replaced.iter().map(String::as_str)); } let file = ActionsFile::new(imp.actions, vec![imp.set.clone()]); // Play, Conditional, Batch and Create Droplet steps call actions by name: follow the renames in // the actions just loaded, each target looked up once by the name the file gave it. - let merged = s.actions.list.merge_file(file, replace, |step, renames| { + let merged = s.actions_mut().list.merge_file(file, replace, |step, renames| { let (id, params) = (step.command.as_str(), &mut step.params); // A qualified Batch or Create Droplet reference belongs to the file's original set, not // to a foreign set which happens to have the destination override's name. @@ -81,10 +82,10 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { // Actions an automation client loads keep its gate when the user plays them. if s.authorize.is_some() { for &index in &merged.added { - s.actions.list.set_automation(index, true).map_err(|e| crate::actions_cmds::list_error(cmd, e))?; + s.actions_mut().list.set_automation(index, true).map_err(|e| crate::actions_cmds::list_error(cmd, e))?; } } - let names: Vec = merged.added.iter().map(|&index| s.actions.list.actions()[index].name.clone()).collect(); + let names: Vec = merged.added.iter().map(|&index| s.actions().list.actions()[index].name.clone()).collect(); // Keys go by the file's action order, so two actions the file gives one name keep their own. let keys: Vec<(String, String)> = function_keys.into_iter().filter_map(|(index, key)| Some((names.get(index)?.clone(), key))).collect(); if !keys.is_empty() { @@ -124,21 +125,21 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), }; let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { - let idx = crate::actions_cmds::resolve(s.actions.list.actions(), p, cmd)?; - let a = &s.actions.list.actions()[idx]; + let idx = crate::actions_cmds::resolve(s.actions().list.actions(), p, cmd)?; + let a = &s.actions().list.actions()[idx]; (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) } else if let Some(set) = set_param { - let list: Vec<&Action> = s.actions.list.actions().iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); + let list: Vec<&Action> = s.actions().list.actions().iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); // An empty set New Set made is written with no actions, as Photoshop saves one. - if list.is_empty() && !s.actions.list.sets().contains(&set.as_str()) { + if list.is_empty() && !s.actions().list.sets().contains(&set.as_str()) { return Err(bad(cmd, format!("no actions in a set named `{set}`"))); } (set, list) } else { - if s.actions.list.actions().is_empty() { + if s.actions().list.actions().is_empty() { return Err(bad(cmd, "there are no actions to save")); } - (DEFAULT_SET.to_string(), s.actions.list.actions().iter().collect()) + (DEFAULT_SET.to_string(), s.actions().list.actions().iter().collect()) }; let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); let keys: Vec<(String, String)> = diff --git a/crates/engine-core/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine-core/src/cmd/atn_cmds/frame_section_tests.rs index be71cfde3c..3f7db1ac2a 100644 --- a/crates/engine-core/src/cmd/atn_cmds/frame_section_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/frame_section_tests.rs @@ -1,6 +1,7 @@ //! #10723: Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection` //! (`docs/atn.md`, "Recorded through the menus"). +use crate::actions_cmds::ActionsExt; use super::*; use photocraft_doc::{Layer, LayerId}; use photocraft_geom::Rect; @@ -116,7 +117,7 @@ fn recorded_steps_load_and_save_back_unchanged() { let (mut s, r) = load(vec![d.clone()]); assert_eq!(r["unsupported"], json!([]), "{r}"); let (id, p) = { - let step = &s.actions.list.actions()[0].steps[0]; + let step = &s.actions().list.actions()[0].steps[0]; (&step.command, &step.params) }; let mut p = p.clone(); @@ -185,7 +186,7 @@ fn native_steps_save_the_measured_keys() { ] { assert_eq!(exported(&p), Some(d.clone()), "{p}"); let (s, _) = load(vec![d]); - assert_eq!(s.actions.list.actions()[0].steps[0], craft::automation::actions::ActionStep::new(FRAME, back), "{p}"); + assert_eq!(s.actions().list.actions()[0].steps[0], craft::automation::actions::ActionStep::new(FRAME, back), "{p}"); } } @@ -234,7 +235,7 @@ fn other_forms_keep_the_photoshop_step() { for d in forms { let (mut s, r) = load(vec![d.clone()]); assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); assert_eq!(saved(&mut s), Some(d.to_bytes())); } } @@ -244,7 +245,7 @@ fn other_forms_keep_the_photoshop_step() { #[test] fn changed_or_damaged_steps_save_their_settings() { let (s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); - let mut p = s.actions.list.actions()[0].steps[0].params.clone(); + let mut p = s.actions().list.actions()[0].steps[0].params.clone(); assert!(p.get(SOURCE).is_some(), "{p}"); p["layer"] = json!("Other"); assert_eq!(exported(&p), Some(canonical(by_name("Other"), Some("Frame 1")))); diff --git a/crates/engine-core/src/cmd/atn_cmds/layer_list_tests.rs b/crates/engine-core/src/cmd/atn_cmds/layer_list_tests.rs index ea4a62c3de..2fc6968a7f 100644 --- a/crates/engine-core/src/cmd/atn_cmds/layer_list_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/layer_list_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; @@ -32,15 +33,15 @@ fn opacities(s: &Session) -> Vec { #[test] fn the_layers_list_survives_a_strict_roundtrip() { let (mut s, first, second) = two_layers(); - s.actions.list.push(Action::new("Targets", vec![ActionStep::new("layer.setProps", json!({"layers": [first, second], "opacity": 0.5}))])).unwrap(); - s.actions.list.assign_set(0, Some("S".into())).unwrap(); + s.actions_mut().list.push(Action::new("Targets", vec![ActionStep::new("layer.setProps", json!({"layers": [first, second], "opacity": 0.5}))])).unwrap(); + s.actions_mut().list.assign_set(0, Some("S".into())).unwrap(); s.execute("actions.play", json!({"action": "Targets"})).unwrap(); assert_eq!(opacities(&s), [0.5, 0.5]); s.execute("edit.undo", json!({})).unwrap(); assert_eq!(opacities(&s), [1.0, 1.0]); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let (bytes, skipped) = export("S", &[&action], &[], false).unwrap(); assert_eq!(skipped, []); let file = atn::parse(&bytes).unwrap(); diff --git a/crates/engine-core/src/cmd/atn_cmds/layer_props_tests.rs b/crates/engine-core/src/cmd/atn_cmds/layer_props_tests.rs index eeae01c35e..af0e6efbae 100644 --- a/crates/engine-core/src/cmd/atn_cmds/layer_props_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/layer_props_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::{ActionList, ActionStep, ActionsFile}; @@ -132,7 +133,7 @@ fn expanded_properties_replay_like_direct_edits_at_every_depth() { let action = Action::new("Properties", vec![ActionStep::new("layer.setProps", params)]); let (bytes, _) = export("Set", &[&action], &[], false).unwrap(); let mut replay = prepare(); - replay.actions.list = ActionList::from_file(ActionsFile::new(import(&bytes).unwrap().actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(import(&bytes).unwrap().actions, Vec::new())); let result = replay.execute("actions.play", json!({"action": "Properties"})).unwrap(); assert!(result["failed"].is_null(), "{result}"); assert_eq!(result["ran"], 3); diff --git a/crates/engine-core/src/cmd/atn_cmds/measurement_tests.rs b/crates/engine-core/src/cmd/atn_cmds/measurement_tests.rs index 1d1096a11f..826386b3e8 100644 --- a/crates/engine-core/src/cmd/atn_cmds/measurement_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/measurement_tests.rs @@ -1,6 +1,7 @@ //! #10723: Image › Analysis › Set Measurement Scale › Custom steps, recorded as a Set of the //! document's `measurementScale` property (`docs/atn.md`, "Recorded through the menus"). +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -59,7 +60,7 @@ fn a_recorded_scale_step_loads_and_saves_back_unchanged() { let d = recorded(t); let (mut s, r) = load(vec![set_item(d.clone())]); assert_eq!(r["unsupported"], json!([]), "{r}"); - let ActionStep { command: id, params: p } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: id, params: p } = &s.actions().list.actions()[0].steps[0]; assert_eq!(id, SET_SCALE); assert_eq!( (&p["preset"], p["pixelLength"].as_f64(), p["logicalLength"].as_f64(), &p["units"]), @@ -96,7 +97,7 @@ fn a_native_scale_saves_the_measured_form() { let d = export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor).unwrap(); assert_eq!(d, recorded(scale("measurementScale", 120, 3.0, "mm"))); let (s, _) = load(vec![set_item(d)]); - assert_eq!(s.actions.list.actions()[0].steps[0].params, p); + assert_eq!(s.actions().list.actions()[0].steps[0].params, p); // `logicalUnits` is the command's other spelling of `units`, and the preset defaults to custom. let other = json!({"pixelLength": 120, "logicalLength": 3, "logicalUnits": "mm"}); assert_eq!(export_item(SET_SCALE, &other, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 120, 3.0, "mm")))); @@ -156,7 +157,7 @@ fn other_forms_keep_the_photoshop_step() { for d in forms { let (mut s, r) = load(vec![set_item(d.clone())]); assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes())); } } @@ -166,7 +167,7 @@ fn other_forms_keep_the_photoshop_step() { #[test] fn changed_or_damaged_steps_save_their_settings() { let (s, _) = load(vec![set_item(recorded(scale("null", 100, 25.4, "inches")))]); - let mut p = s.actions.list.actions()[0].steps[0].params.clone(); + let mut p = s.actions().list.actions()[0].steps[0].params.clone(); assert!(p.get(SOURCE).is_some(), "{p}"); p["units"] = json!("cm"); assert_eq!(export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 100, 25.4, "cm")))); diff --git a/crates/engine-core/src/cmd/atn_cmds/mode_change_tests.rs b/crates/engine-core/src/cmd/atn_cmds/mode_change_tests.rs index e28f64274d..42222b988e 100644 --- a/crates/engine-core/src/cmd/atn_cmds/mode_change_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/mode_change_tests.rs @@ -2,6 +2,7 @@ //! reference application: class `cjsp`, then `Msge`, `SrcM` (`Cndn` per ticked source mode) and //! `DstM` (the target mode's object). +use crate::actions_cmds::ActionsExt; use super::stylize_tests::{load_items, saved_items}; use super::*; use photocraft_color::ColorMode; @@ -65,7 +66,7 @@ fn every_measured_source_loads_and_saves_back() { let d = recorded("Recorded message", &codes, target("Grys")); let mut s = load_items(vec![item(d.clone())]); let (id, p) = { - let step = &s.actions.list.actions()[0].steps[0]; + let step = &s.actions().list.actions()[0].steps[0]; (&step.command, &step.params) }; assert_eq!(id, ID, "{codes:?}"); @@ -84,7 +85,7 @@ fn every_native_target_loads_and_the_canonical_form_carries_only_the_settings() let d = recorded("", &["URGB", "ULab"], target(class)); let s = load_items(vec![item(d.clone())]); let (id, p) = { - let step = &s.actions.list.actions()[0].steps[0]; + let step = &s.actions().list.actions()[0].steps[0]; (&step.command, &step.params) }; assert_eq!((id.as_str(), p), (ID, &json!({"from": ["rgb", "lab"], "to": to}))); @@ -139,7 +140,7 @@ fn a_loaded_step_plays_like_the_reference() { (recorded("", &["UGry", "URGB"], target("LbCM")), ColorMode::Lab), ] { let mut s = load_items(vec![item(d.clone())]); - assert_eq!(s.actions.list.actions()[0].steps[0].command, ID, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, ID, "{d:?}"); s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert_eq!(played["ran"], 1, "{played}"); @@ -200,7 +201,7 @@ fn other_forms_keep_the_photoshop_step() { } for d in forms.into_iter().chain([wrong_type]) { let mut s = load_items(vec![item(d.clone())]); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{d:?}"); let back = saved_items(&mut s); assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::name(EVENT), Some(d.to_bytes()))); assert_eq!(back[0].dictionary, b"Conditional Mode Change", "{d:?}"); @@ -244,7 +245,7 @@ fn changed_settings_save_into_the_recorded_descriptor() { (other_class, changed_other_class), ] { let s = load_items(vec![item(original.clone())]); - let mut p = s.actions.list.actions()[0].steps[0].params.clone(); + let mut p = s.actions().list.actions()[0].steps[0].params.clone(); assert!(p.get(SOURCE).is_some(), "{p}"); assert_eq!(exported(&p), Some(original)); p["from"] = json!(["cmyk", "rgb"]); @@ -256,7 +257,7 @@ fn changed_settings_save_into_the_recorded_descriptor() { Descriptor::new("cjsp").with("DstM", target(dst)).with("SrcM", src_m(sources)).with("Msge", D::Text(UnicodeString::new_nul("Recorded message"))) }; let s = load_items(vec![item(reordered(&["UGry"], "RGBM"))]); - let mut p = s.actions.list.actions()[0].steps[0].params.clone(); + let mut p = s.actions().list.actions()[0].steps[0].params.clone(); assert_eq!((&p["from"], &p["to"]), (&json!(["grayscale"]), &json!("rgb")), "{p}"); assert_eq!(exported(&p), Some(reordered(&["UGry"], "RGBM"))); p["from"] = json!(["cmyk", "rgb"]); diff --git a/crates/engine-core/src/cmd/atn_cmds/path_tests.rs b/crates/engine-core/src/cmd/atn_cmds/path_tests.rs index d536857589..8ad1b81807 100644 --- a/crates/engine-core/src/cmd/atn_cmds/path_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/path_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem, UnicodeString, atn}; use super::*; use crate::actions_cmds::{ActionList, ActionsFile}; @@ -119,15 +120,15 @@ fn whole_atn_and_native_insert_path_replay_keep_geometry() { let mut s = crate::session(); s.execute("file.new", json!({"width":400,"height":300})).unwrap(); s.execute("path.set", json!({"name":"Source","path":crate::vector_cmds::path_json(&expected)})).unwrap(); - s.actions.list.push(Action::new("Captured", Vec::new())).unwrap(); + s.actions_mut().list.push(Action::new("Captured", Vec::new())).unwrap(); let revision = s.active().unwrap().revision; s.execute("actions.insertPath", json!({"action":0,"name":"Source"})).unwrap(); assert_eq!(s.active().unwrap().revision, revision); - let (bytes, skipped) = super::super::export("S", &[&s.actions.list.actions()[0]], &[], false).unwrap(); + let (bytes, skipped) = super::super::export("S", &[&s.actions().list.actions()[0]], &[], false).unwrap(); assert!(skipped.is_empty()); let imported = super::super::import(&bytes).unwrap(); assert!(imported.unsupported.is_empty()); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); s.execute("path.set", json!({"name":"Source","path":{"subpaths":[]}})).unwrap(); let played = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); diff --git a/crates/engine-core/src/cmd/atn_cmds/recorded_tools_tests.rs b/crates/engine-core/src/cmd/atn_cmds/recorded_tools_tests.rs index 2eae59c50b..ece3e1aec1 100644 --- a/crates/engine-core/src/cmd/atn_cmds/recorded_tools_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/recorded_tools_tests.rs @@ -2,6 +2,7 @@ //! gives them (measured in `docs/atn.md` › "Measured through dialogs and recordings"; once mapped, //! the events are listed with the supported events instead). +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -68,9 +69,9 @@ fn gradient_tool_steps_load_play_and_save_back() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&action(items))})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); + let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); assert_eq!(ids, ["layer.newFillLayer.gradient", "gradient.fill.set"]); - let set_params = &s.actions.list.actions()[0].steps[1].params; + let set_params = &s.actions().list.actions()[0].steps[1].params; assert_eq!( (set_params["angle"].as_f64(), set_params["scale"].as_f64(), set_params["align"].as_bool()), (Some(-35.0), Some(140.0), Some(false)), @@ -117,13 +118,13 @@ fn create_droplet_step_loads_plays_and_saves_back() { let recorded = droplet(&file, &out, &[("OvrO", D::Boolean(true))]); let mut s = crate::session(); // The action the droplet runs. - s.actions.list.push(crate::actions_cmds::Action::new("Sharpen", vec![ActionStep::new("filter.sharpen.sharpen", json!({}))])).unwrap(); - s.actions.list.assign_set(0, Some("Tools".into())).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Sharpen", vec![ActionStep::new("filter.sharpen.sharpen", json!({}))])).unwrap(); + s.actions_mut().list.assign_set(0, Some("Tools".into())).unwrap(); let loaded = s .execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&action(vec![step(b"CrtD", "Create Droplet", recorded.clone())]))})) .unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - let a = s.actions.list.actions().iter().find(|a| a.name == "A").unwrap(); + let a = s.actions().list.actions().iter().find(|a| a.name == "A").unwrap(); assert_eq!( a.steps, [ActionStep::new("file.automate.createDroplet", json!({"path": file, "action": "Sharpen", "set": "Tools", "output": out, "overrideOpen": true}))] @@ -205,11 +206,11 @@ fn create_droplet_steps_follow_a_renamed_loaded_action() { }) .unwrap(); let mut s = crate::session(); - s.actions.list.push(crate::actions_cmds::Action::new("Sharpen", vec![])).unwrap(); - s.actions.list.assign_set(0, Some("Tools".into())).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Sharpen", vec![])).unwrap(); + s.actions_mut().list.assign_set(0, Some("Tools".into())).unwrap(); let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&file), "set": "Loaded"})).unwrap(); assert_eq!(r["actions"], json!(["Sharpen 2", "A"]), "{r}"); - let a = s.actions.list.actions().iter().find(|a| a.name == "A").unwrap(); + let a = s.actions().list.actions().iter().find(|a| a.name == "A").unwrap(); assert_eq!(a.steps[0].params["action"], "Sharpen 2", "{:?}", a.steps[0]); assert_eq!((&a.steps[1].params["action"], &a.steps[1].params["set"]), (&json!("Sharpen 2"), &json!("Loaded")), "{:?}", a.steps[1]); } diff --git a/crates/engine-core/src/cmd/atn_cmds/render_tests.rs b/crates/engine-core/src/cmd/atn_cmds/render_tests.rs index 5a9e6160a8..5b182193fc 100644 --- a/crates/engine-core/src/cmd/atn_cmds/render_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/render_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -68,7 +69,7 @@ fn code_spellings_in_text_steps_keep_their_bytes_and_flags() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1, "{:?}", original.actions[0].items[0].event); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP); let saved = s.execute("actions.save", json!({"action": "Render"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let back = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); @@ -115,7 +116,7 @@ fn clouds_events_map_and_refuse_unrepresentable_native_settings() { fn clouds_recorded_through_the_dialog_save() { for id in ["filter.render.clouds", "filter.render.differenceClouds"] { let mut s = crate::session(); - s.actions.list.push(Action::new("Render", vec![ActionStep::new(id, json!({"seed": 0}))])).unwrap(); + s.actions_mut().list.push(Action::new("Render", vec![ActionStep::new(id, json!({"seed": 0}))])).unwrap(); let saved = s.execute("actions.save", json!({"action": "Render"})).unwrap(); assert_eq!(saved["skipped"], json!([]), "{id}"); let back = import(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); @@ -243,7 +244,7 @@ fn duplicate_render_keys_keep_their_bytes_and_flags() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1, "{event}/{key}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP); let saved = s.execute("actions.save", json!({"action": "Render"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let back = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); diff --git a/crates/engine-core/src/cmd/atn_cmds/selection_tests.rs b/crates/engine-core/src/cmd/atn_cmds/selection_tests.rs index 9be4a0c6f4..2478ec499b 100644 --- a/crates/engine-core/src/cmd/atn_cmds/selection_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/selection_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -98,9 +99,9 @@ fn assert_kept(id: &str, name: Option<&str>, descriptor: Descriptor) { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data":photocraft_paint::tile::b64_encode(&atn::write(&original).unwrap())})).unwrap(); assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1, "{id}/{name:?}/{descriptor:?}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP); - assert!(s.actions.list.actions()[0].disabled.contains(&0)); - assert!(s.actions.list.actions()[0].dialogs.contains(&0)); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP); + assert!(s.actions().list.actions()[0].disabled.contains(&0)); + assert!(s.actions().list.actions()[0].dialogs.contains(&0)); let saved = s.execute("actions.save", json!({"action":"Step"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); diff --git a/crates/engine-core/src/cmd/atn_cmds/stylize_tests.rs b/crates/engine-core/src/cmd/atn_cmds/stylize_tests.rs index fa0db81272..28cfd37ab6 100644 --- a/crates/engine-core/src/cmd/atn_cmds/stylize_tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/stylize_tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -12,7 +13,7 @@ fn parameterless_stylize_and_pixelate_events_use_both_event_id_forms() { ] { for event in [AtnEvent::Code(code), AtnEvent::name(name)] { let mut s = load_items(vec![AtnItem { event, descriptor: Some(desc("null")), ..Default::default() }]); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new(id, json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new(id, json!({}))]); assert_eq!(saved_items(&mut s)[0].descriptor, Some(desc("null"))); assert!(export_item(id, &json!({"layer": 17}), "Group D").is_none()); assert!(export_item(id, &json!({"target": "mask"}), "Group D").is_none()); @@ -167,14 +168,14 @@ fn measured_defaults_and_every_changed_value_round_trip_in_order() { item.event = AtnEvent::name(fixture.name); } let mut s = load_items(vec![item]); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new(fixture.id, params.clone())], "{} named={named}", fixture.code); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new(fixture.id, params.clone())], "{} named={named}", fixture.code); let saved = saved_items(&mut s); assert_eq!(saved[0].event, AtnEvent::Code(fixture.code.as_bytes().try_into().unwrap())); assert_eq!(saved[0].descriptor.as_ref(), Some(descriptor), "{} named={named}", fixture.code); } } let mut s = load_items(vec![code_item(fixture.code, desc("null"))]); - assert_eq!(s.actions.list.actions()[0].steps[0], ActionStep::new(fixture.id, fixture.defaults), "{} missing keys", fixture.code); + assert_eq!(s.actions().list.actions()[0].steps[0], ActionStep::new(fixture.id, fixture.defaults), "{} missing keys", fixture.code); assert_eq!(saved_items(&mut s)[0].descriptor, Some(fixture.default)); } } @@ -199,8 +200,8 @@ fn numeric_imports_clamp_measured_ranges() { for (input, expected) in [(i32::MIN, min), (min - 1, min), (min, min), (max, max), (max + 1, max), (i32::MAX, max)] { let value = if code == "Msc " { px(f64::from(input)) } else { D::Integer(input) }; let mut s = load_items(vec![code_item(code, desc("null").with(key, value))]); - assert_ne!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{code}/{key}"); - assert_eq!(s.actions.list.actions()[0].steps[0].params[param], expected, "{code}/{key}/{input}"); + assert_ne!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{code}/{key}"); + assert_eq!(s.actions().list.actions()[0].steps[0].params[param], expected, "{code}/{key}/{input}"); assert!(saved_items(&mut s)[0].descriptor.is_some()); } } @@ -220,8 +221,8 @@ fn trace_levels_clamp_on_import_and_play_at_the_boundary() { let mut item = code_item("TrcC", descriptor); item.with_dialog = true; let mut imported = load_items(vec![item]); - assert_eq!(imported.actions.list.actions()[0].steps[0].command, "filter.stylize.traceContour", "{level}/{name}"); - assert_eq!(imported.actions.list.actions()[0].steps[0].params["level"], clamped); + assert_eq!(imported.actions().list.actions()[0].steps[0].command, "filter.stylize.traceContour", "{level}/{name}"); + assert_eq!(imported.actions().list.actions()[0].steps[0].params["level"], clamped); let saved = saved_items(&mut imported); let expected = desc("null").with("Lvl ", D::Integer(clamped)).with("Edg ", enm("CntE", edge)); assert_eq!(saved[0].descriptor.as_ref().unwrap().to_bytes(), expected.to_bytes()); @@ -276,7 +277,7 @@ fn enum_values_map_exactly_and_unknown_descriptors_stay_kept() { ] { for (value, expected) in &values { let mut s = load_items(vec![code_item(code, desc("null").with(key, enm(ty, value)))]); - assert_eq!(s.actions.list.actions()[0].steps[0].params[param], *expected, "{code}/{value}"); + assert_eq!(s.actions().list.actions()[0].steps[0].params[param], *expected, "{code}/{value}"); assert_eq!(saved_items(&mut s)[0].descriptor.as_ref().unwrap().get(key), Some(&enm(ty, value))); } for value in [enm(ty, "????"), enm("Bad!", values[0].0), D::Boolean(true)] { @@ -286,9 +287,9 @@ fn enum_values_map_exactly_and_unknown_descriptors_stay_kept() { item.with_dialog = true; item.dialog_options = 2; let mut s = load_items(vec![item]); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{code}/{key}"); - assert!(s.actions.list.actions()[0].disabled.contains(&0)); - assert!(s.actions.list.actions()[0].dialogs.contains(&0)); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP, "{code}/{key}"); + assert!(s.actions().list.actions()[0].disabled.contains(&0)); + assert!(s.actions().list.actions()[0].dialogs.contains(&0)); let saved = saved_items(&mut s); assert_eq!(saved[0].descriptor, Some(descriptor)); assert!(!saved[0].enabled); @@ -303,7 +304,7 @@ fn enum_values_map_exactly_and_unknown_descriptors_stay_kept() { ("FndE", desc("null").with("unknown", D::Boolean(true))), ] { let mut s = load_items(vec![code_item(code, descriptor.clone())]); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP); assert_eq!(saved_items(&mut s)[0].descriptor, Some(descriptor)); } } @@ -337,7 +338,7 @@ fn exports_materialize_native_defaults_and_reject_unrepresentable_settings() { let mut params = fixture.defaults.clone(); params[key] = value; let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new(fixture.id, params)])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new(fixture.id, params)])).unwrap(); assert!(s.execute("actions.save", json!({"action":"A"})).is_err(), "{}/{key}", fixture.id); } let mut params = fixture.defaults.clone(); @@ -373,9 +374,9 @@ fn imported_group_d_playback_matches_direct_commands_across_modes_and_depths() { for (depth, mode) in [(8, "rgb"), (16, "rgb"), (32, "rgb"), (8, "gray"), (8, "cmyk"), (16, "lab")] { let mut imported = load_items(items.clone()); imported.execute("actions.setHistory", json!({"singleState": single_state})).unwrap(); - imported.actions.list.set_step(0, 10, false).unwrap(); - imported.actions.list.set_dialog(0, 0, true).unwrap(); - let steps = imported.actions.list.actions()[0].steps.clone(); + imported.actions_mut().list.set_step(0, 10, false).unwrap(); + imported.actions_mut().list.set_dialog(0, 0, true).unwrap(); + let steps = imported.actions().list.actions()[0].steps.clone(); let mut direct = crate::session(); for s in [&mut imported, &mut direct] { prepare_pattern(s, depth, mode); @@ -434,11 +435,11 @@ fn pixels(s: &Session) -> Vec<[f32; 4]> { fn native_and_measured_defaults_stay_distinct_through_playback() { use photocraft_algo::FilterParams; let mosaic = load_items(vec![code_item("Msc ", desc("null"))]); - let measured = &mosaic.actions.list.actions()[0].steps[0].params; + let measured = &mosaic.actions().list.actions()[0].steps[0].params; assert!(matches!(crate::filters::params_for("filter.pixelate.mosaic",&json!({})),Some(FilterParams::Mosaic{cell_size}) if cell_size==10.0)); assert!(matches!(crate::filters::params_for("filter.pixelate.mosaic",measured),Some(FilterParams::Mosaic{cell_size}) if cell_size==2.0)); let trace = load_items(vec![code_item("TrcC", desc("null"))]); - let measured = &trace.actions.list.actions()[0].steps[0].params; + let measured = &trace.actions().list.actions()[0].steps[0].params; assert!(matches!(crate::filters_ext::params_for("filter.stylize.traceContour", &json!({})), Some(FilterParams::TraceContour { upper: false, .. }))); assert!(matches!(crate::filters_ext::params_for("filter.stylize.traceContour", measured), Some(FilterParams::TraceContour { upper: true, .. }))); for id in ["filter.pixelate.mosaic", "filter.stylize.traceContour"] { @@ -466,7 +467,7 @@ fn tiles_and_pointillize_exports_drop_dialog_colours() { coloured["background"] = json!("#ffffff"); assert_eq!(export_item(id, &coloured, "Group D").unwrap().descriptor, plain, "{id}"); let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new(id, coloured)])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new(id, coloured)])).unwrap(); assert!(s.execute("actions.save", json!({"action":"A"})).is_ok(), "{id}"); } } diff --git a/crates/engine-core/src/cmd/atn_cmds/tests.rs b/crates/engine-core/src/cmd/atn_cmds/tests.rs index ae77cc0f2c..8a68cdbf4e 100644 --- a/crates/engine-core/src/cmd/atn_cmds/tests.rs +++ b/crates/engine-core/src/cmd/atn_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; @@ -303,7 +304,7 @@ fn layer_comp_apply_imports_plays_and_undoes() { 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}))]); + 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(); @@ -345,7 +346,7 @@ fn layer_comp_apply_round_trips_by_name() { assert_eq!(file.actions[0].items[0].descriptor, Some(descriptor)); let mut reloaded = crate::session(); reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap(); - assert_eq!(reloaded.actions.list.actions(), s.actions.list.actions()); + assert_eq!(reloaded.actions().list.actions(), s.actions().list.actions()); } // Local comp ids and the default comp cannot be resolved to a portable name at export. for params in [json!({}), json!({"comp": 1}), json!({"comp": null}), json!({"comp": true}), json!({"comp": []})] { @@ -374,8 +375,8 @@ fn layer_comp_apply_unknown_references_are_kept_and_stop_playback() { 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()); + 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(); @@ -407,7 +408,7 @@ fn load_maps_events_keeps_flags_and_plays() { r["unsupported"].as_array().unwrap().iter().map(|u| (u["event"].as_str().unwrap().into(), u["name"].as_str().unwrap().into())).collect(); assert_eq!(unsupported, [("slct".to_string(), "Select".to_string()), ("syntheticFill".to_string(), "Generative Fill".to_string())]); - let a = &s.actions.list.actions()[0]; + let a = &s.actions().list.actions()[0]; assert_eq!(a.set.as_deref(), Some("Test Set")); let ids: Vec<&str> = a.steps.iter().map(|st| st.command.as_str()).collect(); assert_eq!( @@ -432,7 +433,7 @@ fn load_maps_events_keeps_flags_and_plays() { assert_eq!(a.steps[7].params, json!({"action": "Finish"})); assert_eq!(a.dialogs.iter().copied().collect::>(), [0], "the dialog toggle is kept"); assert_eq!(a.disabled.iter().copied().collect::>(), [4, 8], "tool selections are switched off, as is the step the file had off"); - assert_eq!(s.actions.list.actions()[1].steps, [ActionStep::new("select.inverse", json!({}))]); + assert_eq!(s.actions().list.actions()[1].steps, [ActionStep::new("select.inverse", json!({}))]); // Playback: the mapped steps run, the layer is found by name, and the kept Photoshop step // stops the action with its name. @@ -450,11 +451,11 @@ fn load_maps_events_keeps_flags_and_plays() { // Loading the same set again replaces it; a different set with the same action names // gets unique names and its Play steps follow. s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); - assert_eq!(s.actions.list.actions().len(), 2); + assert_eq!(s.actions().list.actions().len(), 2); let r = s.execute("actions.load", json!({"data": b64(&bytes), "set": "Other"})).unwrap(); assert_eq!(r["actions"], json!(["Soften 2", "Finish 2"])); - assert_eq!(s.actions.list.actions()[2].steps[7].params, json!({"action": "Finish 2"})); - assert_eq!(s.actions.list.actions()[2].set.as_deref(), Some("Other")); + assert_eq!(s.actions().list.actions()[2].steps[7].params, json!({"action": "Finish 2"})); + assert_eq!(s.actions().list.actions()[2].set.as_deref(), Some("Other")); } /// A name the file shares with the list is renamed to the first free one, and the file's own names stay: "A" becomes @@ -465,14 +466,14 @@ fn load_renames_each_play_target_once() { let mut s = crate::session(); let mut mine = Action::new("A", vec![]); mine.set = Some("Mine".into()); - s.actions.list.push(mine).unwrap(); + s.actions_mut().list.push(mine).unwrap(); let a = Action::new("A", vec![ActionStep::new("actions.conditional", json!({"if": "always", "then": "A", "else": "A 2"}))]); let a2 = Action::new("A 2", vec![ActionStep::new("actions.play", json!({"action": "A"}))]); let keys = [("A".to_string(), "F4".to_string())]; let (bytes, _) = export("File", &[&a, &a2], &keys, false).unwrap(); let r = s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); assert_eq!(r["actions"], json!(["A 3", "A 2"])); - let get = |n: &str| s.actions.list.actions().iter().find(|a| a.name == n && a.set.as_deref() == Some("File")).unwrap(); + let get = |n: &str| s.actions().list.actions().iter().find(|a| a.name == n && a.set.as_deref() == Some("File")).unwrap(); assert_eq!(get("A 2").steps[0].params["action"], "A 3", "plays the file's A, which is now A 3"); let cond = &get("A 3").steps[0].params; assert_eq!((&cond["then"], &cond["else"]), (&json!("A 3"), &json!("A 2")), "{cond}"); @@ -483,12 +484,12 @@ fn load_renames_each_play_target_once() { for (name, steps) in [("A", vec![]), ("B", vec![ActionStep::new("actions.play", json!({"action": "A"}))])] { let mut a = Action::new(name, steps); a.set = Some("File".into()); - s.actions.list.push(a).unwrap(); + s.actions_mut().list.push(a).unwrap(); } let (bytes, _) = export("File", &[&Action::new("A", vec![])], &[], false).unwrap(); let r = s.execute("actions.load", json!({"data": b64(&bytes), "replace": false})).unwrap(); assert_eq!(r["actions"], json!(["A 2"])); - assert_eq!(s.actions.list.actions()[1].steps[0].params, json!({"action": "A"}), "B still plays the A it had"); + assert_eq!(s.actions().list.actions()[1].steps[0].params, json!({"action": "A"}), "B still plays the A it had"); } /// A name over the 1,024-character limit is clipped for the action and for the steps that call it, @@ -500,13 +501,13 @@ fn load_renames_play_targets_longer_than_the_name_limit() { let clipped = "x".repeat(1024); let mut mine = Action::new(clipped.clone(), vec![]); mine.set = Some("Mine".into()); - s.actions.list.push(mine).unwrap(); + s.actions_mut().list.push(mine).unwrap(); let a = Action::new(long.clone(), vec![]); let caller = Action::new("Caller", vec![ActionStep::new("actions.play", json!({"action": long}))]); let (bytes, _) = export("File", &[&a, &caller], &[], false).unwrap(); s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); let renamed = format!("{clipped} 2"); - let caller = s.actions.list.actions().iter().find(|a| a.name == "Caller").unwrap(); + let caller = s.actions().list.actions().iter().find(|a| a.name == "Caller").unwrap(); assert_eq!(caller.steps[0].params["action"], renamed.as_str()); } @@ -521,8 +522,8 @@ fn load_clips_an_overlong_set_override() { let long = "s".repeat(super::convert::MAX_NAME_CHARS * 4); s.execute("actions.load", json!({"data": b64(&bytes), "set": long})).unwrap(); let clipped = "s".repeat(super::convert::MAX_NAME_CHARS); - assert_eq!(s.actions.list.actions().len(), 3); - assert!(s.actions.list.actions().iter().all(|a| a.set.as_deref() == Some(clipped.as_str()))); + assert_eq!(s.actions().list.actions().len(), 3); + assert!(s.actions().list.actions().iter().all(|a| a.set.as_deref() == Some(clipped.as_str()))); } #[test] @@ -542,7 +543,7 @@ fn save_round_trips_through_photoshop_events() { let mut s = crate::session(); let bytes = atn::write(&sample()).unwrap(); s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap(); - let first = s.actions.list.actions().to_vec(); + let first = s.actions().list.actions().to_vec(); let r = s.execute("actions.save", json!({"set": "Test Set"})).unwrap(); assert_eq!(r["actions"], json!(["Soften", "Finish"])); assert_eq!(r["skipped"], json!([])); @@ -562,10 +563,10 @@ fn save_round_trips_through_photoshop_events() { // Loading what was saved gives the same actions. let mut t = crate::session(); t.execute("actions.load", json!({"data": b64(&saved)})).unwrap(); - assert_eq!(t.actions.list.actions(), first); + assert_eq!(t.actions().list.actions(), first); // A step with no Photoshop equivalent fails unless skipped. - s.actions.list.push(Action::new("Ours", vec![ActionStep::new("unsupported.forTest", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Ours", vec![ActionStep::new("unsupported.forTest", json!({}))])).unwrap(); let e = s.execute("actions.save", json!({"action": "Ours"})).unwrap_err().to_string(); assert!(e.contains("unsupported.forTest"), "{e}"); let r = s.execute("actions.save", json!({"action": "Ours", "skipUnsupported": true})).unwrap(); @@ -581,7 +582,7 @@ fn save_round_trips_through_photoshop_events() { fn a_selective_color_step_in_the_scalar_form_keeps_its_values() { let back = |params: Value| -> Value { let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new("image.adjustments.selectiveColor", params)])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new("image.adjustments.selectiveColor", params)])).unwrap(); let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); assert_eq!(r["skipped"], json!([])); let imported = import(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); @@ -609,7 +610,7 @@ fn a_selective_color_step_in_the_scalar_form_keeps_its_values() { // writing it would export an adjustment that is not the one recorded. `null` is absent, as // the command reads it. let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new("image.adjustments.selectiveColor", json!({"colors": "reds", "cyan": "35"}))])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new("image.adjustments.selectiveColor", json!({"colors": "reds", "cyan": "35"}))])).unwrap(); let e = s.execute("actions.save", json!({"action": "A"})).unwrap_err().to_string(); assert!(e.contains("image.adjustments.selectiveColor"), "{e}"); @@ -637,15 +638,15 @@ fn a_setting_the_event_cannot_hold_is_refused() { ("layer.setAdjustment", json!({"kind": "exposure", "document": 2, "exposure": -0.75})), ] { let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new(id, params)])).unwrap(); - let before = s.actions.list.actions()[0].steps.clone(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new(id, params)])).unwrap(); + let before = s.actions().list.actions()[0].steps.clone(); let e = s.execute("actions.save", json!({"action": "A"})).unwrap_err().to_string(); assert!(e.contains(id), "{id}: {e}"); // A refused save leaves the action as it was: the step is still there to be played. - assert_eq!(s.actions.list.actions()[0].steps, before, "{id}"); + assert_eq!(s.actions().list.actions()[0].steps, before, "{id}"); let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": true})).unwrap(); assert_eq!(r["skipped"], json!([{"action": "A", "step": 0, "id": id}]), "{id}"); - assert_eq!(s.actions.list.actions()[0].steps, before, "{id}: skipping a step does not drop it"); + assert_eq!(s.actions().list.actions()[0].steps, before, "{id}: skipping a step does not drop it"); } } @@ -671,7 +672,7 @@ fn settings_at_the_value_the_event_plays_still_export() { ("image.adjustments.equalize", json!({})), ] { let mut s = crate::session(); - s.actions.list.push(Action::new("A", vec![ActionStep::new(id, params.clone())])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![ActionStep::new(id, params.clone())])).unwrap(); let r = s.execute("actions.save", json!({"action": "A"})).unwrap_or_else(|e| panic!("{id} {params}: {e}")); assert_eq!(r["skipped"], json!([]), "{id} {params}"); } @@ -1665,11 +1666,11 @@ fn step_commands_and_bad_params_fail_gracefully() { ] { assert!(s.execute("actions.load", p.clone()).is_err(), "{p}"); } - assert!(s.actions.list.actions().is_empty()); + assert!(s.actions().list.actions().is_empty()); for p in [json!({}), json!({"set": "Nope"}), json!({"action": 3}), json!({"path": 7}), json!({"skipUnsupported": "no"}), json!({"set": ""})] { assert!(s.execute("actions.save", p.clone()).is_err(), "{p}"); } - s.actions.list.push(Action::new("One", vec![ActionStep::new("select.all", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("One", vec![ActionStep::new("select.all", json!({}))])).unwrap(); assert!(s.execute("actions.save", json!({"path": ""})).is_err()); assert!(s.execute("actions.save", json!({})).unwrap()["data"].is_string()); @@ -1680,7 +1681,7 @@ fn step_commands_and_bad_params_fail_gracefully() { assert!(s.execute(PHOTOSHOP_STEP, p.clone()).is_err(), "{p}"); } // A Photoshop step with a damaged descriptor is left out of a save rather than crashing it. - s.actions + s.actions_mut() .list .push(Action::new("Broken", vec![ActionStep::new(PHOTOSHOP_STEP, json!({"event": "GsnB", "name": "Blur", "descriptor": b64(b"\x00\x00\x00")}))])) .unwrap(); @@ -1692,7 +1693,7 @@ fn step_commands_and_bad_params_fail_gracefully() { fn save_writes_the_file_and_the_set_of_the_selected_action() { let mut s = crate::session(); s.execute("actions.load", json!({"data": b64(&atn::write(&sample()).unwrap())})).unwrap(); - s.actions.list.push(Action::new("Loose", vec![ActionStep::new("select.all", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Loose", vec![ActionStep::new("select.all", json!({}))])).unwrap(); let dir = std::env::temp_dir().join(format!("pc-atn-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("Saved.atn"); @@ -1716,14 +1717,14 @@ fn save_writes_the_file_and_the_set_of_the_selected_action() { fn save_over_an_existing_file_never_rewrites_it_in_place() { use std::io::Read; let mut s = crate::session(); - s.actions.list.push(Action::new("Owned", vec![ActionStep::new("select.all", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Owned", vec![ActionStep::new("select.all", json!({}))])).unwrap(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("Owned.atn"); let p = path.to_string_lossy().to_string(); s.execute("actions.save", json!({"path": p})).unwrap(); let before = std::fs::read(&path).unwrap(); let mut old = std::fs::File::open(&path).unwrap(); - s.actions.list.push(Action::new("Second", vec![ActionStep::new("select.all", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Second", vec![ActionStep::new("select.all", json!({}))])).unwrap(); s.execute("actions.save", json!({"path": p})).unwrap(); let mut seen = Vec::new(); old.read_to_end(&mut seen).unwrap(); @@ -2061,7 +2062,7 @@ fn select_document_by_offset_imports_plays_and_saves_back() { s.execute("document.move", json!({"document": 1, "to": 0})).unwrap(); let r = s.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(r["unsupported"], json!([]), "{r}"); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps[0], ActionStep::new("document.activate", json!({"offset": -1}))); assert_eq!(steps[3], ActionStep::new("document.activate", json!({"offset": 1}))); @@ -2074,7 +2075,7 @@ fn select_document_by_offset_imports_plays_and_saves_back() { assert_eq!(pixel(&mut s), [1.0, 0.0, 0.0, 1.0]); assert_eq!(s.documents()[1].doc.layers.len(), 1, "the source is only copied from"); - let first = s.actions.list.actions().to_vec(); + let first = s.actions().list.actions().to_vec(); let r = s.execute("actions.save", json!({"set": "Template"})).unwrap(); assert_eq!(r["skipped"], json!([])); let saved = photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap(); @@ -2091,7 +2092,7 @@ fn select_document_by_offset_imports_plays_and_saves_back() { assert!(file.actions[0].items[0].descriptor.as_ref().unwrap().get("DocI").is_none()); let mut t = crate::session(); t.execute("actions.load", json!({"data": b64(&saved)})).unwrap(); - assert_eq!(t.actions.list.actions(), first); + assert_eq!(t.actions().list.actions(), first); // An absolute tab index has no Photoshop equivalent: it stays out of a strict save. assert!(export_item("document.activate", &json!({"document": 0}), "S").is_none()); assert!(export_item("document.activate", &json!({"document": 0, "offset": 1}), "S").is_none()); @@ -2320,10 +2321,10 @@ fn events_photoshop_only_runs_by_name_export_by_name_and_old_codes_still_import( let mut s = crate::session(); let r = s.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(r["unsupported"], json!([]), "{r}"); - let ids = |i: usize| s.actions.list.actions()[i].steps.iter().map(|st| st.command.clone()).collect::>(); + let ids = |i: usize| s.actions().list.actions()[i].steps.iter().map(|st| st.command.clone()).collect::>(); assert_eq!(ids(0), ["filter.blur.boxBlur", "filter.blur.surfaceBlur", "layer.flattenImage", "layer.flattenImage"]); assert_eq!(ids(1), ["filter.blur.boxBlur", "filter.blur.surfaceBlur", "layer.flattenImage"]); - assert_eq!(s.actions.list.actions()[1].steps[1].params, json!({"radius": 5, "threshold": 15})); + assert_eq!(s.actions().list.actions()[1].steps[1].params, json!({"radius": 5, "threshold": 15})); // Saving them writes the ids Photoshop runs, never the old codes. let saved = s.execute("actions.save", json!({"set": "S"})).unwrap(); let file = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); @@ -2376,7 +2377,7 @@ fn photo_filter_saves_under_the_name_photoshop_runs() { let mut t = crate::session(); let r = t.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(r["unsupported"], json!([]), "{r}"); - for a in t.actions.list.actions() { + for a in t.actions().list.actions() { assert_eq!(a.steps.len(), 1, "{}", a.name); assert_eq!(a.steps[0].command, "image.adjustments.photoFilter", "{}", a.name); let mut p = a.steps[0].params.clone(); @@ -2420,7 +2421,7 @@ fn black_white_adjustment_layer_saves_as_photoshops_class_and_old_class_still_im let id = "layer.newAdjustmentLayer.blackWhite"; let params = json!({"reds": 17, "yellows": 83, "greens": -12, "cyans": 107, "blues": 51, "magentas": 133, "tint": true, "tintColor": "#c08040"}); let mut s = crate::session(); - s.actions.list.push(Action::new("BW", vec![ActionStep::new(id, params.clone())])).unwrap(); + s.actions_mut().list.push(Action::new("BW", vec![ActionStep::new(id, params.clone())])).unwrap(); let r = s.execute("actions.save", json!({"action": "BW"})).unwrap(); assert_eq!(r["skipped"], json!([])); let saved = photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap(); @@ -2431,7 +2432,7 @@ fn black_white_adjustment_layer_saves_as_photoshops_class_and_old_class_still_im let mut t = crate::session(); let r = t.execute("actions.load", json!({"data": b64(&saved)})).unwrap(); assert_eq!(r["unsupported"], json!([]), "{r}"); - assert_eq!(t.actions.list.actions()[0].steps, vec![ActionStep::new(id, params)]); + assert_eq!(t.actions().list.actions()[0].steps, vec![ActionStep::new(id, params)]); // Photoshop's minimal Make (no settings) and an old PhotoCraft Make with a setting both load, // the setting kept; near misses stay Photoshop steps. @@ -2443,9 +2444,9 @@ fn black_white_adjustment_layer_saves_as_photoshops_class_and_old_class_still_im let data = set_of("S", vec![("A", ["BanW", "BlnW", "BANW", "BlnWx"].into_iter().map(make).collect())]); let mut t = crate::session(); let r = t.execute("actions.load", json!({"data": data})).unwrap(); - let steps: Vec<&str> = t.actions.list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); + let steps: Vec<&str> = t.actions().list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); assert_eq!(steps, [id, id, PHOTOSHOP_STEP, PHOTOSHOP_STEP], "{r}"); - assert_eq!(t.actions.list.actions()[0].steps[1].params["reds"], 17, "{r}"); + assert_eq!(t.actions().list.actions()[0].steps[1].params["reds"], 17, "{r}"); } /// #11517: a native Black & White coefficient may be fractional, but an ATN long cannot. @@ -2551,7 +2552,7 @@ fn smart_blur_quality_uses_photoshop_codes() { let data = set_of("Blurs", vec![("Smart", items)]); let mut s = crate::session(); s.execute("actions.load", json!({"data": data})).unwrap(); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; for ((q, _, quality, mode), ActionStep { command: id, params: p }) in cases.iter().zip(steps) { assert_eq!(id, "filter.blur.smartBlur", "{q}"); assert_eq!(p, &json!({"radius": 6, "threshold": 60, "quality": quality, "mode": mode}), "{q}"); @@ -2955,7 +2956,7 @@ fn numeric_layer_references_refuse_silent_fallback_to_current_selection() { }; // Named layer reference exports successfully with Name reference to "A" - s.actions.list.push(Action::new("DeleteNamed", vec![ActionStep::new("layer.delete", json!({"layer": "A"}))])).unwrap(); + s.actions_mut().list.push(Action::new("DeleteNamed", vec![ActionStep::new("layer.delete", json!({"layer": "A"}))])).unwrap(); let saved_named = s.execute("actions.save", json!({"action": "DeleteNamed"})).unwrap(); assert_eq!(saved_named["steps"], 1); let named_desc = parse_first_desc(&saved_named); @@ -2965,7 +2966,7 @@ fn numeric_layer_references_refuse_silent_fallback_to_current_selection() { } // Omitted layer reference (target selection) exports successfully with Trgt enumerated reference - s.actions.list.push(Action::new("DeleteTarget", vec![ActionStep::new("layer.delete", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("DeleteTarget", vec![ActionStep::new("layer.delete", json!({}))])).unwrap(); let saved_target = s.execute("actions.save", json!({"action": "DeleteTarget"})).unwrap(); assert_eq!(saved_target["steps"], 1); let target_desc = parse_first_desc(&saved_target); @@ -2975,7 +2976,7 @@ fn numeric_layer_references_refuse_silent_fallback_to_current_selection() { } // Explicit null layer reference also exports successfully as target selection with Trgt enumerated reference - s.actions.list.push(Action::new("DeleteNull", vec![ActionStep::new("layer.delete", json!({"layer": null}))])).unwrap(); + s.actions_mut().list.push(Action::new("DeleteNull", vec![ActionStep::new("layer.delete", json!({"layer": null}))])).unwrap(); let saved_null = s.execute("actions.save", json!({"action": "DeleteNull"})).unwrap(); assert_eq!(saved_null["steps"], 1); let null_desc = parse_first_desc(&saved_null); @@ -2986,12 +2987,12 @@ fn numeric_layer_references_refuse_silent_fallback_to_current_selection() { // An id beyond the u32 the `Idnt` reference holds cannot be carried and must never silently // fall back to the current target; an in-range id exports as the `Idnt` itself (#7246). - s.actions.list.push(Action::new("DeleteNumeric", vec![ActionStep::new("layer.delete", json!({"layer": u32::MAX as u64 + 1}))])).unwrap(); - let before_actions = s.actions.list.actions().to_vec(); + s.actions_mut().list.push(Action::new("DeleteNumeric", vec![ActionStep::new("layer.delete", json!({"layer": u32::MAX as u64 + 1}))])).unwrap(); + let before_actions = s.actions().list.actions().to_vec(); let before_rev = s.active().unwrap().revision; let err_delete = s.execute("actions.save", json!({"action": "DeleteNumeric"})); assert!(err_delete.is_err(), "strict export must reject numeric layer ID for layer.delete rather than falling back to current target"); - assert_eq!(s.actions.list.actions(), before_actions, "session actions must remain unchanged when save fails"); + assert_eq!(s.actions().list.actions(), before_actions, "session actions must remain unchanged when save fails"); assert_eq!(s.active().unwrap().revision, before_rev, "document revision must remain unchanged when save fails"); let err_msg = err_delete.unwrap_err().to_string(); assert!(err_msg.contains("(`layer.delete` with numeric layer 4294967296)"), "error message should name the numeric layer: {err_msg}"); @@ -3013,11 +3014,11 @@ fn numeric_layer_references_refuse_silent_fallback_to_current_selection() { ("BringForwardNumeric", "layer.arrange.bringForward", json!({"layer": u32::MAX as u64 + 1})), ("SendBackwardNumeric", "layer.arrange.sendBackward", json!({"layer": u32::MAX as u64 + 1})), ] { - s.actions.list.push(Action::new(name, vec![ActionStep::new(id, params)])).unwrap(); - let before_actions = s.actions.list.actions().to_vec(); + s.actions_mut().list.push(Action::new(name, vec![ActionStep::new(id, params)])).unwrap(); + let before_actions = s.actions().list.actions().to_vec(); let before_rev = s.active().unwrap().revision; assert!(s.execute("actions.save", json!({"action": name})).is_err()); - assert_eq!(s.actions.list.actions(), before_actions, "session actions must remain unchanged when save fails"); + assert_eq!(s.actions().list.actions(), before_actions, "session actions must remain unchanged when save fails"); assert_eq!(s.active().unwrap().revision, before_rev, "document revision must remain unchanged when save fails"); } @@ -3071,7 +3072,7 @@ fn arbitrary_rotation_keeps_interpolation_through_atn() { fn emboss_saves_as_photoshops_event_and_loads_back() { let mut s = crate::session(); let params = json!({"angle": 130, "height": 1, "amount": 70}); - s.actions.list.push(Action::new("Pore", vec![ActionStep::new("filter.stylize.emboss", params.clone())])).unwrap(); + s.actions_mut().list.push(Action::new("Pore", vec![ActionStep::new("filter.stylize.emboss", params.clone())])).unwrap(); let r = s.execute("actions.save", json!({"action": "Pore"})).unwrap(); assert_eq!(r["skipped"], json!([])); let saved = photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap(); @@ -3084,7 +3085,7 @@ fn emboss_saves_as_photoshops_event_and_loads_back() { } let mut t = crate::session(); t.execute("actions.load", json!({"data": b64(&saved)})).unwrap(); - assert_eq!(t.actions.list.actions()[0].steps, vec![ActionStep::new("filter.stylize.emboss", params)]); + assert_eq!(t.actions().list.actions()[0].steps, vec![ActionStep::new("filter.stylize.emboss", params)]); } /// A filter recorded against a layer mask must not export as a plain filter that edits the @@ -3406,7 +3407,7 @@ fn vibrance_adjustment_layer_steps_save_with_the_string_class() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps[1], ActionStep::new("layer.newAdjustmentLayer.vibrance", json!({"vibrance": 10, "saturation": 5})), "{steps:?}"); assert_eq!((&steps[0], &steps[1]), (&steps[2], &steps[3]), "the old `Vbrn` class imports the same"); let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap(); @@ -3423,7 +3424,7 @@ fn vibrance_adjustment_layer_steps_save_with_the_string_class() { } let mut reloaded = crate::session(); reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap(); - assert_eq!(reloaded.actions.list.actions()[0].steps, s.actions.list.actions()[0].steps); + assert_eq!(reloaded.actions().list.actions()[0].steps, s.actions().list.actions()[0].steps); } /// Our Vibrance has no `temperature` or `tint`: a recorded Vibrance Set or Make with either one @@ -3437,7 +3438,7 @@ fn vibrance_steps_with_temperature_or_tint_save_back_unchanged() { let data = set_of("Vibrance", vec![("A", vec![item("set", "Set", Some(set.clone())), item("Mk ", "Make", Some(make.clone()))])]); let mut s = crate::session(); s.execute("actions.load", json!({"data": data})).unwrap(); - assert!(s.actions.list.actions()[0].steps.iter().all(|st| st.command == "actions.photoshopStep"), "{:?}", s.actions.list.actions()[0].steps); + assert!(s.actions().list.actions()[0].steps.iter().all(|st| st.command == "actions.photoshopStep"), "{:?}", s.actions().list.actions()[0].steps); let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap(); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); let file = atn::parse(&bytes).unwrap(); @@ -3592,12 +3593,12 @@ fn image_size_explicit_sides_keep_precedence_over_percent() { assert_eq!((size.width, size.height), expected, "native {params} at {depth} bits"); let mut recorded = crate::session(); - recorded.actions.list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])).unwrap(); - let before = recorded.actions.list.clone(); + recorded.actions_mut().list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])).unwrap(); + let before = recorded.actions().list.clone(); let saved = recorded.execute("actions.save", json!({"action": "Resize"})).unwrap(); assert_eq!(saved["skipped"], json!([])); assert_eq!(saved["steps"], 1); - assert_eq!(recorded.actions.list, before); + assert_eq!(recorded.actions().list, before); let mut replay = crate::session(); let loaded = replay.execute("actions.load", json!({"data": saved["data"]})).unwrap(); @@ -3691,7 +3692,7 @@ fn select_rect_modes_export_without_becoming_replace() { s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); // Default or "replace" mode succeeds - s.actions + s.actions_mut() .list .push(Action::new("ReplaceAct", vec![ActionStep::new("select.rect", json!({"x": 4, "y": 4, "width": 2, "height": 2, "mode": "replace"}))])) .unwrap(); @@ -3699,19 +3700,19 @@ fn select_rect_modes_export_without_becoming_replace() { assert_eq!(saved["steps"], 1); for (mode, event) in [("add", "AddT"), ("subtract", "SbtF"), ("intersect", "IntW")] { - s.actions.list.push(Action::new(mode, vec![ActionStep::new("select.rect", json!({"x":4,"y":4,"width":2,"height":2,"mode":mode}))])).unwrap(); - let before = s.actions.list.actions().to_vec(); + s.actions_mut().list.push(Action::new(mode, vec![ActionStep::new("select.rect", json!({"x":4,"y":4,"width":2,"height":2,"mode":mode}))])).unwrap(); + let before = s.actions().list.actions().to_vec(); let saved = s.execute("actions.save", json!({"action":mode})).unwrap(); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].event.id(), event); assert_eq!(import(&bytes).unwrap().actions[0].steps[0].params["mode"], mode); - assert_eq!(s.actions.list.actions(), before); + assert_eq!(s.actions().list.actions(), before); } - s.actions.list.push(Action::new("Unsupported", vec![ActionStep::new("select.rect", json!({"x":4,"y":4,"width":2,"height":2,"mode":"xor"}))])).unwrap(); - let before = s.actions.list.actions().to_vec(); + s.actions_mut().list.push(Action::new("Unsupported", vec![ActionStep::new("select.rect", json!({"x":4,"y":4,"width":2,"height":2,"mode":"xor"}))])).unwrap(); + let before = s.actions().list.actions().to_vec(); assert!(s.execute("actions.save", json!({"action":"Unsupported"})).is_err()); - assert_eq!(s.actions.list.actions(), before, "rejected export must leave actions unchanged"); + assert_eq!(s.actions().list.actions(), before, "rejected export must leave actions unchanged"); // With skipUnsupported: true, unrepresentable modes are reported in skipped let skipped = s.execute("actions.save", json!({"action": "Unsupported", "skipUnsupported": true})).unwrap(); @@ -3725,7 +3726,7 @@ fn radial_blur_off_center_strict_export_refuses_silent_recentering() { s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); // Default center (omitted) exports successfully - s.actions + s.actions_mut() .list .push(Action::new("DefaultCenter", vec![ActionStep::new("filter.blur.radialBlur", json!({"amount": 50, "method": "spin", "quality": "good"}))])) .unwrap(); @@ -3733,7 +3734,7 @@ fn radial_blur_off_center_strict_export_refuses_silent_recentering() { assert_eq!(saved["steps"], 1); // Explicit (0.5, 0.5) center also exports successfully - s.actions + s.actions_mut() .list .push(Action::new( "ExplicitDefaultCenter", @@ -3744,17 +3745,17 @@ fn radial_blur_off_center_strict_export_refuses_silent_recentering() { assert_eq!(saved_exp["steps"], 1); // Off-center radial blur cannot be silently recentered in strict export - s.actions + s.actions_mut() .list .push(Action::new( "OffCenter", vec![ActionStep::new("filter.blur.radialBlur", json!({"amount": 50, "method": "spin", "quality": "good", "centerX": 0.1, "centerY": 0.2}))], )) .unwrap(); - let before_actions = s.actions.list.actions().to_vec(); + let before_actions = s.actions().list.actions().to_vec(); let err = s.execute("actions.save", json!({"action": "OffCenter"})); assert!(err.is_err(), "strict export must reject off-center radial blur rather than silently recentering it"); - assert_eq!(s.actions.list.actions(), before_actions, "actions list must remain unchanged after rejected save"); + assert_eq!(s.actions().list.actions(), before_actions, "actions list must remain unchanged after rejected save"); // With skipUnsupported: true, off-center radial blur is skipped let skipped = s.execute("actions.save", json!({"action": "OffCenter", "skipUnsupported": true})).unwrap(); @@ -3762,24 +3763,24 @@ fn radial_blur_off_center_strict_export_refuses_silent_recentering() { assert_eq!(skipped["skipped"][0]["id"], "filter.blur.radialBlur"); // Radial blur targeting a mask must not export as a plain filter that edits pixels - s.actions + s.actions_mut() .list .push(Action::new( "MaskTarget", vec![ActionStep::new("filter.blur.radialBlur", json!({"amount": 50, "method": "spin", "quality": "good", "target": "mask"}))], )) .unwrap(); - let before_actions = s.actions.list.actions().to_vec(); + let before_actions = s.actions().list.actions().to_vec(); let err_mask = s.execute("actions.save", json!({"action": "MaskTarget"})); assert!(err_mask.is_err(), "strict export must reject radial blur with non-pixel target"); - assert_eq!(s.actions.list.actions(), before_actions, "actions list must remain unchanged after rejected save"); + assert_eq!(s.actions().list.actions(), before_actions, "actions list must remain unchanged after rejected save"); let skipped_mask = s.execute("actions.save", json!({"action": "MaskTarget", "skipUnsupported": true})).unwrap(); assert_eq!(skipped_mask["steps"], 0); assert_eq!(skipped_mask["skipped"][0]["id"], "filter.blur.radialBlur"); // Explicit pixels target exports successfully - s.actions + s.actions_mut() .list .push(Action::new( "PixelsTarget", @@ -4020,7 +4021,7 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, "filter.cameraRaw"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, "filter.cameraRaw"); let saved_step = |r: &Value| { let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); saved.actions[0].items.first().map(|i| (i.event.clone(), i.dictionary.clone(), i.descriptor.clone())) @@ -4042,16 +4043,16 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() { assert_eq!(played["ran"], 1, "{played}"); assert!(played.get("failed").is_none(), "{played}"); // Edited, it no longer matches what was recorded. - let recorded = s.actions.list.actions()[0].steps[0].clone(); + let recorded = s.actions().list.actions()[0].steps[0].clone(); let mut edited = recorded.clone(); edited.params["exposure"] = json!(1.5); - s.actions.list.replace_step(0, 0, edited).unwrap(); + s.actions_mut().list.replace_step(0, 0, edited).unwrap(); let e = s.execute("actions.save", json!({"action": "A"})).unwrap_err().to_string(); assert!(e.contains("filter.cameraRaw"), "{e}"); // Recorded by PhotoCraft: no descriptor to write back. let mut plain = recorded; plain.params.as_object_mut().unwrap().remove("__atnDescriptor"); - s.actions.list.replace_step(0, 0, plain).unwrap(); + s.actions_mut().list.replace_step(0, 0, plain).unwrap(); let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": true})).unwrap(); assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "{r}"); } @@ -4074,7 +4075,7 @@ fn camera_raw_filter_steps_with_unknown_keys_stay_photoshop_steps() { let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); let unsupported: Vec = loaded["unsupported"].as_array().unwrap().iter().map(|u| u["step"].as_u64().unwrap()).collect(); assert_eq!(unsupported, [0, 1, 2], "{loaded}"); - let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); + let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, "filter.cameraRaw"]); // Kept, it still saves back as recorded. let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); @@ -4285,7 +4286,7 @@ fn gallery_effect_steps_load_clamp_play_and_save_back() { for (code, effect) in [("AccE", "accentedEdges"), ("Ct ", "cutout"), ("Plst", "plaster")] { let (id, p) = gallery_params(gallery_step("GEfc", code, desc("null"))); assert_eq!(id, format!("filter.gallery.{effect}")); - s.actions.list.push(Action::new(code, vec![ActionStep::new(id, p)])).unwrap(); + s.actions_mut().list.push(Action::new(code, vec![ActionStep::new(id, p)])).unwrap(); let played = s.execute("actions.play", json!({"action": code})).unwrap(); assert_eq!(played["ran"], 1, "{code}: {played}"); } @@ -4419,7 +4420,7 @@ fn gallery_effect_steps_save_back_as_the_event_they_were_recorded_as() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); + let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); assert_eq!(ids, ["filter.gallery.accentedEdges", "filter.gallery.cutout", "filter.gallery.accentedEdges"]); s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); @@ -4495,7 +4496,7 @@ fn channel_and_color_steps_load_and_save_back() { let r = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); assert_eq!(r["unsupported"], json!([])); assert_eq!( - s.actions.list.actions()[0].steps, + s.actions().list.actions()[0].steps, vec![ ActionStep::new("channel.split", json!({})), ActionStep::new("channel.mergeSpot", json!({})), @@ -4516,7 +4517,7 @@ fn channel_and_color_steps_load_and_save_back() { // Match Color with no reference plays on the image itself. s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); s.execute("filter.render.clouds", json!({})).unwrap(); - s.actions.list.push(Action::new("Match", vec![s.actions.list.actions()[0].steps[3].clone()])).unwrap(); + s.actions_mut().list.push(Action::new("Match", vec![s.actions().list.actions()[0].steps[3].clone()])).unwrap(); let played = s.execute("actions.play", json!({"action": "Match"})).unwrap(); assert_eq!(played["ran"], 1, "{played}"); } @@ -4694,12 +4695,12 @@ fn trap_step_without_a_width_saves_back_the_same() { }; let mut s = crate::session(); s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); - let loaded = s.actions.list.actions().to_vec(); + let loaded = s.actions().list.actions().to_vec(); assert_eq!(loaded[0].steps, vec![ActionStep::new("image.trap", json!({"width": 1}))]); let saved = s.execute("actions.save", json!({"set": "S"})).unwrap(); let mut t = crate::session(); t.execute("actions.load", json!({"data": saved["data"].as_str().unwrap()})).unwrap(); - assert_eq!(t.actions.list.actions(), loaded); + assert_eq!(t.actions().list.actions(), loaded); } /// The Match Color dialog records Source "None" as `"source": -1`, which the command plays @@ -4740,7 +4741,7 @@ fn select_color_components_import_play_and_round_trip() { assert_eq!(s.execute("channel.list", json!({})).unwrap(), expected, "{mode}/{depth}/{channel}"); let saved = s.execute("actions.save", json!({"set": "Components"})).unwrap(); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); - assert_eq!(import(&bytes).unwrap().actions[0].steps, s.actions.list.actions()[0].steps); + assert_eq!(import(&bytes).unwrap().actions[0].steps, s.actions().list.actions()[0].steps); } } } @@ -4768,7 +4769,7 @@ fn select_color_components_preserve_unsupported_selection_shapes() { let data = set_of("Unknown", vec![("Pick", vec![item("select", "Select", Some(selection.clone()))])]); let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1); - assert_eq!(s.actions.list.actions()[0].steps[0].command, PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, PHOTOSHOP_STEP); let target = s.execute("channel.list", json!({})).unwrap(); let played = s.execute("actions.play", json!({"action": "Pick"})).unwrap(); assert_eq!(played["failed"]["id"], PHOTOSHOP_STEP); @@ -4826,16 +4827,16 @@ fn select_channel_export_rejects_nested_color_selections() { s.execute("file.new", json!({"width":2,"height":1,"mode":"cmyk"})).unwrap(); s.execute("channel.target", params.clone()).unwrap(); assert_eq!(s.active().unwrap().channel_view.selected_colors, colors); - s.actions.list.push(Action::new("Nested", vec![ActionStep::new("channel.target", params.clone())])).unwrap(); + s.actions_mut().list.push(Action::new("Nested", vec![ActionStep::new("channel.target", params.clone())])).unwrap(); assert!(s.execute("actions.save", json!({"action":"Nested"})).is_err(), "{params} must not become a single Cyan selection"); let skipped = s.execute("actions.save", json!({"action":"Nested","skipUnsupported":true})).unwrap(); assert_eq!(skipped["skipped"], json!([{"action":"Nested","step":0,"id":"channel.target"}])); let bytes = photocraft_paint::tile::b64_decode(skipped["data"].as_str().unwrap()).unwrap(); assert!(atn::parse(&bytes).unwrap().actions[0].items.is_empty()); - assert_eq!(s.actions.list.actions()[0].steps[0].params, params); + assert_eq!(s.actions().list.actions()[0].steps[0].params, params); } let mut s = crate::session(); - s.actions.list.push(Action::new("Cyan", vec![ActionStep::new("channel.target", json!({"channel":{"color":"CYAN"},"extend":false}))])).unwrap(); + s.actions_mut().list.push(Action::new("Cyan", vec![ActionStep::new("channel.target", json!({"channel":{"color":"CYAN"},"extend":false}))])).unwrap(); let saved = s.execute("actions.save", json!({"action":"Cyan"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); @@ -4851,26 +4852,26 @@ fn select_channel_export_rejects_mode_specific_gray_objects() { let mut s = crate::session(); s.execute("file.new", json!({"width":2,"height":1,"mode":mode})).unwrap(); assert_eq!(s.execute("channel.target", params.clone()).is_ok(), mode == "gray"); - s.actions.list.push(Action::new("Gray object", vec![ActionStep::new("channel.target", params.clone())])).unwrap(); + s.actions_mut().list.push(Action::new("Gray object", vec![ActionStep::new("channel.target", params.clone())])).unwrap(); assert!(s.execute("actions.save", json!({"action":"Gray object"})).is_err(), "{mode}/{color} must not become composite"); let skipped = s.execute("actions.save", json!({"action":"Gray object","skipUnsupported":true})).unwrap(); assert_eq!(skipped["skipped"], json!([{"action":"Gray object","step":0,"id":"channel.target"}])); let bytes = photocraft_paint::tile::b64_decode(skipped["data"].as_str().unwrap()).unwrap(); assert!(atn::parse(&bytes).unwrap().actions[0].items.is_empty()); - assert_eq!(s.actions.list.actions()[0].steps[0].params, params); + assert_eq!(s.actions().list.actions()[0].steps[0].params, params); } } let mut s = crate::session(); - s.actions.list.push(Action::new("Portable", vec![ActionStep::new("channel.target", json!({"channel":"composite"}))])).unwrap(); + s.actions_mut().list.push(Action::new("Portable", vec![ActionStep::new("channel.target", json!({"channel":"composite"}))])).unwrap(); let saved = s.execute("actions.save", json!({"action":"Portable"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); - assert_eq!(import(&bytes).unwrap().actions[0].steps, s.actions.list.actions()[0].steps); + assert_eq!(import(&bytes).unwrap().actions[0].steps, s.actions().list.actions()[0].steps); let gray = set_of("Gray", vec![("Pick", vec![item("select", "Select", Some(desc("null").with("null", channel_ord("Gry"))))])]); let mut rgb = crate::session(); rgb.execute("file.new", json!({"width":2,"height":1,"mode":"rgb"})).unwrap(); rgb.execute("actions.load", json!({"data":gray})).unwrap(); - assert_eq!(rgb.actions.list.actions()[0].steps[0], ActionStep::new("channel.target", json!({"channel":"composite"}))); + assert_eq!(rgb.actions().list.actions()[0].steps[0], ActionStep::new("channel.target", json!({"channel":"composite"}))); assert!(rgb.execute("actions.play", json!({"action":"Pick"})).unwrap().get("failed").is_none()); } @@ -5268,7 +5269,7 @@ fn newer_feature_steps_load_with_photoshops_defaults() { ActionStep::new("filter.sharpen.smartSharpen", mapped(newer("smartSharpen", gaussian_sharpen(&[]))).1), ], ); - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); let played = s.execute("actions.play", json!({"action": "Paint"})).unwrap(); assert_eq!(played["ran"], 2, "{played}"); } @@ -5552,7 +5553,7 @@ fn newer_feature_selection_steps_play() { }) .unwrap(); let play = |s: &mut Session, name: &str| { - s.actions.list.push(Action::new(name, vec![ActionStep::from(mapped(newer(name, desc("null"))))])).unwrap(); + s.actions_mut().list.push(Action::new(name, vec![ActionStep::from(mapped(newer(name, desc("null"))))])).unwrap(); let played = s.execute("actions.play", json!({"action": name})).unwrap(); assert!(played.get("failed").is_none(), "{name}: {played}"); assert_eq!(played["ran"], 1, "{name}: {played}"); @@ -5708,7 +5709,7 @@ fn video_other_and_matting_steps_load_play_and_save_back() { } assert_eq!((steps[0].0.as_str(), &p), (id, ¶ms), "{code}"); assert_eq!(export_item(id, &steps[0].1, "S").unwrap().descriptor.unwrap().items, d.items, "{code}"); - s.actions.list.push(Action::new(code, vec![ActionStep::new(id, steps[0].1.clone())])).unwrap(); + s.actions_mut().list.push(Action::new(code, vec![ActionStep::new(id, steps[0].1.clone())])).unwrap(); let played = s.execute("actions.play", json!({"action": code})).unwrap(); assert_eq!(played["ran"], 1, "{code}: {played}"); } @@ -6099,7 +6100,7 @@ fn distort_filter_steps_load_clamp_play_and_save_back() { assert_eq!((got.as_str(), &p), (id, ¶ms), "{code}"); // Every key, in the order Photoshop records them. assert_eq!(export_item(id, &p, "S").unwrap().descriptor.unwrap().items, d.items, "{code}"); - s.actions.list.push(Action::new(code, vec![ActionStep::new(id, p)])).unwrap(); + s.actions_mut().list.push(Action::new(code, vec![ActionStep::new(id, p)])).unwrap(); let played = s.execute("actions.play", json!({"action": code})).unwrap(); assert_eq!(played["ran"], 1, "{code}: {played}"); } @@ -6293,7 +6294,7 @@ fn wave_values_the_command_rejects_are_kept_or_refused() { let (id, p) = one_step(distort("Wave", d)); assert!(export_item(&id, &p, "S").is_some(), "{p} refused"); let name = format!("W{k}"); - s.actions.list.push(Action::new(&name, vec![ActionStep::new(id, p.clone())])).unwrap(); + s.actions_mut().list.push(Action::new(&name, vec![ActionStep::new(id, p.clone())])).unwrap(); let played = s.execute("actions.play", json!({"action": name})).unwrap(); assert_eq!(played["ran"], 1, "{p}: {played}"); } @@ -6453,7 +6454,7 @@ fn pattern_fill_missing_everywhere_names_the_pattern() { #[test] fn save_finds_a_set_by_its_exact_name_with_spaces() { let mut s = crate::session(); - s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }).unwrap(); + s.actions_mut().list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }).unwrap(); s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); let saved = s.execute("actions.save", json!({"set": " Web "})).unwrap(); @@ -6561,7 +6562,7 @@ fn load_rejects_bad_encodings() { for bad in [json!(3), json!(""), json!("nope"), json!("replacement"), json!(["gbk"])] { assert!(s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": bad})).is_err(), "{bad}"); } - assert!(s.actions.list.actions().is_empty(), "nothing is loaded when the encoding is bad"); + assert!(s.actions().list.actions().is_empty(), "nothing is loaded when the encoding is bad"); } /// Edit › Check Spelling in its recorded form: `spellCheck`, `null` = the `spellCheck` property of @@ -6790,7 +6791,7 @@ fn gradient_fill_set_imports_midpoints_plays_and_saves_back_unchanged() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded.clone())])).unwrap())})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - let ActionStep { command: id, params: p } = s.actions.list.actions()[0].steps[0].clone(); + let ActionStep { command: id, params: p } = s.actions().list.actions()[0].steps[0].clone(); assert_eq!(id, "gradient.fill.set"); let mut expected = json!({ "style": "radial", "angle": 30, @@ -6816,8 +6817,8 @@ fn gradient_fill_set_imports_midpoints_plays_and_saves_back_unchanged() { // Default midpoints load as `[]`, which clears the custom ones when played. let mut s2 = crate::session(); s2.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded_gradient([50, 50, 50]))])).unwrap())})).unwrap(); - assert_eq!(s2.actions.list.actions()[0].steps[0].params["midpoints"], json!([])); - s.actions = s2.actions; + assert_eq!(s2.actions().list.actions()[0].steps[0].params["midpoints"], json!([])); + *s.actions_mut() = s2.actions(); s.execute("actions.play", json!({"action": "A"})).unwrap(); let photocraft_doc::Fill::Gradient { midpoints, .. } = active_fill(&s) else { panic!("not a gradient") }; assert!(midpoints.is_empty() || midpoints.iter().all(|m| *m == 0.5), "{midpoints:?}"); @@ -6828,9 +6829,9 @@ fn gradient_fill_set_imports_midpoints_plays_and_saves_back_unchanged() { fn edited_gradient_fill_set_writes_a_fresh_descriptor() { let mut s = crate::session(); s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded_gradient([50, 25, 70]))])).unwrap())})).unwrap(); - let mut step = s.actions.list.actions()[0].steps[0].clone(); + let mut step = s.actions().list.actions()[0].steps[0].clone(); step.params["midpoints"] = json!([0.4, 0.6]); - s.actions.list.replace_step(0, 0, step).unwrap(); + s.actions_mut().list.replace_step(0, 0, step).unwrap(); let (_, d) = saved_first(&mut s); let t = get_obj(d.as_ref().unwrap(), "T ").unwrap(); let clrs = get_list(get_obj(t, "Grad").unwrap(), "Clrs").unwrap(); @@ -6838,7 +6839,7 @@ fn edited_gradient_fill_set_writes_a_fresh_descriptor() { assert_eq!(mids, vec![50.0, 40.0, 60.0]); // Its own import is the edited params. let Mapped::Steps(steps) = (event_for(&AtnEvent::Code(*b"setd")).unwrap().from)(d.as_ref().unwrap()) else { panic!("did not import") }; - let mut edited = without_hidden(&s.actions.list.actions()[0].steps[0].params); + let mut edited = without_hidden(&s.actions().list.actions()[0].steps[0].params); edited["midpoints"] = json!([0.4, 0.6]); normalise(&mut edited); assert_eq!(without_hidden(&steps[0].1), edited); @@ -6852,7 +6853,7 @@ fn gradient_fill_make_imports_plays_and_saves_back_unchanged() { let mut s = crate::session(); let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_make(recorded.clone())])).unwrap())})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); - assert_eq!(s.actions.list.actions()[0].steps[0].command, "layer.newFillLayer.gradient"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, "layer.newFillLayer.gradient"); let (event, d) = saved_first(&mut s); assert_eq!(event, AtnEvent::Code(*b"Mk ")); assert_eq!(get_obj(get_obj(d.as_ref().unwrap(), "Usng").unwrap(), "Type"), Some(&recorded)); @@ -6993,7 +6994,7 @@ fn blend_if_imports_and_plays() { assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); let mut expected = json!({"blendIf": [{"channel": "gray", "thisLayer": [0, 30, 200, 255], "underlying": [10, 10, 240, 250]}, {"channel": "red", "thisLayer": [20, 40, 255, 255]}]}); normalise(&mut expected); - let ActionStep { command: id, params: p } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: id, params: p } = &s.actions().list.actions()[0].steps[0]; assert_eq!((id.as_str(), p), ("layer.layerStyle.blendingOptions", &expected)); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); @@ -7014,7 +7015,7 @@ fn blend_if_with_the_dialog_options_is_one_step_and_a_rename_splits() { let dialog = desc("Lyr ").with("Opct", pct(40.0)).with("fillOpacity", pct(70.0)).with("Md ", enm("BlnM", "Mltp")).with("Blnd", blnd.clone()); let mut s = blend_layers(8); s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(dialog.clone())])).unwrap())})).unwrap(); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps.len(), 1, "{steps:?}"); assert_eq!(steps[0].command, "layer.layerStyle.blendingOptions"); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); @@ -7029,7 +7030,7 @@ fn blend_if_with_the_dialog_options_is_one_step_and_a_rename_splits() { let mut s = blend_layers(8); s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(desc("Lyr ").with("Nm ", text("Renamed")).with("Opct", pct(40.0)).with("Blnd", blnd))])).unwrap())})) .unwrap(); - let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); + let ids: Vec<&str> = s.actions().list.actions()[0].steps.iter().map(|st| st.command.as_str()).collect(); assert!(ids.contains(&"layer.setProps") && ids.contains(&"layer.layerStyle.blendingOptions"), "{ids:?}"); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); @@ -7046,7 +7047,7 @@ fn blend_if_with_the_recorded_effects_scale_saves_back_unchanged() { let dialog = desc("Lyr ").with("Opct", pct(80.0)).with("Blnd", blnd.clone()).with("Lefx", D::Descriptor(desc("Lefx").with("Scl ", pct(100.0)))); let mut s = blend_layers(8); s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(dialog.clone())])).unwrap())})).unwrap(); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps.len(), 1, "{steps:?}"); assert_eq!(steps[0].command, "layer.layerStyle.blendingOptions"); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); @@ -7094,11 +7095,11 @@ fn save_and_reload(steps: Vec) -> (Value, Vec) { let mut s = crate::session(); let mut action = Action::new("A", steps); action.set = Some("Review".into()); - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); let saved = s.execute("actions.save", json!({"set": "Review", "skipUnsupported": true})).unwrap(); let mut fresh = crate::session(); fresh.execute("actions.load", json!({"data": saved["data"]})).unwrap(); - (saved["skipped"].clone(), fresh.actions.list.actions()[0].steps.clone()) + (saved["skipped"].clone(), fresh.actions().list.actions()[0].steps.clone()) } /// Calculations plays an omitted blending as Multiply, so Save Actions writes it as Multiply. @@ -7227,6 +7228,6 @@ fn whole_library_conditional_scopes_roundtrip() { assert_eq!(imported.actions[0].steps[0].params["thenSet"], DEFAULT_SET); assert_eq!(imported.actions[0].steps[0].params["elseSet"], DEFAULT_SET); s.execute("actions.replace", json!({"data":b64(&bytes),"confirm":true})).unwrap(); - let params = &s.actions.list.actions()[0].steps[0].params; + let params = &s.actions().list.actions()[0].steps[0].params; assert_eq!((params["then"].as_str(), params["else"].as_str()), (Some("Target"), Some("Target")), "{params}"); } diff --git a/crates/engine-core/src/cmd/automate_cmds.rs b/crates/engine-core/src/cmd/automate_cmds.rs index 0270e92089..0c875a14f1 100644 --- a/crates/engine-core/src/cmd/automate_cmds.rs +++ b/crates/engine-core/src/cmd/automate_cmds.rs @@ -12,6 +12,7 @@ //! bound in Preferences (`scriptEvents`) and fired by [`fire_event`]: the engine fires New, //! Close, Print and Export itself; the app shell fires Start, Open and Save. +use crate::actions_cmds::ActionsExt; use photocraft_doc::{Layer, LayerContent}; use serde_json::{Value, json}; @@ -307,16 +308,16 @@ pub(crate) fn named_action_steps(s: &Session, p: &Value, cmd: &str) -> Result { let set = set.as_str().ok_or_else(|| bad(cmd, "\"set\" must be a string"))?; let name = p.get("action").and_then(Value::as_str).ok_or_else(|| bad(cmd, "a set needs a named action"))?; - s.actions + s.actions() .list .actions() .iter() .position(|a| a.name == name && a.set.as_deref() == Some(set)) .ok_or_else(|| bad(cmd, format!("no action named `{name}` in set `{set}`")))? } - None => crate::actions_cmds::resolve(s.actions.list.actions(), p, cmd)?, + None => crate::actions_cmds::resolve(s.actions().list.actions(), p, cmd)?, }; - let action = s.actions.list.action(index).ok_or_else(|| bad(cmd, "the selected action no longer exists"))?; + let action = s.actions().list.action(index).ok_or_else(|| bad(cmd, "the selected action no longer exists"))?; Ok(action.enabled_steps().map(|(_, step)| (step.command.clone(), step.params.clone())).collect()) } @@ -335,7 +336,7 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result { check_known(&commands, cmd)?; // Play Action steps need their actions when the droplet runs on its own (#2794). Not under // `actions`: the CLI reads that key as an action set. - let called = crate::actions_cmds::called_actions(s.actions.list.actions(), &mut steps); + let called = crate::actions_cmds::called_actions(s.actions().list.actions(), &mut steps); let path = if path.ends_with(".pcdroplet") || path.ends_with(".json") { path.to_string() } else { format!("{path}.pcdroplet") }; let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&path)); let steps_json: Vec = steps.iter().map(|(id, pr)| json!([id, pr])).collect(); diff --git a/crates/engine-core/src/cmd/automate_cmds/tests.rs b/crates/engine-core/src/cmd/automate_cmds/tests.rs index aca34ad5d1..f83a8c8cc0 100644 --- a/crates/engine-core/src/cmd/automate_cmds/tests.rs +++ b/crates/engine-core/src/cmd/automate_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; @@ -184,7 +185,7 @@ fn batch_and_droplets_use_the_named_actions_enabled_steps() { let mut rotate = crate::actions_cmds::Action::new("Rotate", vec![ActionStep::new("image.imageRotation.90cw", json!({})), ActionStep::new("file.close", json!({}))]); rotate.disabled.insert(1); - s.actions.list = list_of(vec![invert, rotate]); + s.actions_mut().list = list_of(vec![invert, rotate]); for command in ["file.automate.batch", "file.automate.createDroplet"] { for (i, action) in [json!("Rotate"), json!(1)].into_iter().enumerate() { let output = format!("{dir}/{command}-{i}"); @@ -209,7 +210,7 @@ fn batch_and_droplets_keep_explicit_steps_and_reject_invalid_sources_before_writ let dir = tmp("action-sources"); let inputs = images(&dir, 1, 2, 1); let mut s = crate::session(); - s.actions.list.push(crate::actions_cmds::Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); for command in ["file.automate.batch", "file.automate.createDroplet"] { for (i, source) in [ json!({"steps": [["image.imageRotation.90cw", {}]], "action": "Missing"}), @@ -315,7 +316,7 @@ fn droplets_carry_the_actions_their_play_steps_call() { let inputs = images(&dir, 2, 40, 20); let mut s = crate::session(); let act = |name: &str, steps: Value| -> Action { serde_json::from_value(json!({"name": name, "steps": steps})).unwrap() }; - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ act("Unrelated", json!([["image.imageRotation.180", {}]])), act("Rotate", json!([["image.imageRotation.90cw", {}]])), // Calls Rotate by index (as the panel records it) and itself (caught at run time). @@ -347,11 +348,11 @@ fn droplets_carry_the_actions_their_play_steps_call() { assert_eq!(r["errors"].as_array().unwrap().len(), inputs.len(), "a self-call fails instead of looping: {r}"); // Retain the copied action's flags as well as its steps. - s.actions.list.append_recorded(1, [ActionStep::new("file.close", json!({}))]).unwrap(); - s.actions.list.set_step(1, 1, false).unwrap(); - s.actions.list.set_dialog(1, 0, true).unwrap(); - s.actions.list.assign_set(1, Some("Captured".into())).unwrap(); - s.actions + s.actions_mut().list.append_recorded(1, [ActionStep::new("file.close", json!({}))]).unwrap(); + s.actions_mut().list.set_step(1, 1, false).unwrap(); + s.actions_mut().list.set_dialog(1, 0, true).unwrap(); + s.actions_mut().list.assign_set(1, Some("Captured".into())).unwrap(); + s.actions_mut() .list .push(act( "BatchLoop", @@ -402,12 +403,12 @@ fn droplets_carry_the_actions_their_play_steps_call() { assert!(saved.get("calledActions").is_none(), "{name}: preserve deferred missing-target and legacy policy"); } if let Some(captured) = saved["calledActions"].as_array().and_then(|actions| actions.iter().find(|a| a["name"] == "Rotate")) { - assert_eq!(*captured, json!(s.actions.list.actions()[1]), "{name}: preserve disabled/dialog/set flags"); + assert_eq!(*captured, json!(s.actions().list.actions()[1]), "{name}: preserve disabled/dialog/set flags"); } for different in [false, true] { let mut replay = crate::session(); if different { - replay.actions.list = list_of(vec![Action::new("Unrelated", Vec::new()), Action::new("Rotate", Vec::new())]); + replay.actions_mut().list = list_of(vec![Action::new("Unrelated", Vec::new()), Action::new("Rotate", Vec::new())]); } let r = replay .execute("file.automate.runDroplet", json!({"droplet": dp, "input": [inputs[0]], "output": format!("{dir}/outer-{name}-{different}")})) @@ -446,7 +447,7 @@ fn droplets_preserve_batch_action_namespaces() { source.disabled.insert(1); source.dialogs.insert(0); source.set = Some("Captured".into()); - maker.actions.list = list_of(vec![Action::new("Gap", Vec::new()), Action::new("Outside", Vec::new()), source.clone()]); + maker.actions_mut().list = list_of(vec![Action::new("Gap", Vec::new()), Action::new("Outside", Vec::new()), source.clone()]); let embedded = vec![ Action::new("LocalGap", Vec::new()), Action::new("Inside", vec![ActionStep::new("image.imageRotation.90cw", json!({}))]), @@ -463,7 +464,7 @@ fn droplets_preserve_batch_action_namespaces() { } } if kind == "caller-null" { - maker.actions.list.append_recorded(1, [ActionStep::new("image.imageRotation.90cw", json!({}))]).unwrap(); + maker.actions_mut().list.append_recorded(1, [ActionStep::new("image.imageRotation.90cw", json!({}))]).unwrap(); batch["calledActions"] = Value::Null; } let mut steps = Vec::new(); @@ -512,7 +513,7 @@ fn droplet_scoped_variants_keep_the_existing_action_limit() { let input = images(&dir, 1, 2, 1).remove(0); for count in [4095, 4096] { let mut maker = crate::session(); - maker.actions.list = list_of((0..count).map(|i| Action::new(format!("A{i}"), Vec::new())).collect()); + maker.actions_mut().list = list_of((0..count).map(|i| Action::new(format!("A{i}"), Vec::new())).collect()); let mut steps: Vec<_> = (0..count).map(|i| json!(["actions.play", {"action": i}])).collect(); steps.push( json!(["file.automate.batch", {"action": 0, "calledActions": [], "input": [input], "output": format!("{dir}/{count}-inner"), "format": "png"}]), @@ -540,7 +541,7 @@ fn droplets_carry_the_actions_their_conditional_steps_call() { let inputs = images(&dir, 2, 40, 20); let mut s = crate::session(); let act = |name: &str, steps: Value| -> Action { serde_json::from_value(json!({"name": name, "steps": steps})).unwrap() }; - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ act("Unrelated", json!([["image.imageRotation.180", {}]])), act("Rotate", json!([["image.imageRotation.90cw", {}]])), // The then branch calls Rotate by index, as the panel records it. @@ -674,7 +675,7 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() { images(&dir, 1, 8, 4); let mut s = crate::session(); s.execute("file.new", json!({"width": 8, "height": 6})).unwrap(); - s.actions + s.actions_mut() .list .push(Action { name: "Rotate".into(), @@ -683,7 +684,7 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() { ..Default::default() }) .unwrap(); - s.actions + s.actions_mut() .list .push(Action { name: "Bad".into(), @@ -708,7 +709,7 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() { assert!(r["errors"][0]["error"].as_str().unwrap().contains("no such layer"), "{r}"); // An action that batches itself stops as a recursive call instead of overflowing the stack. let inner = json!({"steps": [["actions.play", {"action": "Loop"}]], "input": dir.clone(), "output": format!("{dir}/inner"), "format": "png"}); - s.actions + s.actions_mut() .list .push(Action { name: "Loop".into(), steps: vec![ActionStep::new("file.automate.batch", inner)], disabled: Default::default(), ..Default::default() }) .unwrap(); @@ -813,7 +814,7 @@ fn droplets_skip_actions_called_only_from_disabled_steps() { top.disabled.insert(0); let used = crate::actions_cmds::Action::new("Used", vec![ActionStep::new("image.adjustments.invert", json!({}))]); let skipped = crate::actions_cmds::Action::new("Skipped", vec![ActionStep::new("image.imageRotation.90cw", json!({}))]); - s.actions.list = list_of(vec![skipped, top, used]); + s.actions_mut().list = list_of(vec![skipped, top, used]); let r = s.execute("file.automate.createDroplet", json!({"path": format!("{dir}/D"), "steps": [["actions.play", {"action": "Top"}]], "shim": false})).unwrap(); let droplet: Value = serde_json::from_slice(&std::fs::read(r["path"].as_str().unwrap()).unwrap()).unwrap(); diff --git a/crates/engine-core/src/cmd/brush_cmds.rs b/crates/engine-core/src/cmd/brush_cmds.rs index 402616bcc9..99ce27c12f 100644 --- a/crates/engine-core/src/cmd/brush_cmds.rs +++ b/crates/engine-core/src/cmd/brush_cmds.rs @@ -6,6 +6,7 @@ //! (`{"scattering": {"enabled": true}}`). Strokes are deterministic: the jitter seed is the `seed` //! param or a hash of the points, so a journaled command replays to identical pixels. +use crate::preset_store::PresetStoreExt; use photocraft_geom::Rect; use photocraft_paint::mixer::MixerSettings; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; @@ -1326,7 +1327,7 @@ pub fn remembered_settings(b: &BrushSettings) -> Option { /// not a brush or fails the checks `tools.setBrush` makes (a size or scatter out of range). The /// options-bar values are clamped to the ranges their controls allow (size 1..max px; opacity /// 1..100 %; hardness, flow and smoothing 0..100 %), and stored tips load when the store is attached (else -/// they paint with their previews until `Session::attach_preset_store`). +/// they paint with their previews until `PresetStoreExt::attach_preset_store`). pub fn restored_settings(s: &Session, v: &Value) -> Option { if !v.is_object() { return None; diff --git a/crates/engine-core/src/cmd/brush_preset_cmds.rs b/crates/engine-core/src/cmd/brush_preset_cmds.rs index 9d25fb9209..dde2acbee6 100644 --- a/crates/engine-core/src/cmd/brush_preset_cmds.rs +++ b/crates/engine-core/src/cmd/brush_preset_cmds.rs @@ -14,6 +14,7 @@ //! and the order of every preset, built-ins included. A built-in that is renamed or moved to //! another group becomes the user's preset (built-ins are regenerated with their own group). +use crate::preset_store::PresetStoreExt; use photocraft_paint::BrushPreset; use serde_json::{Value, json}; diff --git a/crates/engine-core/src/cmd/channel_cmds/tests.rs b/crates/engine-core/src/cmd/channel_cmds/tests.rs index da49686776..7f0f0500d8 100644 --- a/crates/engine-core/src/cmd/channel_cmds/tests.rs +++ b/crates/engine-core/src/cmd/channel_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::color_cmds::ColorExt; use super::*; use photocraft_color::SampleType; diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index 35318934c1..ad13e46ef2 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -108,7 +108,7 @@ impl Policy { } /// Edit › Color Settings: working spaces, colour management policies and conversion options. -/// Honoured when files are opened ([`Session::open_document`]), by Image › Mode conversions +/// Honoured when files are opened ([`ColorExt::open_document`](crate::color_cmds::ColorExt::open_document)), by Image › Mode conversions /// and by "working" profile specs (Convert to Profile, Proof Setup). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -593,7 +593,7 @@ pub fn document_profile(doc: &Document) -> Arc { pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c }; let default_gray = Builtin::DotGain20Compat; - if s.color.settings.working_gray != default_gray.id() || document_profile(&st.doc).content_hash() != default_gray.profile().content_hash() { + if s.color().settings.working_gray != default_gray.id() || document_profile(&st.doc).content_hash() != default_gray.profile().content_hash() { return c; } let opts = craft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; @@ -971,9 +971,9 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result s.color.resolve(spec, Some(doc), Some(mode))?, + Some(spec) => s.color().resolve(spec, Some(doc), Some(mode))?, None if preserve_indexed_rgb => document_profile(doc), - None => s.color.working(mode), + None => s.color().working(mode), }; if space_mode(dst.color_space) != Some(match mode { @@ -984,8 +984,8 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result { let bytes = if spec == "none" { None } else { - let prof = s.color.resolve(spec, Some(doc), None)?; + let prof = s.color().resolve(spec, Some(doc), None)?; if prof.color_space != mode_space(doc.mode) { return Err(EngineError::Other(format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode))); } @@ -1151,9 +1151,9 @@ fn convert_to_profile(s: &mut Session, p: &Value) -> Result { if doc.mode == ColorMode::Bitmap { return Err(EngineError::Other("Convert to Profile is not available for Bitmap documents".into())); } - let dst = s.color.resolve(spec, Some(doc), None)?; - let intent = intent_or(p, s.color.settings.intent())?; - let bpc = bool_param(p, "bpc", s.color.settings.bpc); + let dst = s.color().resolve(spec, Some(doc), None)?; + let intent = intent_or(p, s.color().settings.intent())?; + let bpc = bool_param(p, "bpc", s.color().settings.bpc); let flatten = profile_option(p, "flatten")?; let rasterize = profile_option(p, "rasterizePlaced")?; let dither = profile_option(p, "dither")?; @@ -1216,7 +1216,7 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let (id, doc) = (st.doc.id, st.doc.clone()); let name = p.get("profile").and_then(Value::as_str).unwrap_or("working-cmyk").to_string(); - let profile = s.color.resolve(&name, Some(&doc), Some(ColorMode::Cmyk))?; + let profile = s.color().resolve(&name, Some(&doc), Some(ColorMode::Cmyk))?; let intent = intent_param(p)?; let setup = ProofSetup { name, @@ -1226,7 +1226,7 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { simulate_paper: bool_param(p, "simulatePaper", false), kind: crate::proof_sim::ProofKind::Profile, }; - let pv = s.color.proof_mut(id); + let pv = s.color_mut().proof_mut(id); pv.setup = setup.clone(); Ok( json!({ "profile": setup.profile.description, "intent": setup.intent.id(), "bpc": setup.bpc, "simulatePaper": setup.simulate_paper, "proofColors": pv.enabled }), @@ -1235,7 +1235,7 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { fn proof_colors(s: &mut Session, p: &Value) -> Result { let id = s.active().ok_or(EngineError::NoDocument)?.doc.id; - let pv = s.color.proof_mut(id); + let pv = s.color_mut().proof_mut(id); pv.enabled = p.get("on").and_then(Value::as_bool).unwrap_or(!pv.enabled); Ok(json!({ "on": pv.enabled, "profile": pv.setup.profile.description })) } @@ -1243,7 +1243,7 @@ fn proof_colors(s: &mut Session, p: &Value) -> Result { fn gamut_warning(s: &mut Session, p: &Value) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let doc = st.doc.clone(); - let pv = s.color.proof_mut(doc.id); + let pv = s.color_mut().proof_mut(doc.id); pv.gamut_warning = p.get("on").and_then(Value::as_bool).unwrap_or(!pv.gamut_warning); if let Some(t) = p.get("threshold").and_then(Value::as_f64) { pv.gamut_threshold = t.max(0.0) as f32; @@ -1261,7 +1261,7 @@ fn gamut_warning(s: &mut Session, p: &Value) -> Result { /// Edit › Color Settings: read or change working spaces, policies and conversion options. fn color_settings(s: &mut Session, p: &Value) -> Result { let cmd = "edit.colorSettings"; - let mut next = s.color.settings.clone(); + let mut next = s.color().settings.clone(); if p.get("reset").and_then(Value::as_bool) == Some(true) { next = ColorSettings::default(); } @@ -1318,22 +1318,22 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { next.spot_dot_gain = g as f32; } validate_settings(&next).map_err(|msg| EngineError::BadParams { cmd: cmd.into(), msg })?; - if next != s.color.settings { + if next != s.color().settings { photocraft_compose::psblend::set_text_gamma(next.blend_text_gamma); photocraft_compose::multichannel::set_spot_dot_gain(next.spot_dot_gain); - s.color.settings = next; + s.color_mut().settings = next; // Persisted with the preferences. s.prefs.edit(|_| ()); } - let c = &s.color.settings; - let desc = |m: ColorMode| s.color.working(m).description.clone(); + let c = &s.color().settings; + let desc = |m: ColorMode| s.color().working(m).description.clone(); Ok(json!({ "settings": c, "working": {"rgb": desc(ColorMode::Rgb), "cmyk": desc(ColorMode::Cmyk), "gray": desc(ColorMode::Grayscale)}, - "monitor": s.color.monitor().description, - "monitorDetected": !s.color.displays.is_empty(), - "monitorStatus": s.color.monitor_status(), - "displays": s.color.display_statuses(), + "monitor": s.color().monitor().description, + "monitorDetected": !s.color().displays.is_empty(), + "monitorStatus": s.color().monitor_status(), + "displays": s.color().display_statuses(), })) } @@ -1345,8 +1345,8 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result { match action { "preserve" | "useEmbedded" => Ok(json!({"action": "kept"})), "convert" | "convertToWorking" => { - let dst = s.color.working(mode); - let (intent, bpc) = (s.color.settings.intent(), s.color.settings.bpc); + let dst = s.color().working(mode); + let (intent, bpc) = (s.color().settings.intent(), s.color().settings.bpc); s.edit("Convert to Working RGB", |doc, _| convert_document(doc, &dst, intent, bpc))?; Ok(json!({"action": "converted", "profile": dst.description})) } @@ -1358,7 +1358,7 @@ fn profile_mismatch(s: &mut Session, p: &Value) -> Result { Ok(json!({"action": "discarded"})) } "assignWorking" => { - let w = s.color.working(mode); + let w = s.color().working(mode); s.edit("Assign Profile", |doc, _| { doc.icc_profile = Some(w.to_bytes()); Ok(()) @@ -1630,26 +1630,26 @@ mod tests { monitor.description = "Synthetic identity-matrix gamma monitor".into(); monitor.trc = Some(std::array::from_fn(|_| craft_cms::Curve::Gamma(2.2))); let monitor = monitor.with_encoded_bytes(); - s.color.set_displays(Ok(vec![crate::display_color::Display { + s.color_mut().set_displays(Ok(vec![crate::display_color::Display { id: 1, name: "Synthetic monitor".into(), frame: [0.0, 0.0, 800.0, 600.0], profile_name: None, icc: Some(monitor.to_bytes()), }])); - let pv = s.color.proof_mut(d.id); + let pv = s.color_mut().proof_mut(d.id); pv.setup.profile = Arc::new(Profile::parse(&proof.to_bytes()).unwrap()); pv.enabled = true; - assert!(s.color.gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_some(), "ordinary profile conversion is separable"); + assert!(s.color().gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_some(), "ordinary profile conversion is separable"); for command in ["view.proofSetup.legacyMacintoshRgb", "view.proofSetup.colorBlindnessProtanopia", "view.proofSetup.colorBlindnessDeuteranopia"] { // These commands retain the previously selected custom profile. s.execute(command, json!({})).unwrap(); - assert!(s.color.display_transform_for(&d, Some(1)).unwrap().gpu_matrix_shaper().is_some(), "fixture must exercise the shortcut"); - assert!(s.color.gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_none(), "{command} must retain its simulation"); - assert!(s.color.gpu_canvas_lut_for(&d, 9, Some(1)).unwrap().is_some(), "{command} still has its LUT fallback"); + assert!(s.color().display_transform_for(&d, Some(1)).unwrap().gpu_matrix_shaper().is_some(), "fixture must exercise the shortcut"); + assert!(s.color().gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_none(), "{command} must retain its simulation"); + assert!(s.color().gpu_canvas_lut_for(&d, 9, Some(1)).unwrap().is_some(), "{command} still has its LUT fallback"); } s.execute("view.proofColors", json!({"on": false})).unwrap(); - assert!(s.color.gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_some(), "disabled simulations do not block ordinary display conversion"); + assert!(s.color().gpu_canvas_matrix_shaper_for(&d, Some(1)).unwrap().is_some(), "disabled simulations do not block ordinary display conversion"); } #[test] @@ -1657,27 +1657,27 @@ mod tests { let mut s = session("rgb", 8); paint_rgb(&mut s); let id = doc(&s).id; - assert!(!s.color.proof(id).enabled); + assert!(!s.color().proof(id).enabled); s.execute("view.proofSetup", json!({"profile": "coated-cmyk", "intent": "perceptual", "simulatePaper": true})).unwrap(); - let pv = s.color.proof(id); + let pv = s.color().proof(id); assert_eq!((pv.setup.intent, pv.setup.simulate_paper), (Intent::Perceptual, true)); s.execute("view.proofColors", json!({})).unwrap(); - assert!(s.color.proof(id).enabled); + assert!(s.color().proof(id).enabled); let d = doc(&s).clone(); - let t = s.color.display_transform(&d).unwrap(); + let t = s.color().display_transform(&d).unwrap(); let mut o = [0.0f32; 3]; t.eval(&[1.0, 1.0, 1.0], &mut o).unwrap(); assert!(o[0] < 0.97, "paper simulation: {o:?}"); - let lut = s.color.display_lut(&d, 17).unwrap(); + let lut = s.color().display_lut(&d, 17).unwrap(); assert_eq!(lut.data().len(), 17 * 17 * 17); s.execute("view.proofColors", json!({"on": false})).unwrap(); - let t2 = s.color.display_transform(&d).unwrap(); + let t2 = s.color().display_transform(&d).unwrap(); t2.eval(&[1.0, 1.0, 1.0], &mut o).unwrap(); assert!(o.iter().all(|v| (v - 1.0).abs() < 1e-3), "no proof: identity-ish {o:?}"); // Saturated sRGB blue is outside coated CMYK; mid gray and white are inside. let r = s.execute("view.gamutWarning", json!({"on": true})).unwrap(); assert!(r["on"].as_bool().unwrap()); - let (mask, count) = gamut_mask(&d, &s.color.proof(id).setup, 4.0).unwrap(); + let (mask, count) = gamut_mask(&d, &s.color().proof(id).setup, 4.0).unwrap(); assert_eq!(r["outOfGamut"].as_u64().unwrap() as usize, count); let w = d.size.width as usize; assert_eq!(mask[8 * w + 20], 255, "blue out of gamut"); @@ -1690,7 +1690,7 @@ mod tests { let s = session("gray", 8); let p = composite_profile(doc(&s)); assert_eq!(p.color_space, ColorSpace::Rgb); - let t = s.color.display_transform(doc(&s)).unwrap(); + let t = s.color().display_transform(doc(&s)).unwrap(); let mut o = [0.0f32; 3]; t.eval(&[0.5, 0.5, 0.5], &mut o).unwrap(); // The default working gray (Dot Gain 20 %-compatible, gamma 1.732) shows gray 0.5 as the @@ -1738,6 +1738,7 @@ mod assign_profile_enabled_modes_tests; #[cfg(test)] mod settings_tests { + use crate::prefs::SavedPrefsExt; use super::*; fn tagged(spec: &str) -> Document { @@ -1760,11 +1761,11 @@ mod settings_tests { assert!(s.execute("edit.colorSettings", json!({"intent": "vivid"})).is_err()); let r = s.execute("edit.colorSettings", json!({"workingRgb": "adobe-rgb-compat", "intent": "perceptual", "bpc": false})).unwrap(); assert!(r["working"]["rgb"].as_str().unwrap().starts_with("Adobe RGB")); - assert_eq!(s.color.settings.intent(), Intent::Perceptual); + assert_eq!(s.color().settings.intent(), Intent::Perceptual); // Settings travel with the preferences file. let mut t = crate::session(); t.load_prefs_json(&s.prefs_to_json()).unwrap(); - assert_eq!(t.color.settings, s.color.settings); + assert_eq!(t.color().settings, s.color().settings); } // The Blend Text Colors Using Gamma test is `tests/text_gamma.rs`: it changes the @@ -1775,28 +1776,28 @@ mod settings_tests { let mut s = crate::session(); // Ask When Opening off: nothing to ask, mismatched or missing. s.execute("edit.colorSettings", json!({"askOnMismatch": false, "askOnMissing": false})).unwrap(); - assert!(s.color.open_question(&tagged("adobe-rgb-compat")).is_none()); + assert!(s.color().open_question(&tagged("adobe-rgb-compat")).is_none()); let mut untagged = tagged("srgb"); untagged.icc_profile = None; - assert!(s.color.open_question(&untagged).is_none()); + assert!(s.color().open_question(&untagged).is_none()); // On: a mismatch asks, suggesting the policy's answer; a matching profile never asks. s.execute("edit.colorSettings", json!({"askOnMismatch": true, "askOnMissing": true, "policyRgb": "convert"})).unwrap(); - let q = s.color.open_question(&tagged("adobe-rgb-compat")).unwrap(); + let q = s.color().open_question(&tagged("adobe-rgb-compat")).unwrap(); assert_eq!((q["mismatch"].as_bool(), q["action"].as_str()), (Some(true), Some("convert"))); assert!(q["embedded"].as_str().unwrap().starts_with("Adobe RGB")); - assert!(s.color.open_question(&tagged("srgb")).is_none()); - assert_eq!(s.color.open_question(&untagged).unwrap()["missing"], true); + assert!(s.color().open_question(&tagged("srgb")).is_none()); + assert_eq!(s.color().open_question(&untagged).unwrap()["missing"], true); // Asking changes nothing; the answer is applied to the document. let mut d = tagged("adobe-rgb-compat"); - s.color.resolve_open(&mut d, "preserve").unwrap(); + s.color().resolve_open(&mut d, "preserve").unwrap(); assert!(desc(&d).unwrap().starts_with("Adobe RGB")); - s.color.resolve_open(&mut d, "convert").unwrap(); + s.color().resolve_open(&mut d, "convert").unwrap(); assert_eq!(desc(&d).as_deref(), Some("sRGB IEC61966-2.1")); - s.color.resolve_open(&mut d, "discard").unwrap(); + s.color().resolve_open(&mut d, "discard").unwrap(); assert_eq!(desc(&d), None); - s.color.resolve_open(&mut d, "assignWorking").unwrap(); + s.color().resolve_open(&mut d, "assignWorking").unwrap(); assert_eq!(desc(&d).as_deref(), Some("sRGB IEC61966-2.1")); - assert!(s.color.resolve_open(&mut d, "explode").is_err()); + assert!(s.color().resolve_open(&mut d, "explode").is_err()); } #[test] @@ -1995,7 +1996,7 @@ mod settings_tests { assert!(desc(d).unwrap().contains("2020"), "depth {depth}: {:?}", desc(d)); } // "working" specs follow the settings too. - let p = s.color.resolve("working-rgb", None, None).unwrap(); + let p = s.color().resolve("working-rgb", None, None).unwrap(); assert!(p.description.contains("2020")); } diff --git a/crates/engine-core/src/cmd/comps_cmds/tests.rs b/crates/engine-core/src/cmd/comps_cmds/tests.rs index 965d5fec48..dc3c8698bf 100644 --- a/crates/engine-core/src/cmd/comps_cmds/tests.rs +++ b/crates/engine-core/src/cmd/comps_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; use photocraft_color::BlendMode; use photocraft_doc::Layer; @@ -525,7 +526,7 @@ fn a_recorded_apply_layer_comp_finds_the_comp_by_name() { // A second document whose comp with the recorded id is another one. let (mut other, _, ob) = session(8); - other.actions = s.actions.clone(); + *other.actions_mut() = s.actions().clone(); let show = |s: &mut Session, visible: bool| { s.edit("t", |d, _| { d.layer_mut(ob).unwrap().visible = visible; diff --git a/crates/engine-core/src/cmd/contour_lib_cmds.rs b/crates/engine-core/src/cmd/contour_lib_cmds.rs index 6e7a13ae06..a0f5049f73 100644 --- a/crates/engine-core/src/cmd/contour_lib_cmds.rs +++ b/crates/engine-core/src/cmd/contour_lib_cmds.rs @@ -7,6 +7,8 @@ //! history. A user contour is applied to an effect as a `contour` curve object (see //! [`contour_param`]); `.shc` files go through `craft_psd::shc` (see [`contours_from_shc`]). +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_doc::Contour; use photocraft_doc::adjust::CurvePoint; use serde_json::{Value, json}; @@ -81,7 +83,7 @@ pub fn from_json(v: &Value) -> Vec { } fn list(s: &mut Session, _: &Value) -> Result { - let lib = &s.presets.contours; + let lib = &s.presets().contours; Ok(json!({"count": lib.len(), "contours": lib.iter().map(|c| json!({"name": name_of(c), "contour": contour_param(c)})).collect::>()})) } @@ -89,32 +91,32 @@ fn new(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.contours.new"; let c = contour_from_param(p.get("contour").ok_or_else(|| bad(CMD, "missing `contour` (a standard contour's name or a curve object)"))?) .ok_or_else(|| bad(CMD, "`contour` is not a usable contour (unknown name, or a curve with fewer than 2 or more than 64 points)"))?; - if s.presets.contours.len() >= MAX_USER_CONTOURS { + if s.presets().contours.len() >= MAX_USER_CONTOURS { return Err(bad(CMD, format!("the contour library is full ({MAX_USER_CONTOURS} contours)"))); } let name = match p.get("name") { - None | Some(Value::Null) => format!("Contour {}", s.presets.contours.len() + 1), + None | Some(Value::Null) => format!("Contour {}", s.presets().contours.len() + 1), Some(Value::String(n)) if !n.trim().is_empty() => n.trim().to_string(), Some(_) => return Err(bad(CMD, "`name` must be a non-empty string")), }; - let name = add(&mut s.presets.contours, c, &name); - s.presets_changed(); - let contour = s.presets.contours.last().map(contour_param).unwrap_or(Value::Null); - Ok(json!({"name": name, "contour": contour, "count": s.presets.contours.len()})) + let name = add(&mut s.presets_mut().contours, c, &name); + presets_changed(s); + let contour = s.presets().contours.last().map(contour_param).unwrap_or(Value::Null); + Ok(json!({"name": name, "contour": contour, "count": s.presets().contours.len()})) } fn delete(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.contours.delete"; let name = str_param(p, "name").ok_or_else(|| bad(CMD, "missing `name`"))?; let at = s - .presets + .presets() .contours .iter() .position(|c| name_of(c) == name) .ok_or_else(|| bad(CMD, format!("no user contour \"{name}\" (see layer.layerStyle.contours.list)")))?; - s.presets.contours.remove(at); - s.presets_changed(); - Ok(json!({"deleted": name, "count": s.presets.contours.len()})) + s.presets_mut().contours.remove(at); + presets_changed(s); + Ok(json!({"deleted": name, "count": s.presets().contours.len()})) } fn load(s: &mut Session, p: &Value) -> Result { @@ -130,7 +132,7 @@ fn load(s: &mut Session, p: &Value) -> Result { if loaded.is_empty() { return Err(bad(CMD, "the file holds no usable contours")); } - let mut lib = if replace { Vec::new() } else { s.presets.contours.clone() }; + let mut lib = if replace { Vec::new() } else { s.presets().contours.clone() }; let mut names = Vec::new(); for c in loaded { if lib.len() >= MAX_USER_CONTOURS { @@ -139,20 +141,20 @@ fn load(s: &mut Session, p: &Value) -> Result { let n = name_of(&c).to_string(); names.push(add(&mut lib, c, &n)); } - s.presets.contours = lib; - s.presets_changed(); - Ok(json!({"loaded": names, "count": s.presets.contours.len(), "skipped": found.len() - names.len()})) + s.presets_mut().contours = lib; + presets_changed(s); + Ok(json!({"loaded": names, "count": s.presets().contours.len(), "skipped": found.len() - names.len()})) } fn save(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.contours.save"; let lib: Vec<&Contour> = match p.get("names") { - None | Some(Value::Null) => s.presets.contours.iter().collect(), + None | Some(Value::Null) => s.presets().contours.iter().collect(), Some(Value::Array(a)) => { let mut v = Vec::new(); for n in a { let n = n.as_str().ok_or_else(|| bad(CMD, "`names` must be strings"))?; - v.push(s.presets.contours.iter().find(|c| name_of(c) == n).ok_or_else(|| bad(CMD, format!("no user contour \"{n}\"")))?); + v.push(s.presets().contours.iter().find(|c| name_of(c) == n).ok_or_else(|| bad(CMD, format!("no user contour \"{n}\"")))?); } v } @@ -257,7 +259,7 @@ mod tests { // Appending the same file again keeps every name unique. let r = load(&mut s, &json!({"data": data})).unwrap(); assert_eq!(r["count"], 6); - let names: std::collections::HashSet<_> = s.presets.contours.iter().map(|c| name_of(c).to_string()).collect(); + let names: std::collections::HashSet<_> = s.presets().contours.iter().map(|c| name_of(c).to_string()).collect(); assert_eq!(names.len(), 6); } @@ -265,12 +267,12 @@ mod tests { fn library_persists_with_the_presets() { let mut s = crate::session(); new(&mut s, &json!({"contour": curve("x"), "name": "Mine"})).unwrap(); - let saved = s.presets.to_json(&s); + let saved = s.presets().to_json(&s); let mut t = crate::session(); t.load_presets_json(saved); - assert_eq!(t.presets.contours.len(), 1); - assert_eq!(name_of(&t.presets.contours[0]), "Mine"); - assert_eq!(t.presets.contours, s.presets.contours); + assert_eq!(t.presets().contours.len(), 1); + assert_eq!(name_of(&t.presets().contours[0]), "Mine"); + assert_eq!(t.presets().contours, s.presets().contours); } #[test] @@ -285,7 +287,7 @@ mod tests { assert!(delete(&mut s, &json!({})).is_err()); assert!(save(&mut s, &json!({})).is_err(), "empty library"); new(&mut s, &json!({"contour": curve("x"), "name": "Existing"})).unwrap(); - let before = s.presets.contours.clone(); + let before = s.presets().contours.clone(); for p in [ json!({}), json!({"data": 3}), @@ -296,9 +298,9 @@ mod tests { json!({"path": "/nonexistent/x.shc"}), ] { assert!(load(&mut s, &p).is_err(), "{p}"); - assert_eq!(s.presets.contours, before, "{p}"); + assert_eq!(s.presets().contours, before, "{p}"); } - assert_eq!(s.presets.contours, before); + assert_eq!(s.presets().contours, before); let big = from_json(&json!([{"points": [[0, 0]]}, "Ring", 7, {"name": "Cone", "points": [[0, 0], [1, 1]]}])); assert_eq!(big.len(), 1); assert_eq!(name_of(&big[0]), "Cone 2"); @@ -307,12 +309,12 @@ mod tests { fn malformed_persisted_library_keeps_existing_contours() { let mut s = crate::session(); new(&mut s, &json!({"contour": curve("x"), "name": "Existing"})).unwrap(); - let before = s.presets.contours.clone(); + let before = s.presets().contours.clone(); for value in [json!(null), json!(3), json!("bad"), json!({})] { s.load_presets_json(json!({"contours": value})); - assert_eq!(s.presets.contours, before); + assert_eq!(s.presets().contours, before); } s.load_presets_json(json!({"contours": []})); - assert!(s.presets.contours.is_empty()); + assert!(s.presets().contours.is_empty()); } } diff --git a/crates/engine-core/src/cmd/document_preset_cmds.rs b/crates/engine-core/src/cmd/document_preset_cmds.rs index 85d77dc4fc..0cb58c2291 100644 --- a/crates/engine-core/src/cmd/document_preset_cmds.rs +++ b/crates/engine-core/src/cmd/document_preset_cmds.rs @@ -1,6 +1,8 @@ //! Named New Document configurations. The existing preferences services persist these with the //! other presets; selecting one only returns settings, and document creation stays in `file.new`. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_color::{ColorMode, SampleType}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -270,44 +272,44 @@ pub(crate) fn load_recent(value: Value) -> Vec { fn add_recent(s: &mut Session, p: &Value) -> Result { const CMD: &str = "document.recent.add"; let settings = DocumentSettings::from_params(s, p.get("settings").unwrap_or(&Value::Null), CMD)?; - let recent = &mut s.presets.recent_documents; + let recent = &mut s.presets_mut().recent_documents; recent.retain(|r| r.command_params() != settings.command_params()); recent.insert(0, settings); recent.truncate(MAX_RECENT); - s.presets_changed(); - Ok(json!({"recent":s.presets.recent_documents})) + presets_changed(s); + Ok(json!({"recent":s.presets().recent_documents})) } fn save(s: &mut Session, p: &Value) -> Result { const CMD: &str = "document.presets.save"; let name = checked_name(req_str(p, "name", CMD)?).map_err(|e| bad(CMD, e))?; - if s.presets.documents.iter().any(|pr| pr.name.eq_ignore_ascii_case(&name)) { + if s.presets().documents.iter().any(|pr| pr.name.eq_ignore_ascii_case(&name)) { return Err(bad(CMD, format!("A preset named \"{name}\" already exists; choose another name"))); } - if s.presets.documents.len() >= MAX_PRESETS { + if s.presets().documents.len() >= MAX_PRESETS { return Err(bad(CMD, format!("At most {MAX_PRESETS} document presets can be saved"))); } let settings = DocumentSettings::from_params(s, p.get("settings").unwrap_or(&Value::Null), CMD)?; let preset = DocumentPreset { name, settings }; let result = json!({"preset":preset}); - s.presets.documents.push(preset); - s.presets_changed(); + s.presets_mut().documents.push(preset); + presets_changed(s); Ok(result) } fn get(s: &mut Session, p: &Value) -> Result { const CMD: &str = "document.presets.get"; let name = req_str(p, "name", CMD)?; - let preset = s.presets.documents.iter().find(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; + let preset = s.presets().documents.iter().find(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; Ok(json!({"preset":preset,"params":preset.settings.command_params()})) } fn delete(s: &mut Session, p: &Value) -> Result { const CMD: &str = "document.presets.delete"; let name = req_str(p, "name", CMD)?; - let index = s.presets.documents.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; - s.presets.documents.remove(index); - s.presets_changed(); + let index = s.presets().documents.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; + s.presets_mut().documents.remove(index); + presets_changed(s); Ok(json!({"deleted":name})) } @@ -317,12 +319,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { const CMD: &str = "document.presets.rename"; let name = req_str(p, "name", CMD)?; let new_name = checked_name(req_str(p, "newName", CMD)?).map_err(|e| bad(CMD, e))?; - let index = s.presets.documents.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; - if s.presets.documents.iter().enumerate().any(|(i, pr)| i != index && pr.name.eq_ignore_ascii_case(&new_name)) { + let index = s.presets().documents.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such document preset"))?; + if s.presets().documents.iter().enumerate().any(|(i, pr)| i != index && pr.name.eq_ignore_ascii_case(&new_name)) { return Err(bad(CMD, format!("A preset named \"{new_name}\" already exists; choose another name"))); } - s.presets.documents[index].name.clone_from(&new_name); - s.presets_changed(); + s.presets_mut().documents[index].name.clone_from(&new_name); + presets_changed(s); Ok(json!({"renamed":new_name})) } @@ -335,7 +337,7 @@ pub fn specs() -> Vec { shortcut: None, params: "{}", enabled: always, - run: |s, _| Ok(json!({"presets":s.presets.documents})), + run: |s, _| Ok(json!({"presets":s.presets().documents})), journal: false, }, CommandSpec { @@ -385,7 +387,7 @@ pub fn specs() -> Vec { shortcut: None, params: "{} -> {recent:[settings]} (newest first; each settings.command params minus unit/resolutionUnit go to file.new)", enabled: always, - run: |s, _| Ok(json!({"recent":s.presets.recent_documents})), + run: |s, _| Ok(json!({"recent":s.presets().recent_documents})), journal: false, }, CommandSpec { @@ -404,6 +406,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::prefs::SavedPrefsExt; use super::*; fn settings() -> Value { @@ -432,14 +435,14 @@ mod tests { let preset = saved(&mut s, "Press", config.clone()); assert_eq!(preset["settings"]["profile"], "coated-cmyk"); let next = reload(&s); - let params = next.presets.documents[0].settings.command_params(); + let params = next.presets().documents[0].settings.command_params(); assert_eq!(params["profile"], "coated-cmyk"); let mut s2 = crate::session(); s2.execute("file.new", params).unwrap(); assert!(s2.active().unwrap().doc.icc_profile.is_some()); let plain = saved(&mut s, "Plain", settings()); assert!(plain["settings"].get("profile").is_none()); - assert!(s.presets.documents[1].settings.command_params().get("profile").is_none()); + assert!(s.presets().documents[1].settings.command_params().get("profile").is_none()); } #[test] @@ -454,7 +457,7 @@ mod tests { assert_eq!(preset["name"], "Product square"); assert_eq!(preset["settings"], config); let mut next = reload(&s); - assert_eq!(next.presets.documents, s.presets.documents); + assert_eq!(next.presets().documents, s.presets().documents); let rev = next.prefs.rev(); let selected = next.execute("document.presets.get", json!({"name":"product SQUARE"})).unwrap(); assert_eq!(selected["preset"], preset); @@ -509,7 +512,7 @@ mod tests { assert!(s.prefs.rev() > rev); let mut s = reload(&s); assert_eq!(s.execute("document.presets.list", json!({})).unwrap()["presets"].as_array().unwrap().len(), 1); - assert_eq!(s.presets.documents[0].name, "Keep me"); + assert_eq!(s.presets().documents[0].name, "Keep me"); assert!(s.execute("document.presets.get", json!({"name":"Delete me"})).is_err()); assert!(s.execute("document.presets.delete", json!({"name":"Delete me"})).is_err()); } @@ -518,7 +521,7 @@ mod tests { fn old_preferences_and_malformed_presets_keep_unrelated_settings() { let mut original = crate::session(); original.edit_prefs(|p| p.general.beep_when_done = true); - original.presets.tool_presets[0].name = "Unrelated tool preset".into(); + original.presets_mut().tool_presets[0].name = "Unrelated tool preset".into(); let valid = saved(&mut original, "Keep me", settings()); for invalid in [json!("bad collection"), json!([false, {}, {"name":"broken","settings":{}}])] { let mut value = original.prefs_value(); @@ -526,8 +529,8 @@ mod tests { let mut s = crate::session(); s.load_prefs_json(&value.to_string()).unwrap(); assert!(s.prefs().general.beep_when_done); - assert_eq!(s.presets.tool_presets[0].name, "Unrelated tool preset"); - assert!(s.presets.documents.is_empty()); + assert_eq!(s.presets().tool_presets[0].name, "Unrelated tool preset"); + assert!(s.presets().documents.is_empty()); } let mut value = original.prefs_value(); let mut bad = valid.clone(); @@ -535,8 +538,8 @@ mod tests { value["presets"]["documents"] = json!([bad, valid, valid]); let mut s = crate::session(); s.load_prefs_json(&value.to_string()).unwrap(); - assert_eq!(s.presets.documents.len(), 1, "keep valid entries, discard bad/duplicate entries"); - assert_eq!(s.presets.documents[0].name, "Keep me"); + assert_eq!(s.presets().documents.len(), 1, "keep valid entries, discard bad/duplicate entries"); + assert_eq!(s.presets().documents[0].name, "Keep me"); for without_presets in [false, true] { let mut value = original.prefs_value(); if without_presets { @@ -546,7 +549,7 @@ mod tests { } let mut old = crate::session(); old.load_prefs_json(&value.to_string()).unwrap(); - assert!(old.presets.documents.is_empty()); + assert!(old.presets().documents.is_empty()); assert!(old.prefs().general.beep_when_done); } } @@ -557,7 +560,7 @@ mod tests { let mut config = settings(); saved(&mut s, "Keep me", config.clone()); config["width"] = json!(99); - assert_eq!(s.presets.documents[0].settings.width, 16); + assert_eq!(s.presets().documents[0].settings.width, 16); let before = s.prefs_value(); let rev = s.prefs.rev(); for name in ["", " \t\n ", "Keep me", " keep ME ", &"x".repeat(256)] { @@ -620,7 +623,7 @@ mod tests { value["presets"]["recent_documents"] = json!([{"width":-1}, recent[1], "junk", recent[1], recent[2]]); let mut next = crate::session(); next.load_prefs_json(&value.to_string()).unwrap(); - assert_eq!(next.presets.recent_documents.iter().map(|r| r.width).collect::>(), [25, 24]); + assert_eq!(next.presets().recent_documents.iter().map(|r| r.width).collect::>(), [25, 24]); assert!(next.documents().is_empty(), "recording never creates a document"); } @@ -630,7 +633,7 @@ mod tests { for name in ["One", "Two", "Three"] { saved(&mut s, name, settings()); } - let names = |s: &Session| s.presets.documents.iter().map(|p| p.name.clone()).collect::>(); + let names = |s: &Session| s.presets().documents.iter().map(|p| p.name.clone()).collect::>(); s.execute("document.presets.rename", json!({"name":"Two","newName":" Zwei "})).unwrap(); assert_eq!(names(&s), ["One", "Zwei", "Three"]); s.execute("document.presets.rename", json!({"name":"Zwei","newName":"ZWEI"})).unwrap(); diff --git a/crates/engine-core/src/cmd/edit_menu_cmds.rs b/crates/engine-core/src/cmd/edit_menu_cmds.rs index 79a39df192..a9ae828940 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds.rs @@ -5,6 +5,9 @@ //! Check Spelling is not implemented: it needs a word list per language, and no permissively //! licensed dictionary small enough to bundle (or a pure-Rust checker with one) was available. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; +use crate::preset_store::PresetStoreExt; use photocraft_color::{BlendMode, PixelFormat}; use photocraft_doc::vector::Path; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; @@ -211,7 +214,7 @@ fn export_import(s: &mut Session, p: &Value) -> Result { custom_shapes: if want("customShapes") { s.edit_state.custom_shapes.clone() } else { Vec::new() }, tool_presets: if want("tools") { let builtins = crate::presets::tools::builtin(); - s.presets.tool_presets.iter().filter(|preset| bool_or(p, "includeBuiltins", false) || !builtins.contains(preset)).cloned().collect() + s.presets().tool_presets.iter().filter(|preset| bool_or(p, "includeBuiltins", false) || !builtins.contains(preset)).cloned().collect() } else { Vec::new() }, @@ -229,7 +232,7 @@ fn export_import(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("not a preset file (format `{}`)", file.format))); } // Validate the whole tool import before changing any preset library. - let mut tools = s.presets.tool_presets.clone(); + let mut tools = s.presets().tool_presets.clone(); let nt = if want("tools") { file.tool_presets.len() } else { 0 }; if nt > crate::presets::tools::MAX_PRESETS { return Err(bad(cmd, "too many tool presets")); @@ -276,8 +279,8 @@ fn export_import(s: &mut Session, p: &Value) -> Result { } } if want("tools") { - s.presets.tool_presets = tools; - s.presets_changed(); + s.presets_mut().tool_presets = tools; + presets_changed(s); } Ok(json!({"brushes": nb, "customShapes": ns, "tools": nt})) } diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs index 6f2d0601d2..182c09e977 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/presets.rs @@ -1,3 +1,4 @@ +use crate::preset_store::PresetStoreExt; use super::{CustomShape, Deserialize, Document, EngineError, LayerContent, LayerId, Path, Result, Serialize, Session, Value, bad, json, str_or}; // ------------------------------------------------------------------ Define Brush / Custom Shape diff --git a/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs b/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs index c2c83df2ee..84f08a6cb2 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::presets::PresetsExt; use super::*; use photocraft_doc::vector::Subpath; @@ -904,17 +905,17 @@ fn tool_presets_round_trip_through_export_import() { } let selected = target.execute("tool.presets.select", json!({"preset":"2 : 3"})).unwrap(); assert_eq!(selected["options"]["toolOptions"]["crop_ratio"], "2:3"); - assert_eq!(target.presets.tool_presets.iter().filter(|p| p.name == "2 : 3").count(), 1); + assert_eq!(target.presets().tool_presets.iter().filter(|p| p.name == "2 : 3").count(), 1); let only_brushes = source.execute("edit.presets.exportImportPresets", json!({"kinds":["brushes"]})).unwrap(); assert_eq!(only_brushes["tools"], 0); let with_builtins = source.execute("edit.presets.exportImportPresets", json!({"kinds":["tools"], "includeBuiltins":true})).unwrap(); - assert_eq!(with_builtins["tools"].as_u64().unwrap() as usize, source.presets.tool_presets.len()); + assert_eq!(with_builtins["tools"].as_u64().unwrap() as usize, source.presets().tool_presets.len()); } #[test] fn tool_preset_import_is_validated_before_mutation_and_accepts_old_files() { let mut s = crate::session(); - let before = s.presets.tool_presets.clone(); + let before = s.presets().tool_presets.clone(); for preset in [ json!({"name":"", "tool":"crop", "options":{}}), json!({"name":"x".repeat(256), "tool":"crop", "options":{}}), @@ -926,11 +927,11 @@ fn tool_preset_import_is_validated_before_mutation_and_accepts_old_files() { json!({"action":"import", "data":{"format":PRESET_FORMAT, "toolPresets":[{"name":"Valid", "tool":"crop", "options":{}}, preset]}}), ); assert!(result.is_err()); - assert_eq!(s.presets.tool_presets, before); + assert_eq!(s.presets().tool_presets, before); } let too_many: Vec<_> = (0..crate::presets::tools::MAX_PRESETS + 1).map(|i| json!({"name":format!("Crop {i}"), "tool":"crop", "options":{}})).collect(); assert!(s.execute("edit.presets.exportImportPresets", json!({"action":"import", "data":{"format":PRESET_FORMAT, "toolPresets":too_many}})).is_err()); - assert_eq!(s.presets.tool_presets, before); + assert_eq!(s.presets().tool_presets, before); let result = s.execute("edit.presets.exportImportPresets", json!({"action":"import", "data":{"format":PRESET_FORMAT, "version":1}})).unwrap(); assert_eq!(result["tools"], 0); } diff --git a/crates/engine-core/src/cmd/export_preset_cmds.rs b/crates/engine-core/src/cmd/export_preset_cmds.rs index 29bbd15809..4bf74ed2db 100644 --- a/crates/engine-core/src/cmd/export_preset_cmds.rs +++ b/crates/engine-core/src/cmd/export_preset_cmds.rs @@ -1,6 +1,8 @@ //! Named Export As configurations. They persist with the other presets in the preferences //! document; applying one only returns settings, and the export itself stays in Export As. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -173,33 +175,33 @@ pub(crate) fn load(value: Value) -> Vec { fn save(s: &mut Session, p: &Value) -> Result { const CMD: &str = "file.export.presets.save"; let name = checked_name(req_str(p, "name", CMD)?).map_err(|e| bad(CMD, e))?; - if s.presets.export_presets.len() >= MAX_PRESETS && s.presets.export_presets.iter().all(|pr| !pr.name.eq_ignore_ascii_case(&name)) { + if s.presets().export_presets.len() >= MAX_PRESETS && s.presets().export_presets.iter().all(|pr| !pr.name.eq_ignore_ascii_case(&name)) { return Err(bad(CMD, format!("At most {MAX_PRESETS} export presets can be saved"))); } let settings = ExportPresetSettings::from_params(p.get("settings").unwrap_or(&Value::Null), CMD)?; let preset = ExportPreset { name: name.clone(), settings }; - if let Some(existing) = s.presets.export_presets.iter_mut().find(|pr| pr.name.eq_ignore_ascii_case(&name)) { + if let Some(existing) = s.presets_mut().export_presets.iter_mut().find(|pr| pr.name.eq_ignore_ascii_case(&name)) { *existing = preset.clone(); } else { - s.presets.export_presets.push(preset.clone()); + s.presets_mut().export_presets.push(preset.clone()); } - s.presets_changed(); + presets_changed(s); Ok(json!({"preset": preset})) } fn get(s: &mut Session, p: &Value) -> Result { const CMD: &str = "file.export.presets.get"; let name = req_str(p, "name", CMD)?; - let preset = s.presets.export_presets.iter().find(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; + let preset = s.presets().export_presets.iter().find(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; Ok(json!({"preset": preset})) } fn delete(s: &mut Session, p: &Value) -> Result { const CMD: &str = "file.export.presets.delete"; let name = req_str(p, "name", CMD)?; - let index = s.presets.export_presets.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; - s.presets.export_presets.remove(index); - s.presets_changed(); + let index = s.presets().export_presets.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; + s.presets_mut().export_presets.remove(index); + presets_changed(s); Ok(json!({"deleted": name})) } @@ -210,13 +212,13 @@ fn rename(s: &mut Session, p: &Value) -> Result { const CMD: &str = "file.export.presets.rename"; let name = req_str(p, "name", CMD)?; let new_name = checked_name(req_str(p, "newName", CMD)?).map_err(|e| bad(CMD, e))?; - let index = s.presets.export_presets.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; - if s.presets.export_presets.iter().enumerate().any(|(at, pr)| at != index && pr.name.eq_ignore_ascii_case(&new_name)) { + let index = s.presets().export_presets.iter().position(|pr| pr.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(CMD, "No such export preset"))?; + if s.presets().export_presets.iter().enumerate().any(|(at, pr)| at != index && pr.name.eq_ignore_ascii_case(&new_name)) { return Err(bad(CMD, "Another export preset has that name")); } - s.presets.export_presets[index].name = new_name; - s.presets_changed(); - Ok(json!({"preset": s.presets.export_presets[index]})) + s.presets_mut().export_presets[index].name = new_name; + presets_changed(s); + Ok(json!({"preset": s.presets().export_presets[index]})) } pub fn specs() -> Vec { @@ -228,7 +230,7 @@ pub fn specs() -> Vec { shortcut: None, params: "{}", enabled: always, - run: |s, _| Ok(json!({"presets": s.presets.export_presets})), + run: |s, _| Ok(json!({"presets": s.presets().export_presets})), journal: false, }, CommandSpec { @@ -276,6 +278,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::prefs::SavedPrefsExt; use super::*; fn settings(sizing: &str) -> Value { @@ -303,7 +306,7 @@ mod tests { s.execute("file.export.presets.save", json!({"name": " Web JPEG ", "settings": settings("pixels")})).unwrap(); let again = s.execute("file.export.presets.save", json!({"name": "web jpeg", "settings": settings("scale")})).unwrap(); assert_eq!(again["preset"]["settings"]["sizing"], "scale"); - assert_eq!(s.presets.export_presets.len(), 1, "saving the same name replaces it"); + assert_eq!(s.presets().export_presets.len(), 1, "saving the same name replaces it"); let raw = s.prefs_to_json(); let mut restored = crate::session(); @@ -325,7 +328,7 @@ mod tests { let raw = restored.prefs_to_json(); let mut after = crate::session(); after.load_prefs_json(&raw).unwrap(); - assert!(after.presets.export_presets.is_empty()); + assert!(after.presets().export_presets.is_empty()); } #[test] @@ -334,7 +337,7 @@ mod tests { for name in ["one", "two", "three"] { s.execute("file.export.presets.save", json!({"name": name, "settings": settings("scale")})).unwrap(); } - let names = |s: &Session| s.presets.export_presets.iter().map(|p| p.name.clone()).collect::>(); + let names = |s: &Session| s.presets().export_presets.iter().map(|p| p.name.clone()).collect::>(); s.execute("file.export.presets.rename", json!({"name": "two", "newName": "second"})).unwrap(); assert_eq!(names(&s), ["one", "second", "three"]); assert!(s.execute("file.export.presets.rename", json!({"name": "second", "newName": "THREE"})).is_err()); diff --git a/crates/engine-core/src/cmd/exr_cmds.rs b/crates/engine-core/src/cmd/exr_cmds.rs index 2659f2d4e3..df5a324537 100644 --- a/crates/engine-core/src/cmd/exr_cmds.rs +++ b/crates/engine-core/src/cmd/exr_cmds.rs @@ -3,6 +3,7 @@ //! AOV). The query command feeds the File › Open EXR Parts… dialog, the CLI, MCP and the //! control channel alike. +use crate::color_cmds::ColorExt; use serde_json::{Value, json}; use crate::commands::CommandSpec; diff --git a/crates/engine-core/src/cmd/file_cmds/batch_run.rs b/crates/engine-core/src/cmd/file_cmds/batch_run.rs index a275c5a48d..2645051d83 100644 --- a/crates/engine-core/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine-core/src/cmd/file_cmds/batch_run.rs @@ -1,3 +1,5 @@ +use crate::color_cmds::ColorExt; +use crate::actions_cmds::ActionsExt; use super::open::import_at_raw_ppi; use super::paths::{extension, file_name, join, list_files, list_images, read_file, sanitize, stem, write_file}; use super::processing::parse_steps; @@ -860,7 +862,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // Steps that call another action play it from the caller's actions; the playback stack comes // along so an action that batches itself is caught as a recursive call. let called = match p.get("calledActions") { - None | Some(Value::Null) => s.actions.called.clone(), + None | Some(Value::Null) => s.actions().called.clone(), // A droplet brings the actions it calls (#2794) and plays from those alone. Some(v) => { let actions: Vec = @@ -880,7 +882,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { parse_steps(act)? } else { // The caller selects the source; calledActions supplies only its internal namespace. - let index = batch_action(s.actions.playable().actions(), p)?; + let index = batch_action(s.actions().playable().actions(), p)?; let (_, action, _) = crate::actions_cmds::playback_plan(s, &json!({"action": index}))?; called_name = Some(action.name.clone()); action.enabled_steps().map(|(_, step)| (step.command.clone(), step.params.clone())).collect() @@ -954,7 +956,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } let mut playback_stack = s.recording.playback_stack.clone(); playback_stack.extend(called_name); - let actions = crate::actions_cmds::ActionState { list: s.actions.list.clone(), called, ..Default::default() }; + let actions = crate::actions_cmds::ActionState { list: s.actions().list.clone(), called, ..Default::default() }; let run = crate::ActionRecording { playing: if named { s.recording.playing.saturating_add(1) } else { s.recording.playing }, playback_stack, @@ -983,7 +985,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // The nesting depth and shared budget of the levels above travel with the run too. let previous_shared = std::mem::replace(&mut s.recording.budget_shared, run.budget_shared); let previous_depth = std::mem::replace(&mut s.recording.batch_depth, run.batch_depth); - let previous_called = std::mem::replace(&mut s.actions.called, actions.called); + let previous_called = std::mem::replace(&mut s.actions_mut().called, actions.called); let owns_history = s.action_history.is_none() && s.prefs().actions.create_single_history_state; if owns_history { crate::actions_cmds::begin_document_history(s, &action_name); @@ -996,7 +998,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { s.recording.playback_stack = previous_stack; s.recording.budget_shared = previous_shared; s.recording.batch_depth = previous_depth; - s.actions.called = previous_called; + s.actions_mut().called = previous_called; if previous_playing == 0 && !previous_shared { s.recording.playback_steps = previous_steps; } @@ -1025,7 +1027,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let raw_ppi = super::open::raw_open_resolution(s); let action_prefs = s.prefs().actions.clone(); let prefs = s.prefs.clone(); - let color_settings = s.color.settings.clone(); + let color_settings = s.color().settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); let script_count = s.recording.script_steps; let outputs: Vec<(String, String)> = if save_and_close { @@ -1070,10 +1072,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let _ = check_folder_format; if quiet_profiles || quiet_raw { scratch.prefs = prefs.clone(); - scratch.color.settings = color_settings.clone(); + scratch.color_mut().settings = color_settings.clone(); if quiet_profiles { - scratch.color.settings.ask_on_mismatch = false; - scratch.color.settings.ask_on_missing = false; + scratch.color_mut().settings.ask_on_mismatch = false; + scratch.color_mut().settings.ask_on_missing = false; } scratch.authorize = authorize; if quiet_raw { @@ -1155,7 +1157,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { Ok(()) }; scratch.authorize = authorize; - scratch.actions = actions.clone(); + *scratch.actions_mut() = actions.clone(); scratch.recording = run.clone(); scratch.recording.playback_steps = carried.get(); scratch.recording.script_steps = script_steps.get(); @@ -1459,6 +1461,7 @@ fn preserve_exr(bytes: &[u8]) -> Result<()> { #[cfg(test)] mod action_history_tests { + use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::{Action, ActionStep}; use std::cell::RefCell; @@ -1524,7 +1527,7 @@ mod action_history_tests { } steps.push(ActionStep::new("layer.renameLayer", json!({"name":"Final"}))); let action_steps = if nested { - s.actions.list.push(Action::new("Child", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Child", steps)).unwrap(); vec![ActionStep::new("actions.play", json!({"action":"Child"}))] } else { steps @@ -1535,8 +1538,8 @@ mod action_history_tests { s.execute("file.automate.createDroplet", json!({"path":path,"name":"Named","steps":action_steps,"output":output,"shim":false})).unwrap(); s.execute("file.automate.runDroplet", json!({"droplet":path,"input":paths})).unwrap() } else if named { - let index = s.actions.list.actions().len(); - s.actions.list.push(Action::new("Named", action_steps)).unwrap(); + let index = s.actions().list.actions().len(); + s.actions_mut().list.push(Action::new("Named", action_steps)).unwrap(); s.execute("file.automate.batch", json!({"action":index,"input":paths,"output":output})).unwrap() } else { s.execute("file.automate.batch", json!({"action":"Named","steps":action_steps,"input":paths,"output":output})).unwrap() @@ -1577,13 +1580,13 @@ mod action_history_tests { let before: Vec<_> = s.documents().iter().map(|st| (st.doc.clone(), st.history.past_len())).collect(); let steps = vec![ActionStep::new("layer.renameLayer", json!({"name":"Prefix"})), ActionStep::new("layer.renameLayer", json!({"name":"Final"}))]; let params = if named { - s.actions.list.push(Action::new("Opened batch", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Opened batch", steps)).unwrap(); json!({"source":"open","action":0}) } else { json!({"source":"open","action":"Opened batch","steps":steps}) }; if parent { - s.actions + s.actions_mut() .list .push(Action::new( "Parent", @@ -1630,8 +1633,8 @@ mod action_history_tests { let mut s = crate::session(); s.execute("file.new", json!({"width":4,"height":4})).unwrap(); s.execute("actions.setHistory", json!({"singleState":true})).unwrap(); - s.actions.list.push(Action::new("Original", vec![])).unwrap(); - let library = serde_json::to_value(s.actions.list.actions()).unwrap(); + s.actions_mut().list.push(Action::new("Original", vec![])).unwrap(); + let library = serde_json::to_value(s.actions().list.actions()).unwrap(); let before = s.active().unwrap().doc.clone(); if parent { crate::actions_cmds::begin_document_history(&mut s, "Parent"); @@ -1646,7 +1649,7 @@ mod action_history_tests { ) .unwrap(); assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}"); - assert_eq!(serde_json::to_value(s.actions.list.actions()).unwrap(), library); + assert_eq!(serde_json::to_value(s.actions().list.actions()).unwrap(), library); if parent { assert_eq!(s.action_history.as_ref().unwrap().name, "Parent"); s.execute("layer.renameLayer", json!({"name":"Parent tail"})).unwrap(); diff --git a/crates/engine-core/src/cmd/file_cmds/open.rs b/crates/engine-core/src/cmd/file_cmds/open.rs index 470a58209b..7fc30f22db 100644 --- a/crates/engine-core/src/cmd/file_cmds/open.rs +++ b/crates/engine-core/src/cmd/file_cmds/open.rs @@ -1,3 +1,4 @@ +use crate::color_cmds::ColorExt; use super::paths::{file_name, read_file, stem, template_name}; use super::{Arc, Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, PlaceSteps, Result, Session, Value, json, str_param}; @@ -213,7 +214,7 @@ pub fn open_bytes_as_with_options( path } }; - if raw_settings.is_some() && s.color.open_question(&doc).is_some() { + if raw_settings.is_some() && s.color().open_question(&doc).is_some() { return Err(EngineError::Other(format!("{name}: a color profile question requires interactive opening or suppressWarnings"))); } // Color Settings policies (preserve / convert / discard the embedded profile). diff --git a/crates/engine-core/src/cmd/file_cmds/open_as_smart_object.rs b/crates/engine-core/src/cmd/file_cmds/open_as_smart_object.rs index 7ca92ac1cb..e8b141d7a4 100644 --- a/crates/engine-core/src/cmd/file_cmds/open_as_smart_object.rs +++ b/crates/engine-core/src/cmd/file_cmds/open_as_smart_object.rs @@ -5,6 +5,7 @@ //! size and position `0, 0`) and put into the document before it is admitted, so the opening //! snapshot already shows it. +use crate::color_cmds::ColorExt; use super::open::import_result_for_open; use super::paths::{file_name, read_file, stem, untitled_name}; use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param}; @@ -79,12 +80,12 @@ fn apply( // File › Open's completion: a raw has no embedded profile to ask about; otherwise the profile // prompt holds the document, and without a question the Color Settings policy is applied. let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let question = s.color.open_question(&doc).filter(|_| !raw); + let question = s.color().open_question(&doc).filter(|_| !raw); if damaged || question.is_some() { let held = s.hold_open(doc, false); return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "damaged": damaged, "smartObject": true})); } - let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag); + let color = s.color().open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag); let index = admit_as_smart_object(s, doc); let id = s.documents().get(index).map(|st| st.doc.id.0); // Admission numbers the document again, so the reply reads the name it was admitted under. diff --git a/crates/engine-core/src/cmd/file_cmds/tests.rs b/crates/engine-core/src/cmd/file_cmds/tests.rs index c3f90f9b9e..cf2ea9d96c 100644 --- a/crates/engine-core/src/cmd/file_cmds/tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/tests.rs @@ -1,3 +1,5 @@ +use crate::color_cmds::ColorExt; +use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::{ActionList, ActionStep, ActionsFile}; @@ -24,7 +26,7 @@ fn batch_resolves_action_by_name_and_detects_recursion() { let mut s = crate::session(); let mut action = crate::actions_cmds::Action::new("Scale", vec![ActionStep::new("image.imageSize", json!({"width":16,"height":16}))]); action.set = Some("Ops".into()); - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); let result = s.execute("file.automate.batch", json!({"action":"Scale","set":"Ops","input":[input.clone()],"output":out})).unwrap(); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); for p in [json!({"action":"Nonexistent"}), json!({"action":"Scale","set":"Wrong set"})] { @@ -80,7 +82,7 @@ fn batch_structured_names_keep_image_format_and_refuse_unsupported_save_routing( // One composition witness: Save Actions -> Load Actions -> named Batch -> actual PNG bytes. let mut child = crate::actions_cmds::Action::new("Child", vec![]); child.set = Some("S".into()); - s.actions.list.push(child).unwrap(); + s.actions_mut().list.push(child).unwrap(); let params = json!({"input":dir,"output":output,"action":"Child","set":"S","includeSubfolders":false,"flatOutput":true, "overrideSaveAs":false,"stopOnError":true,"includeNonImages":true,"namingComponents":[{"text":"from-atn"}]}); let driver = crate::actions_cmds::Action::new("Driver", vec![ActionStep::new("file.automate.batch", params)]); @@ -88,7 +90,7 @@ fn batch_structured_names_keep_image_format_and_refuse_unsupported_save_routing( assert!(skipped.is_empty()); let imported = crate::atn_cmds::import(&bytes).unwrap(); assert!(imported.unsupported.is_empty()); - push_all(&mut s.actions.list, imported.actions); + push_all(&mut s.actions_mut().list, imported.actions); s.execute("actions.play", json!({"action":"Driver"})).unwrap(); assert!(std::fs::read(join(&output, "from-atn")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n")); } @@ -123,7 +125,7 @@ fn batch_recorded_stop_for_errors_retains_earlier_outputs_and_stops_before_later assert!(native["errors"].as_array().unwrap().is_empty(), "{native}"); let mut child = crate::actions_cmds::Action::new("Child", vec![]); child.set = Some("S".into()); - s.actions.list.push(child).unwrap(); + s.actions_mut().list.push(child).unwrap(); let output = join(&dir, "recorded"); let p = json!({"input":input,"output":output,"action":"Child","set":"S","stopOnError":true,"includeNonImages":true, "includeSubfolders":false,"overrideSaveAs":false,"flatOutput":true, @@ -135,7 +137,7 @@ fn batch_recorded_stop_for_errors_retains_earlier_outputs_and_stops_before_later assert!(skipped.is_empty()); let imported = crate::atn_cmds::import(&bytes).unwrap(); assert_eq!(imported.actions[0].steps[1].command, "file.new", "the after-Batch sentinel must be replayable"); - push_all(&mut s.actions.list, imported.actions); + push_all(&mut s.actions_mut().list, imported.actions); let result = s.execute("actions.play", json!({"action":"Driver"})).unwrap(); assert_eq!(result["ran"], 0, "{result}"); assert_eq!(result["failed"]["id"], "file.automate.batch"); @@ -222,13 +224,13 @@ fn batch_save_and_close_preserves_caller_and_failed_sources() { vec![ActionStep::new("image.adjustments.invert", json!({})), ActionStep::new("file.saveAs", json!({})), ActionStep::new("file.close", json!({}))], ); child.set = Some("S".into()); - s.actions.list.push(child).unwrap(); + s.actions_mut().list.push(child).unwrap(); let params = json!({"input":dir,"destination":"saveAndClose","action":"Child","set":"S", "includeSubfolders":false,"overrideSaveAs":false,"stopOnError":true,"includeNonImages":true}); let driver = crate::actions_cmds::Action::new("Driver", vec![ActionStep::new("file.automate.batch", params)]); let (bytes, skipped) = crate::atn_cmds::export("S", &[&driver], &[], false).unwrap(); assert!(skipped.is_empty()); - push_all(&mut s.actions.list, crate::atn_cmds::import(&bytes).unwrap().actions); + push_all(&mut s.actions_mut().list, crate::atn_cmds::import(&bytes).unwrap().actions); let result = s.execute("actions.play", json!({"action":"Driver"})).unwrap(); assert_eq!(result["ran"], 1, "{result}"); assert!(result.get("failed").is_none(), "{result}"); @@ -338,8 +340,8 @@ fn batch_override_open_follows_called_conditional_and_script_steps() { let mut s = session(7, 9, 8); let caller = photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap(); let prefs = serde_json::to_value(s.prefs()).unwrap(); - s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", json!({"path":recorded,"as":"png"}))])).unwrap(); - let actions = s.actions.list.to_file().to_json().unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", json!({"path":recorded,"as":"png"}))])).unwrap(); + let actions = s.actions().list.to_file().to_json().unwrap(); let steps = json!([["actions.conditional",{"if":"always","then":"Open"}], ["file.scripts.browse",{"steps":[["file.closeAll",{}],["file.openAs",{"path":recorded,"as":"png"}]]}], ["image.adjustments.invert",{}]]); @@ -349,7 +351,7 @@ fn batch_override_open_follows_called_conditional_and_script_steps() { .execute( "file.automate.batch", json!({"input":[first,second],"output":output,"steps":steps, - "calledActions":s.actions.list.actions(),"overrideOpen":enabled}), + "calledActions":s.actions().list.actions(),"overrideOpen":enabled}), ) .unwrap(); assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); @@ -368,7 +370,7 @@ fn batch_override_open_follows_called_conditional_and_script_steps() { let invalid = join(&dir, "invalid-override"); assert!(s.execute("file.automate.batch", json!({"input":[first],"output":invalid,"steps":[],"overrideOpen":"true"})).is_err()); assert!(!std::path::Path::new(&invalid).exists()); - assert_eq!(s.actions.list.to_file().to_json().unwrap(), actions); + assert_eq!(s.actions().list.to_file().to_json().unwrap(), actions); assert_eq!(serde_json::to_value(s.prefs()).unwrap(), prefs); assert_eq!(photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap(), caller); assert!(s.batch_open.is_none()); @@ -396,7 +398,7 @@ fn batch_override_open_authorizes_effective_path_and_carries_failure_budget() { let existing = png(&output, "b.png", 3, 2, "#4488aa"); let intact = std::fs::read(&existing).unwrap(); let mut s = crate::session(); - s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", json!({"path":"/recorded.png","as":"png"}))])).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", json!({"path":"/recorded.png","as":"png"}))])).unwrap(); s.batch_open = Some(crate::state::BatchOpen { path: first.clone(), sources: Vec::new(), raw_ppi: 300.0, read_only: false }); assert!(matches!(s.execute("file.openAs", json!([1])), Err(EngineError::BadParams { .. }))); assert!(s.documents().is_empty()); @@ -434,7 +436,7 @@ fn batch_override_open_nested_binding_and_save_close_preserve_sources() { let inner = join(&dir, "inner"); let open = json!({"path":"/recorded.png","as":"png"}); let mut s = crate::session(); - s.actions.list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", open.clone())])).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("Open", vec![ActionStep::new("file.openAs", open.clone())])).unwrap(); let steps = json!([["actions.play",{"action":"Open"}], ["file.automate.batch",{"input":[second],"output":inner,"overrideOpen":true,"steps":[["file.openAs",open],["image.adjustments.invert",{}]]}], ["file.closeAll",{}],["file.openAs",open],["image.adjustments.invert",{}]]); @@ -485,8 +487,8 @@ fn batch_quiet_profile_open_uses_caller_policy_and_retains_diagnostics() { let mut s = crate::session(); s.execute("edit.colorSettings", json!({"workingRgb":"srgb","policyRgb":"convert","askOnMismatch":true,"askOnMissing":true})).unwrap(); let prefs = serde_json::to_value(s.prefs()).unwrap(); - let settings = s.color.settings.clone(); - let policy = s.color.open_question(doc(&fixture)).unwrap(); + let settings = s.color().settings.clone(); + let policy = s.color().open_question(doc(&fixture)).unwrap(); assert_eq!(policy["ask"], true); let output = join(&dir, "out"); let result = s.execute("file.automate.batch", json!({"input":[source,bad],"output":output,"suppressWarnings":true,"stopOnError":true,"steps":[]})).unwrap(); @@ -499,7 +501,7 @@ fn batch_quiet_profile_open_uses_caller_policy_and_retains_diagnostics() { assert!(profile.same_colors(craft_cms::Builtin::Srgb.profile())); // A script calling an action with a failing inner Batch still retains both import reports. let inner = join(&dir, "inner"); - s.actions + s.actions_mut() .list .push(crate::actions_cmds::Action::new( "Quiet inner", @@ -518,7 +520,7 @@ fn batch_quiet_profile_open_uses_caller_policy_and_retains_diagnostics() { assert_eq!(notices.len(), 2, "one outer and one inner import, no duplicate: {nested}"); assert!(notices.iter().all(|notice| notice["color"]["action"] == "converted" && notice["color"]["ask"] == false)); assert_eq!(std::fs::read(&source).unwrap(), original); - assert_eq!(s.color.settings, settings); + assert_eq!(s.color().settings, settings); assert_eq!(serde_json::to_value(s.prefs()).unwrap(), prefs); assert!(s.batch_open_notices.is_none()); let invalid = join(&dir, "invalid"); @@ -542,13 +544,13 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { let mut s = crate::session(); s.execute("file.new", json!({"width":8,"height":8})).unwrap(); let nested = |name| ActionStep::new("file.automate.batch", json!({"source":"open","action":name})); - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ crate::actions_cmds::Action::new("Recorder", vec![]), crate::actions_cmds::Action::new("Loop A", vec![nested(if mutual { "Loop B" } else { "Loop A" })]), crate::actions_cmds::Action::new("Loop B", vec![nested("Loop A")]), crate::actions_cmds::Action::new("Leaf", vec![ActionStep::new("actions.play", json!({"action":0}))]), ]); - let definitions = s.actions.list.actions()[1..].to_vec(); + let definitions = s.actions().list.actions()[1..].to_vec(); s.recording.playback_stack = vec!["Enclosing".into()]; s.recording.target = Some((s.journal.len(), 0)); let take = s.recording.take; @@ -560,7 +562,7 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { assert_eq!(s.recording.playback_stack, ["Enclosing"]); assert_eq!(s.recording.target.map(|(_, owner)| owner), Some(0)); assert_eq!(s.recording.take, take); - assert_eq!(&s.actions.list.actions()[1..], definitions.as_slice()); + assert_eq!(&s.actions().list.actions()[1..], definitions.as_slice()); let before = doc(&s).walk().len(); let embedded = vec![crate::actions_cmds::Action::new("Embedded", vec![ActionStep::new("layer.new.layer", json!({"name":"visited"}))])]; let result = batch(&mut s, &json!({"source":"open","action":"Leaf","calledActions":embedded})).unwrap(); @@ -569,7 +571,7 @@ fn named_open_document_batch_keeps_cycle_context_and_live_recorder() { assert_eq!(s.recording.playback_stack, ["Enclosing"]); assert_eq!(s.recording.target.map(|(_, owner)| owner), Some(0)); assert_eq!(s.recording.take, take); - assert_eq!(&s.actions.list.actions()[1..], definitions.as_slice()); + assert_eq!(&s.actions().list.actions()[1..], definitions.as_slice()); } } @@ -591,7 +593,7 @@ fn named_open_document_batch_uses_effective_recorded_parameters() { s.execute("file.new", json!({"width":200,"height":100})).unwrap(); let a = s.execute("layer.new.layer", json!({"name":"A"})).unwrap()["layer"].as_u64().unwrap(); let b = s.execute("layer.new.layer", json!({"name":"B"})).unwrap()["layer"].as_u64().unwrap(); - s.actions + s.actions_mut() .list .push(crate::actions_cmds::Action::new( "Recorded", @@ -670,7 +672,7 @@ fn background_recorded_batch_keeps_opening_and_destination_policies() { let mut s = crate::session(); s.execute("edit.colorSettings", json!({"workingRgb":"srgb","policyRgb":"convert","askOnMismatch":true,"askOnMissing":true})).unwrap(); let prefs = serde_json::to_value(s.prefs()).unwrap(); - let settings = s.color.settings.clone(); + let settings = s.color().settings.clone(); let job = match s .start( "file.automate.batch", @@ -702,7 +704,7 @@ fn background_recorded_batch_keeps_opening_and_destination_policies() { assert!(profile.same_colors(craft_cms::Builtin::Srgb.profile())); assert_eq!(std::fs::read(source).unwrap(), original); assert_eq!(serde_json::to_value(s.prefs()).unwrap(), prefs); - assert_eq!(s.color.settings, settings); + assert_eq!(s.color().settings, settings); assert!(s.documents().is_empty()); } @@ -3091,7 +3093,7 @@ fn named_batch_cycles_stop_before_the_test_ceiling() { if source == "open" { s.execute("file.openAs", json!({"path": input})).unwrap(); } - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ crate::actions_cmds::Action::new("A", vec![first]), crate::actions_cmds::Action::new("B", vec![ActionStep::new("file.automate.batch", params.clone())]), ]); @@ -3125,13 +3127,13 @@ fn named_batch_limits_nesting_and_keeps_the_callers_state() { if source == "open" { s.execute("file.openAs", json!({"path": input})).unwrap(); } - s.actions.list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); + s.actions_mut().list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); s.recording.playing = 16; s.recording.playback_stack = (0..16).map(|i| format!("Parent{i}")).collect(); - let before = (s.actions.clone(), s.recording.clone()); + let before = (s.actions().clone(), s.recording.clone()); let error = s.execute("file.automate.batch", params.clone()).unwrap_err(); assert!(error.to_string().contains("nesting exceeds 16"), "{error}"); - assert_eq!((s.actions.clone(), s.recording.clone()), before); + assert_eq!((s.actions().clone(), s.recording.clone()), before); assert!(!std::path::Path::new(&output).exists()); s.recording.playing = 0; @@ -3152,7 +3154,7 @@ fn named_batch_limits_nesting_and_keeps_the_callers_state() { assert_eq!(s.recording.playing, 0); assert!(s.recording.playback_stack.is_empty()); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[1].steps, vec![ActionStep::new("file.automate.batch", params)]); + assert_eq!(s.actions().list.actions()[1].steps, vec![ActionStep::new("file.automate.batch", params)]); } } @@ -3164,7 +3166,7 @@ fn named_batch_charges_the_existing_budget_across_inputs_and_children() { let input = png(&dir, "red.png", 8, 8, "#ff0000"); let output = join(&dir, "out"); let mut s = crate::session(); - s.actions.list.push(Action::new("Large", vec![ActionStep::new("image.adjustments.invert", json!({})); 100])).unwrap(); + s.actions_mut().list.push(Action::new("Large", vec![ActionStep::new("image.adjustments.invert", json!({})); 100])).unwrap(); let result = s.execute("file.automate.batch", json!({"action": "Large", "input": vec![input.clone(); 1001], "output": output})).unwrap_err(); assert!(result.to_string().contains("step limit"), "{result}"); assert!(!std::path::Path::new(&output).exists()); @@ -3172,13 +3174,13 @@ fn named_batch_charges_the_existing_budget_across_inputs_and_children() { assert!(s.recording.playback_stack.is_empty()); // A finished playback leaves its count behind; a new named Batch starts fresh. - s.actions.list = list_of(vec![Action::new("Empty", Vec::new())]); + s.actions_mut().list = list_of(vec![Action::new("Empty", Vec::new())]); s.recording.playback_steps = MAX_PLAYBACK_STEPS; let result = s.execute("file.automate.batch", json!({"action": "Empty", "input": [input], "output": join(&dir, "fresh")})).unwrap(); assert_eq!(result["errors"], json!([]), "{result}"); assert_eq!(result["files"].as_array().unwrap().len(), 1); - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ Action::new("Outer", vec![ActionStep::new("actions.play", json!({"action": "Leaf"}))]), Action::new("Leaf", vec![ActionStep::new("select.deselect", json!({})); 2]), ]); @@ -3207,14 +3209,14 @@ fn named_batch_allows_nested_work_and_preserves_authorization() { let inner = join(&dir, &format!("inner-{denied}")); let child = json!({"action": "Leaf", "input": [input], "output": inner, "format": "png"}); let mut s = crate::session(); - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ Action::new("Outer", vec![ActionStep::new("file.automate.batch", child)]), Action::new("Leaf", vec![ActionStep::new("image.adjustments.invert", json!({}))]), ]); if denied { s.authorize = Some(deny_invert); } - let before = (s.actions.clone(), s.recording.clone()); + let before = (s.actions().clone(), s.recording.clone()); let result = s.execute("file.automate.batch", json!({"action": "Outer", "input": [input], "output": output, "format": "png"})).unwrap(); if denied { assert_eq!(result["files"], json!([]), "{result}"); @@ -3226,7 +3228,7 @@ fn named_batch_allows_nested_work_and_preserves_authorization() { let saved = photocraft_io::import("red.png", &std::fs::read(join(&inner, "red.png")).unwrap()).unwrap().document; assert_eq!(photocraft_compose::render(&saved, Rect::new(1, 1, 2, 2)).px[0], [0.0, 1.0, 1.0, 1.0]); } - assert_eq!((s.actions.clone(), s.recording.clone()), before); + assert_eq!((s.actions().clone(), s.recording.clone()), before); } } @@ -3244,7 +3246,7 @@ fn nested_batch_errors_stop_actions_but_direct_scripts_keep_results_and_continue assert_eq!(result["errors"].as_array().unwrap().len(), 1); assert_eq!(result["errors"][0].as_object().unwrap().len(), 2, "ordinary errors still contain only file/error"); let steps = vec![ActionStep::new("file.automate.batch", batch), ActionStep::new("file.new", json!({"width": 2, "height": 2}))]; - s.actions.list.push(Action::new("Caller", steps.clone())).unwrap(); + s.actions_mut().list.push(Action::new("Caller", steps.clone())).unwrap(); let result = s.execute("actions.play", json!({"action": "Caller"})).unwrap(); assert_eq!(result["ran"], 0, "{result}"); assert!(result["failed"]["error"].as_str().unwrap().contains("no active document"), "{result}"); @@ -3275,7 +3277,7 @@ fn nested_batch_partial_failures_keep_outputs_and_stop_only_action_parents() { let result = match caller { "batch" => s.execute("file.automate.batch", batch).unwrap(), "action" => { - s.actions.list.push(Action::new("Mixed", steps)).unwrap(); + s.actions_mut().list.push(Action::new("Mixed", steps)).unwrap(); let result = s.execute("actions.play", json!({"action": "Mixed"})).unwrap(); assert_eq!(result["ran"], 0, "{result}"); let error = result["failed"]["error"].as_str().unwrap(); @@ -3312,7 +3314,7 @@ fn successful_nested_batch_allows_later_action_steps() { let input = png(&dir, "red.png", 8, 8, "#ff0000"); let mut s = crate::session(); let batch = json!({"input": [input], "output": join(&dir, "success"), "steps": [], "format": "png"}); - s.actions + s.actions_mut() .list .push(Action::new("Success", vec![ActionStep::new("file.automate.batch", batch), ActionStep::new("file.new", json!({"width": 2, "height": 2}))])) .unwrap(); @@ -4481,7 +4483,7 @@ fn approve_memory_is_neither_journaled_nor_recorded_in_an_action() { assert_eq!((r["approved"].clone(), r["cancelled"].clone()), (json!(false), json!(true))); s.execute("actions.stop", json!({})).unwrap(); assert!(s.journal.iter().all(|(command, _)| command != "file.approveMemory"), "one-shot approval must not become a journal entry: {:?}", s.journal); - let action = s.actions.list.actions().first().expect("the recorded action"); + let action = s.actions().list.actions().first().expect("the recorded action"); assert!(action.steps.iter().all(|step| step.command != "file.approveMemory"), "one-shot approval must not replay from an action: {:?}", action.steps); } @@ -4568,7 +4570,7 @@ fn playback_stops_after_a_cancelled_nested_batch() { REVIEW_CANCEL.with(|slot| *slot.borrow_mut() = Some(ctx.clone())); s.authorize = Some(cancel_at_marker); let batch = json!({"input": [input], "output": join(&dir, "out"), "steps": [["layer.renameLayer", {"name": "Cancel here"}]]}); - s.actions + s.actions_mut() .list .push(crate::actions_cmds::Action::new("Run", vec![ActionStep::new("file.automate.batch", batch), ActionStep::new("layer.new.layer", json!({}))])) .unwrap(); diff --git a/crates/engine-core/src/cmd/gradient_fill_cmds.rs b/crates/engine-core/src/cmd/gradient_fill_cmds.rs index 7a4e036409..2218f3418b 100644 --- a/crates/engine-core/src/cmd/gradient_fill_cmds.rs +++ b/crates/engine-core/src/cmd/gradient_fill_cmds.rs @@ -11,6 +11,7 @@ //! Every edit is one command, so one history step per gesture: the UI previews a drag with //! [`apply_set`] and commits it once on release. +use crate::presets::PresetsExt; use photocraft_color::Color; use photocraft_compose::gradient_fill as gf; use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId}; @@ -123,7 +124,7 @@ fn hex(c: &Color) -> String { /// else the current gradient (Gradients panel); explicit `"transparency"` stops replace its own. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { if let Some(name) = p.get("gradient").and_then(Value::as_str) { - let groups = &s.presets.gradients; + let groups = &s.presets().gradients; return groups .iter() .flat_map(|g| g.items.iter()) @@ -135,7 +136,7 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { if p.get("stops").is_some() { return GradientPreset::from_params("Custom", p, cmd); } - s.presets.gradient.clone().with_transparency(p, cmd) + s.presets().gradient.clone().with_transparency(p, cmd) } /// The fill and frame of gradient fill layer `id`. diff --git a/crates/engine-core/src/cmd/history_options_cmds.rs b/crates/engine-core/src/cmd/history_options_cmds.rs index 034726e4d8..2eb67649bd 100644 --- a/crates/engine-core/src/cmd/history_options_cmds.rs +++ b/crates/engine-core/src/cmd/history_options_cmds.rs @@ -201,6 +201,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::prefs::SavedPrefsExt; use super::*; use serde_json::json; diff --git a/crates/engine-core/src/cmd/layer_copy_cmds.rs b/crates/engine-core/src/cmd/layer_copy_cmds.rs index 40a30f40c8..c08b055858 100644 --- a/crates/engine-core/src/cmd/layer_copy_cmds.rs +++ b/crates/engine-core/src/cmd/layer_copy_cmds.rs @@ -8,6 +8,7 @@ //! document. Pixels are converted to the destination's colour profile (Color Settings' intent and //! black point compensation) and bit depth, as Photoshop converts dragged layers. +use crate::color_cmds::ColorExt; use std::collections::{BTreeSet, HashMap, HashSet}; use photocraft_color::ColorMode; @@ -111,7 +112,7 @@ pub(crate) fn adapt_copies(s: &Session, copies: &mut Document, dest: &Document) } if (copies.mode, &copies.icc_profile) != (dest.mode, &dest.icc_profile) { let profile = crate::color_cmds::document_profile(dest); - crate::color_cmds::convert_document(copies, &profile, s.color.settings.intent(), s.color.settings.bpc)?; + crate::color_cmds::convert_document(copies, &profile, s.color().settings.intent(), s.color().settings.bpc)?; } if copies.depth != dest.depth { crate::image_cmds::for_each_surface(&mut copies.layers, true, &mut |surf, _| { diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tile_damage_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tile_damage_tests.rs index f996083ec4..0802a88dbf 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tile_damage_tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tile_damage_tests.rs @@ -1,6 +1,7 @@ //! #9329 PR A: a pixel change damages only the tiles that changed, and command rects are hints //! checked against them. +use crate::actions_cmds::ActionsExt; use super::*; use photocraft_geom::TILE_SIZE; @@ -536,7 +537,7 @@ fn select_then_edit_in_one_command_is_bounded() { ActionStep::new("edit.fill", json!({"color": "#ff0000"})), ActionStep::new("select.deselect", json!({})), ]; - s.actions.list.push(crate::actions_cmds::Action::new("A", steps)).unwrap(); + s.actions_mut().list.push(crate::actions_cmds::Action::new("A", steps)).unwrap(); let (_, d) = command_damage(&mut s, "actions.play", json!({"action": "A"})); assert!(d.contains(300, 300) && d.contains(349, 339), "{d:?}"); assert!(u64::from(d.width()) * u64::from(d.height()) * 4 < 1024 * 768, "the filled tiles, not the canvas: {d:?}"); diff --git a/crates/engine-core/src/cmd/migrate_cmds.rs b/crates/engine-core/src/cmd/migrate_cmds.rs index ada62282c3..57cf08fbcc 100644 --- a/crates/engine-core/src/cmd/migrate_cmds.rs +++ b/crates/engine-core/src/cmd/migrate_cmds.rs @@ -2,6 +2,8 @@ //! presets file (another install's preferences, or an exported preset library) into the current //! library, appending groups the library doesn't already have (by name). Headless and scriptable. +use crate::presets::PresetsExt; +use crate::presets::presets_changed; use serde_json::{Value, json}; use crate::presets::{Group, PresetState}; @@ -35,7 +37,7 @@ fn migrate(s: &mut Session, p: &Value) -> Result { // Work out what is new against the library as it is, and write the presets only when something // is added: a write through `&mut` moves their revision, and every view that shows them runs again. - let ps: &PresetState = &s.presets; + let ps: &PresetState = s.presets(); let gradients = new_groups(&ps.gradients, groups(&v, "gradients")); let styles = new_groups(&ps.styles, groups(&v, "styles")); let shapes = new_groups(&ps.shapes, groups(&v, "shapes")); @@ -57,13 +59,13 @@ fn migrate(s: &mut Session, p: &Value) -> Result { let (g, st, sh, pt, tp) = (gradients.len(), styles.len(), shapes.len(), pattern_groups.len(), tool_presets.len()); let total = g + st + sh + pt + tp; if total > 0 { - let ps: &mut PresetState = &mut s.presets; + let ps: &mut PresetState = s.presets_mut(); ps.gradients.extend(gradients); ps.styles.extend(styles); ps.shapes.extend(shapes); ps.pattern_groups.extend(pattern_groups); ps.tool_presets.extend(tool_presets); - s.presets_changed(); + presets_changed(s); } let mut counts = serde_json::Map::new(); counts.insert("gradients".into(), json!(g)); @@ -89,13 +91,15 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::prefs::SavedPrefsExt; + use crate::presets::PresetsExt; use super::*; #[test] fn merges_new_groups_only() { let mut s = crate::session(); - let before = s.presets.gradients.len(); - let existing = s.presets.gradients[0].name.clone(); + let before = s.presets().gradients.len(); + let existing = s.presets().gradients[0].name.clone(); // A presets file with one new gradient group and one that already exists. let file = std::env::temp_dir().join(format!("pc-migrate-{}.json", std::process::id())); let data = json!({ @@ -108,21 +112,21 @@ mod tests { }); std::fs::write(&file, serde_json::to_string(&data).unwrap()).unwrap(); let prefs_rev = s.prefs.rev(); - let presets_rev = s.presets.revision(); + let presets_rev = s.presets().revision(); let r = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap(); assert_eq!(r["added"]["gradients"], 1, "only the new group is added"); - assert_eq!(s.presets.gradients.len(), before + 1); - assert!(s.presets.gradients.iter().any(|g| g.name == "My Imported Set")); + assert_eq!(s.presets().gradients.len(), before + 1); + assert!(s.presets().gradients.iter().any(|g| g.name == "My Imported Set")); assert_eq!(s.prefs.rev(), prefs_rev + 1, "migration marks preferences dirty"); - assert_ne!(s.presets.revision(), presets_rev); + assert_ne!(s.presets().revision(), presets_rev); // Idempotent: migrating again adds nothing. let prefs_rev = s.prefs.rev(); - let presets_rev = s.presets.revision(); + let presets_rev = s.presets().revision(); let saved = s.prefs_to_json(); let r2 = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap(); assert_eq!(r2["migrated"], 0); assert_eq!(s.prefs.rev(), prefs_rev, "duplicate groups do not dirty preferences"); - assert_eq!(s.presets.revision(), presets_rev); + assert_eq!(s.presets().revision(), presets_rev); assert_eq!(s.prefs_to_json(), saved); let _ = std::fs::remove_file(file); } @@ -146,11 +150,11 @@ mod tests { } std::fs::write(&file, serde_json::to_string(&data).unwrap()).unwrap(); let prefs_rev = s.prefs.rev(); - let presets_rev = s.presets.revision(); + let presets_rev = s.presets().revision(); let r = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap(); assert_eq!(r["migrated"], 1, "{key}, wrapped={wrapped}"); assert_eq!(s.prefs.rev(), prefs_rev + 1, "{key}, wrapped={wrapped}: preferences must be saved"); - assert_ne!(s.presets.revision(), presets_rev); + assert_ne!(s.presets().revision(), presets_rev); let saved = s.prefs_to_json(); let mut restored = crate::session(); restored.load_prefs_json(&saved).unwrap(); @@ -171,7 +175,7 @@ mod tests { }; // A damaged entry no longer discards the good ones; blank and overlong names are skipped. let mut s = crate::session(); - let before = s.presets.tool_presets.len(); + let before = s.presets().tool_presets.len(); let r = migrate( &mut s, json!({"tool_presets": [ @@ -183,20 +187,20 @@ mod tests { ]}), ); assert_eq!(r["added"]["toolPresets"], 2); - assert_eq!(s.presets.tool_presets.len(), before + 2); - assert!(s.presets.tool_presets.iter().any(|t| t.name == "4x6 print")); - let padded = s.presets.tool_presets.iter().find(|t| t.name == "Padded").expect("trimmed name"); + assert_eq!(s.presets().tool_presets.len(), before + 2); + assert!(s.presets().tool_presets.iter().any(|t| t.name == "4x6 print")); + let padded = s.presets().tool_presets.iter().find(|t| t.name == "Padded").expect("trimmed name"); assert_eq!(padded.options, json!({})); // What was imported survives the next launch. let mut restored = crate::session(); restored.load_prefs_json(&s.prefs_to_json()).unwrap(); - assert_eq!(restored.presets.tool_presets, s.presets.tool_presets); + assert_eq!(restored.presets().tool_presets, s.presets().tool_presets); // The library stays within MAX_PRESETS. let mut s = crate::session(); let many: Vec = (0..MAX_PRESETS + 500).map(|i| json!({"name": format!("p{i}"), "tool": "brush"})).collect(); - let before = s.presets.tool_presets.len(); + let before = s.presets().tool_presets.len(); let r = migrate(&mut s, json!({"tool_presets": many})); - assert_eq!(s.presets.tool_presets.len(), MAX_PRESETS); + assert_eq!(s.presets().tool_presets.len(), MAX_PRESETS); assert_eq!(r["added"]["toolPresets"], MAX_PRESETS - before); let _ = std::fs::remove_file(file); } diff --git a/crates/engine-core/src/cmd/mode_cmds.rs b/crates/engine-core/src/cmd/mode_cmds.rs index 5dbf5841dd..ab39dfc3a7 100644 --- a/crates/engine-core/src/cmd/mode_cmds.rs +++ b/crates/engine-core/src/cmd/mode_cmds.rs @@ -7,6 +7,7 @@ //! inks (`Document::duotone`), which display and flat export render through. Like Photoshop the //! conversions flatten (Indexed, Bitmap) and require a grayscale source (Bitmap, Duotone). +use crate::color_cmds::ColorExt; use craft_cms::{ColorSpace, TransformOptions}; use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind}; use photocraft_algo::transform::{Homography, Interp}; @@ -357,8 +358,8 @@ fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[ // CMYK and Lab flatten through the compositor's sRGB view on the pinned main path. _ => crate::color_cmds::composite_profile(doc), }; - let source = s.color.working(ColorMode::Rgb); - let options = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }; + let source = s.color().working(ColorMode::Rgb); + let options = TransformOptions { intent: s.color().settings.intent(), bpc: s.color().settings.bpc, ..Default::default() }; let transform = craft_cms::transform::cached(&source, &destination, options) .map_err(|e| bad("image.mode.indexedColor", format!("cannot convert matte colour: {e}")))?; let mut output = [0.0; 16]; diff --git a/crates/engine-core/src/cmd/mode_cmds/tests.rs b/crates/engine-core/src/cmd/mode_cmds/tests.rs index 5e5d41bd34..8f52e7eaf4 100644 --- a/crates/engine-core/src/cmd/mode_cmds/tests.rs +++ b/crates/engine-core/src/cmd/mode_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::color_cmds::ColorExt; use super::*; use photocraft_geom::Rect; @@ -374,9 +375,9 @@ fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() { paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] }); let pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0); let profile = doc(&s).icc_profile.clone(); - let source = s.color.working(ColorMode::Rgb); + let source = s.color().working(ColorMode::Rgb); let destination = crate::color_cmds::document_profile(doc(&s)); - let transform = Transform::new(&source, &destination, s.color.settings.intent(), bpc).unwrap(); + let transform = Transform::new(&source, &destination, s.color().settings.intent(), bpc).unwrap(); let mut converted = [0.0; 16]; transform.eval(&color, &mut converted).unwrap(); let expected = [0, 1, 2].map(|i| ((pixel[i] * pixel[3] + converted[i].clamp(0.0, 1.0) * (1.0 - pixel[3])) * 255.0).round() as u8); @@ -1112,7 +1113,7 @@ fn duotone_to_colour_modes_keeps_the_ink_colours() { assert_eq!(d.mode, target, "{ctx}"); let srgb = Builtin::Srgb.profile(); let dst = crate::color_cmds::working_profile(target); - let t = Transform::new(srgb, &dst, s.color.settings.intent(), s.color.settings.bpc).unwrap(); + let t = Transform::new(srgb, &dst, s.color().settings.intent(), s.color().settings.bpc).unwrap(); for x in 0..16 { let got = surf.pixel(x, 1); let want: Vec = if target == ColorMode::Grayscale { diff --git a/crates/engine-core/src/cmd/preset_import_cmds.rs b/crates/engine-core/src/cmd/preset_import_cmds.rs index a312f1efb3..0795ddb883 100644 --- a/crates/engine-core/src/cmd/preset_import_cmds.rs +++ b/crates/engine-core/src/cmd/preset_import_cmds.rs @@ -12,6 +12,9 @@ //! //! [`BrushSettings`]: photocraft_paint::BrushSettings +use crate::presets::presets_changed; +use crate::presets::PresetsExt; +use crate::preset_store::PresetStoreExt; use serde_json::{Value, json}; use crate::commands::CommandSpec; @@ -379,7 +382,7 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { // Same default as the group insertion below and the documented contract (#10640). let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false); let mut taken = - UniqueNames::new_exact(s.presets.gradients.iter().filter(|g| !replace || g.name != group).flat_map(|g| g.items.iter().map(|i| i.name.as_str()))); + UniqueNames::new_exact(s.presets().gradients.iter().filter(|g| !replace || g.name != group).flat_map(|g| g.items.iter().map(|i| i.name.as_str()))); let original_names: Vec = grads.iter().enumerate().map(|(i, g)| if g.name.trim().is_empty() { format!("Gradient {}", i + 1) } else { g.name.trim().to_string() }).collect(); let mut reserved = taken.taken.clone(); @@ -422,7 +425,7 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "the file holds no gradients PhotoCraft can use (noise gradients only)")); } let names: Vec = items.iter().map(|g| g.name.clone()).collect(); - let st = &mut s.presets; + let st = s.presets_mut(); // As with brushes: a new group beside one of the same name unless `replace` (#10640). let group = if replace { st.gradients.retain(|g| g.name != group); @@ -431,7 +434,7 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { free_group(&group, |g| st.gradients.iter().any(|x| x.name == g)) }; st.gradients.push(Group::new(&group, items)); - s.presets_changed(); + presets_changed(s); Ok(json!({"group": group, "imported": names, "count": names.len(), "warnings": warnings})) } @@ -608,17 +611,17 @@ mod tests { assert_eq!(result["imported"], json!(["Duplicate", "Duplicate 2"])); } s.execute("gradient.presets.select", json!({"preset": "Duplicate"})).unwrap(); - let first = s.presets.gradient.clone(); + let first = s.presets().gradient.clone(); s.execute("gradient.presets.select", json!({"preset": "Duplicate 2"})).unwrap(); - assert_ne!(first.stops, s.presets.gradient.stops); - let mut saved = s.presets.to_json(&s); + assert_ne!(first.stops, s.presets().gradient.stops); + let mut saved = s.presets().to_json(&s); let groups = saved["gradients"].as_array_mut().unwrap(); let group = groups.iter_mut().find(|g| g["name"] == "Duplicates").unwrap(); group["items"][1]["name"] = json!("Duplicate"); s.load_presets_json(saved); - let restored = s.presets.gradients.iter().find(|g| g.name == "Duplicates").unwrap(); + let restored = s.presets().gradients.iter().find(|g| g.name == "Duplicates").unwrap(); assert_eq!(restored.items[1].name, "Duplicate 2"); - assert_eq!(s.presets.gradient.name, "Duplicate 2"); + assert_eq!(s.presets().gradient.name, "Duplicate 2"); let result = s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Other", "replace": false})).unwrap(); assert_eq!(result["imported"], json!(["Duplicate 3", "Duplicate 4"])); } @@ -676,7 +679,7 @@ mod tests { assert_eq!(result["imported"], json!(["Foo", "Foo 3", "Foo 2", "FOO"])); for (name, red) in [("Foo", 0.0), ("Foo 3", 0.25), ("Foo 2", 0.5), ("FOO", 0.75)] { s.execute("gradient.presets.select", json!({"preset": name})).unwrap(); - let current = s.presets.gradient.clone(); + let current = s.presets().gradient.clone(); assert_eq!(current.name, name); assert_eq!(current.stops[0].1, crate::presets::gradients::StopColor::Rgb([red, 0.0, 0.0])); } @@ -705,17 +708,17 @@ mod tests { let r = s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap(); assert_eq!(r["imported"], json!(["Ember"])); assert_eq!(r["warnings"].as_array().map(Vec::len), Some(1)); - let g = s.presets.gradients.iter().find(|g| g.name == "Fire").unwrap(); + let g = s.presets().gradients.iter().find(|g| g.name == "Fire").unwrap(); assert_eq!(g.items[0].stops, vec![(0.0, StopColor::Foreground), (1.0, StopColor::Rgb([1.0, 0.0, 0.0]))]); assert_eq!(g.items[0].opacity, vec![(0.0, 1.0), (1.0, 0.0)]); // Re-import adds a group beside it (#10640); with `replace` it replaces the group. - let n = s.presets.gradients.len(); + let n = s.presets().gradients.len(); let r = s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap(); assert_eq!(r["group"], "Fire (2)"); - assert_eq!(s.presets.gradients.len(), n + 1); + assert_eq!(s.presets().gradients.len(), n + 1); s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire", "replace": true})).unwrap(); - assert_eq!(s.presets.gradients.len(), n + 1); - assert_eq!(s.presets.gradients.iter().filter(|g| g.name == "Fire").count(), 1); + assert_eq!(s.presets().gradients.len(), n + 1); + assert_eq!(s.presets().gradients.iter().filter(|g| g.name == "Fire").count(), 1); for p in [json!({}), json!({"data": "@@"}), json!({"data": photocraft_paint::tile::b64_encode(b"8BGR\0\x03")}), json!({"path": "/nope.grd"})] { assert!(s.execute("gradient.presets.importGrd", p.clone()).is_err(), "{p}"); } diff --git a/crates/engine-core/src/cmd/print_cmds.rs b/crates/engine-core/src/cmd/print_cmds.rs index a667b38fd5..56b3271b28 100644 --- a/crates/engine-core/src/cmd/print_cmds.rs +++ b/crates/engine-core/src/cmd/print_cmds.rs @@ -196,14 +196,14 @@ fn keep(kept: &Kept, source: Option<&PrinterSource>, value: T) { /// Lists the printers; called with the spooler lock held. fn list_system_printers(s: &Session) -> Vec { - let list = match stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")) { + let list = match stand_in_printers(s.printer_source(), cfg!(target_arch = "wasm32")) { Some(source) => source(), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); system_printers_now() } }; - keep(&LAST_PRINTERS, s.printer_source.as_ref(), list.clone()); + keep(&LAST_PRINTERS, s.printer_source(), list.clone()); list } @@ -229,14 +229,14 @@ fn stand_in_printers(source: Option<&PrinterSource>, browser: bool) -> Option<&P /// Lists the GDI route's printers; called with the spooler lock held. fn list_rgb_printers(s: &Session) -> RgbPrinters { - let list = match &s.printer_source { + let list = match s.printer_source() { Some(source) => stand_in_rgb_printers(source, cfg!(windows)), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); craft_print::rgb::printers() } }; - keep(&LAST_RGB_PRINTERS, s.printer_source.as_ref(), list.clone()); + keep(&LAST_RGB_PRINTERS, s.printer_source(), list.clone()); list } @@ -264,17 +264,17 @@ pub fn rgb_printers(s: &Session) -> RgbPrinters { /// the same source, or `Unsupported` if that source has no cached list. pub fn rgb_printers_without_waiting(s: &Session) -> RgbPrinters { try_with_spooler(|| list_rgb_printers(s)) - .or_else(|| last(&LAST_RGB_PRINTERS, s.printer_source.as_ref())) + .or_else(|| last(&LAST_RGB_PRINTERS, s.printer_source())) .unwrap_or(Err(craft_print::rgb::PrintError::Unsupported)) } /// Lists printers for the Print dialog. While the system spooler is busy, returns the cached /// list for the same source, or an empty list if that source has no cached list. pub fn printers_without_waiting(s: &mut Session) -> Value { - if stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")).is_none() && system_spooler().is_none() { + if stand_in_printers(s.printer_source(), cfg!(target_arch = "wasm32")).is_none() && system_spooler().is_none() { return system_printers(s, &json!({})).unwrap_or_default(); } - let list = try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS, s.printer_source.as_ref())).unwrap_or_default(); + let list = try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS, s.printer_source())).unwrap_or_default(); printers_answer(list) } @@ -490,7 +490,7 @@ fn cups_spool(job: &PrintJob) -> std::result::Result { /// server and where there is no `lp` (a sandbox). fn system_printers(s: &mut Session, p: &Value) -> Result { let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); - if named.is_none() && (stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")).is_some() || system_spooler().is_some()) { + if named.is_none() && (stand_in_printers(s.printer_source(), cfg!(target_arch = "wasm32")).is_some() || system_spooler().is_some()) { return Ok(printers_answer(system_printer_list(s))); } #[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] @@ -1037,7 +1037,7 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result { let params = p.clone(); let worker_params = params.clone(); let command = cmd.to_string(); - let spooler = s.print_spooler.clone(); + let spooler = s.print_spooler().cloned(); if send && !dry { // Session::execute remains synchronous; the desktop's Session::start snapshots here // and runs PDF composition and the potentially slow driver on a worker. diff --git a/crates/engine-core/src/cmd/print_cmds/tests.rs b/crates/engine-core/src/cmd/print_cmds/tests.rs index 626ab60a63..06fcc3eaf8 100644 --- a/crates/engine-core/src/cmd/print_cmds/tests.rs +++ b/crates/engine-core/src/cmd/print_cmds/tests.rs @@ -345,7 +345,7 @@ fn test_printers() -> PrinterSource { #[test] fn printer_commands_answer_without_a_document_and_reject_bad_settings() { let mut s = crate::session(); - s.printer_source = Some(test_printers()); + *s.printer_source_mut() = Some(test_printers()); let r = s.execute("file.print.printers", json!({})).unwrap(); assert_eq!(r["supported"], cfg!(windows)); let listed = if cfg!(windows) { json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}]) } else { json!([]) }; @@ -805,11 +805,11 @@ fn disabled_printing_never_spools() { #[test] fn printers_lists_the_spooler_destinations_without_a_document() { let mut s = crate::session(); - s.printer_source = Some(test_printers()); + *s.printer_source_mut() = Some(test_printers()); let r = s.execute("file.printers", json!({})).unwrap(); assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}])); assert_eq!(r["default"], "Office"); - s.printer_source = Some(std::sync::Arc::new(Vec::new)); + *s.printer_source_mut() = Some(std::sync::Arc::new(Vec::new)); let r = s.execute("file.printers", json!({})).unwrap(); assert_eq!((r["printers"].clone(), r["default"].clone()), (json!([]), Value::Null)); } @@ -829,7 +829,7 @@ fn printer_listings_enter_the_spooler_one_thread_at_a_time() { let (inside, most, start) = (Arc::clone(&inside), Arc::clone(&most), Arc::clone(&start)); std::thread::spawn(move || { let mut s = crate::session(); - s.printer_source = Some(Arc::new(move || { + *s.printer_source_mut() = Some(Arc::new(move || { let now = inside.fetch_add(1, Ordering::SeqCst) + 1; most.fetch_max(now, Ordering::SeqCst); std::thread::sleep(std::time::Duration::from_millis(5)); @@ -858,7 +858,7 @@ fn a_panic_inside_the_spooler_does_not_block_later_callers() { assert!(panicked.is_err()); assert_eq!(with_spooler(|| 7), 7); let mut s = crate::session(); - s.printer_source = Some(test_printers()); + *s.printer_source_mut() = Some(test_printers()); assert_eq!(s.execute("file.printers", json!({})).unwrap()["default"], "Office"); } @@ -869,7 +869,7 @@ fn a_thread_holding_the_spooler_does_not_wait_for_itself() { let (done, finished) = std::sync::mpsc::channel(); std::thread::spawn(move || { let mut s = crate::session(); - s.printer_source = Some(test_printers()); + *s.printer_source_mut() = Some(test_printers()); // Inside one outer hold, so no other test takes the lock between the calls. let answers = with_spooler(|| { let nested = with_spooler(|| with_spooler(|| 7)); @@ -893,7 +893,7 @@ fn listings_without_waiting_return_the_last_lists_while_the_spooler_is_busy() { let asked = Arc::new(AtomicUsize::new(0)); let counted = Arc::clone(&asked); let mut s = crate::session(); - s.printer_source = Some(Arc::new(move || { + *s.printer_source_mut() = Some(Arc::new(move || { counted.fetch_add(1, Ordering::SeqCst); vec![craft_print::Printer { name: "Office".into(), default: true, two_sided: None, description: String::new() }] })); @@ -903,7 +903,7 @@ fn listings_without_waiting_return_the_last_lists_while_the_spooler_is_busy() { let holder = { let released = Arc::clone(&released); let mut lister = crate::session(); - lister.printer_source = s.printer_source.clone(); + *lister.printer_source_mut() = s.printer_source().cloned(); std::thread::spawn(move || { with_spooler(|| { // Lists this stand-in's printers once with the lock held, so another test's listing @@ -943,7 +943,7 @@ fn uncached_listings_do_not_wait(cache_other: bool) { let asked = Arc::new(AtomicUsize::new(0)); let counted = Arc::clone(&asked); let mut s = crate::session(); - s.printer_source = Some(Arc::new(move || { + *s.printer_source_mut() = Some(Arc::new(move || { counted.fetch_add(1, Ordering::SeqCst); vec![craft_print::Printer { name: "Proofing".into(), default: true, two_sided: None, description: String::new() }] })); @@ -955,7 +955,7 @@ fn uncached_listings_do_not_wait(cache_other: bool) { with_spooler(|| { if cache_other { let mut other = crate::session(); - other.printer_source = Some(test_printers()); + *other.printer_source_mut() = Some(test_printers()); list_system_printers(&other); let _ = list_rgb_printers(&other); } else { @@ -1047,7 +1047,7 @@ fn a_preferred_app_spooler_takes_the_job() { } let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let mut s = session("rgb", 8); - s.print_spooler = Some(recording_spooler(true, &seen)); + *s.print_spooler_mut() = Some(recording_spooler(true, &seen)); let r = s.execute("file.print", json!({"copies": 2, "paper": "a4", "orientation": "landscape"})).unwrap(); assert_eq!((r["sent"].as_bool(), r["backend"].as_str(), r["spooler"].as_str()), (Some(true), Some("test"), Some("queued"))); assert!(r["pdf"].is_null(), "{r}"); @@ -1273,7 +1273,7 @@ mod cups { let e = s.execute("file.print", json!({"printServer": server, "printer": "Office"})).unwrap_err().to_string(); assert!(e.contains("`Office`"), "{e}"); let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - s.print_spooler = Some(recording_spooler(false, &seen)); + *s.print_spooler_mut() = Some(recording_spooler(false, &seen)); let r = s.execute("file.print", json!({"printServer": server})).unwrap(); assert_eq!((r["backend"].as_str(), r["spooler"].as_str()), (Some("test"), Some("queued"))); assert_eq!(seen.lock().unwrap().len(), 1); @@ -1295,7 +1295,7 @@ mod cups { let r = s.execute("file.print", json!({"copies": 2})).unwrap(); assert_eq!((r["sent"].as_bool(), r["backend"].as_str(), r["spooler"].as_str()), (Some(true), Some("ipp"), Some("job 42 on Office"))); let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - s.print_spooler = Some(recording_spooler(false, &seen)); + *s.print_spooler_mut() = Some(recording_spooler(false, &seen)); // The IPP route first, then the app's spooler only when there is no server. let r = s.execute("file.print", json!({})).unwrap(); assert_eq!(r["backend"], "ipp"); diff --git a/crates/engine-core/src/cmd/retouch_cmds.rs b/crates/engine-core/src/cmd/retouch_cmds.rs index ec7cebe56f..de0dd7d6f3 100644 --- a/crates/engine-core/src/cmd/retouch_cmds.rs +++ b/crates/engine-core/src/cmd/retouch_cmds.rs @@ -10,6 +10,7 @@ //! (`poisson`, `inpaint`, `retouch`) and the dab machinery in `photocraft-paint::retouch`; this module //! only parses parameters and wires them together. +use crate::preset_store::PresetStoreExt; use photocraft_algo::inpaint::{self, CompleteParams}; use photocraft_algo::poisson; use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, sponge}; diff --git a/crates/engine-core/src/cmd/retouch_cmds/clone_sampling.rs b/crates/engine-core/src/cmd/retouch_cmds/clone_sampling.rs index e044dfca83..77e8f72fd6 100644 --- a/crates/engine-core/src/cmd/retouch_cmds/clone_sampling.rs +++ b/crates/engine-core/src/cmd/retouch_cmds/clone_sampling.rs @@ -1,4 +1,6 @@ //! Resolve and freeze a clone source without changing the sampled document. +use crate::presets::PresetsExt; +use crate::color_cmds::ColorExt; use std::sync::Arc; use crate::presets::clone_source::uses_slot; @@ -185,7 +187,7 @@ pub(super) fn resolve_preview(s: &Session, p: &Value, map: &crate::presets::clon } fn resolve_source(s: &Session, p: &Value, cmd: &str, source: Option) -> Result { - let slot = s.presets.clone.active(); + let slot = s.presets().clone.active(); let picked = uses_slot(p); if picked && slot.document_closed && source.is_none_or(|d| Some(d.id) == slot.document) { return Err(bad(cmd, crate::presets::clone_source::SOURCE_CLOSED)); @@ -246,6 +248,6 @@ fn color_transform(s: &Session, doc: &Document, which: SampleLayers, cmd: &str) if source.same_bytes(&destination) { return Ok(None); } - let opts = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }; + let opts = TransformOptions { intent: s.color().settings.intent(), bpc: s.color().settings.bpc, ..Default::default() }; craft_cms::transform::cached(&source, &destination, opts).map(Some).map_err(|e| bad(cmd, format!("cannot convert clone source colors: {e}"))) } diff --git a/crates/engine-core/src/cmd/retouch_cmds/clone_source_layer_tests.rs b/crates/engine-core/src/cmd/retouch_cmds/clone_source_layer_tests.rs index ae89424dd2..5cf6e7423e 100644 --- a/crates/engine-core/src/cmd/retouch_cmds/clone_source_layer_tests.rs +++ b/crates/engine-core/src/cmd/retouch_cmds/clone_source_layer_tests.rs @@ -1,3 +1,5 @@ +use crate::presets::PresetsExt; +use crate::color_cmds::ColorExt; use super::*; use crate::presets::clone_source::Mapping; @@ -69,13 +71,13 @@ fn clone_null_source_layer_matches_omission_for_clone_and_heal() { s.execute(cmd, nullable.clone()).unwrap(); assert_eq!(s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().read_region(rect), expected); let before = s.active().unwrap().doc.clone(); - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); for invalid in [json!("bad"), json!(-1), json!(1.5), json!(true), json!([]), json!(u64::MAX)] { nullable["sourceLayer"] = invalid; assert!(LiveRetouch::begin(&s, cmd, &nullable).is_err()); assert!(s.execute(cmd, nullable.clone()).is_err()); assert_eq!(s.active().unwrap().doc, before); - assert_eq!(s.presets.clone, slots); + assert_eq!(s.presets().clone, slots); } } } @@ -93,24 +95,24 @@ fn clone_null_document_matches_omission_for_source_and_slot_edits() { let active = s.active().unwrap().doc.id; let before = s.active().unwrap().doc.clone(); for mut p in [json!({"width": 150}), json!({"offset": [-20, -10], "anchor": [40, 30]}), json!({"source": [8, 12]})] { - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); let expected = s.execute("cloneSource.set", p.clone()).unwrap(); - let expected_slots = s.presets.clone.clone(); - s.presets.clone = slots; + let expected_slots = s.presets().clone.clone(); + s.presets_mut().clone = slots; p["document"] = Value::Null; assert_eq!(s.execute("cloneSource.set", p.clone()).unwrap(), expected); - assert_eq!(s.presets.clone, expected_slots); - assert_eq!(s.presets.clone.active().document, Some(if p.get("source").is_some() { active } else { original })); + assert_eq!(s.presets().clone, expected_slots); + assert_eq!(s.presets().clone.active().document, Some(if p.get("source").is_some() { active } else { original })); assert_eq!(s.active().unwrap().doc, before, "source edits do not paint"); } - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); for invalid in [json!("bad"), json!(-1), json!(1.5), json!(true), json!([]), json!(u64::MAX)] { assert!(s.execute("cloneSource.set", json!({"source": [20, 20], "document": invalid})).is_err()); - assert_eq!(s.presets.clone, slots); + assert_eq!(s.presets().clone, slots); assert_eq!(s.active().unwrap().doc, before); } assert!(s.execute("cloneSource.set", json!({"document": 0, "width": 200})).is_err(), "an explicit document still requires a source"); - assert_eq!(s.presets.clone, slots); + assert_eq!(s.presets().clone, slots); } } @@ -288,7 +290,7 @@ fn clone_cross_document_matching_color_modes_and_profiles_use_cms() { let transform = craft_cms::transform::cached( &from_profile, &to_profile, - TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }, + TransformOptions { intent: s.color().settings.intent(), bpc: s.color().settings.bpc, ..Default::default() }, ) .unwrap(); transform.eval(&native, &mut want).unwrap(); @@ -311,7 +313,7 @@ fn clone_and_heal_cross_document_mode_compatibility_matches_preview_live_and_com let (mut s, _, _) = setup(16, from); s.execute("file.new", json!({"width": 64, "height": 64, "mode": to, "depth": 16})).unwrap(); let before = s.active().unwrap().doc.clone(); - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); let allowed = from == to || (cmd == "paint.healingBrush" && (from == "gray" || to == "gray")); let p = json!({"points": [[48,48]], "size": 8, "hardness": 100}); let (map, _) = crate::presets::clone_source::resolve(&s, &p, (48.0, 48.0), cmd).unwrap(); @@ -319,12 +321,12 @@ fn clone_and_heal_cross_document_mode_compatibility_matches_preview_live_and_com let preview = if cmd == "paint.healingBrush" { healing_preview(&s, rect, &map, "current") } else { clone_preview(&s, rect, &map, "current") }; assert_eq!(preview.is_ok(), allowed, "preview: {from} -> {to}, {cmd}: {preview:?}"); assert_eq!(LiveRetouch::begin(&s, cmd, &p).is_ok(), allowed, "live: {from} -> {to}, {cmd}"); - assert_eq!(s.presets.clone, slots, "preview and live construction are read-only"); + assert_eq!(s.presets().clone, slots, "preview and live construction are read-only"); let result = s.execute(cmd, p); assert_eq!(result.is_ok(), allowed, "commit: {from} -> {to}, {cmd}: {result:?}"); if !allowed { assert_eq!(s.active().unwrap().doc, before); - assert_eq!(s.presets.clone, slots); + assert_eq!(s.presets().clone, slots); } } } @@ -354,10 +356,10 @@ fn clone_closed_source_document_and_stale_live_pixels_fail_gracefully() { assert!((updated[3] - 0.2).abs() < 0.01); s.close(0).unwrap(); let revision = s.active().unwrap().revision; - let anchor = s.presets.clone.active().anchor; + let anchor = s.presets().clone.active().anchor; assert!(s.execute("paint.cloneStamp", p).is_err()); assert_eq!(s.active().unwrap().revision, revision); - assert_eq!(s.presets.clone.active().anchor, anchor); + assert_eq!(s.presets().clone.active().anchor, anchor); for value in [json!(-1), json!("bad"), json!(999999)] { assert!(s.execute("cloneSource.set", json!({"source": [8,8], "document": value})).is_err()); } @@ -397,7 +399,7 @@ fn clone_source_document_json_and_legacy_slots_are_compatible() { s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); let slot = s.execute("cloneSource.set", json!({"source": [8,8], "document": 0})).unwrap(); assert_eq!(slot["document"], 0); - let mut legacy = serde_json::to_value(s.presets.clone.active()).unwrap(); + let mut legacy = serde_json::to_value(s.presets().clone.active()).unwrap(); legacy.as_object_mut().unwrap().remove("document"); let old: crate::presets::clone_source::CloneSource = serde_json::from_value(legacy).unwrap(); assert!(old.document.is_none()); @@ -422,8 +424,8 @@ fn clone_source_replies_keep_document_identity_when_resetting_transforms() { assert_eq!(reply["documentId"], json!(document_id)); assert_eq!(reply["source"], json!([8.0, 8.0])); } - assert_eq!(s.presets.clone.active().scale, [100.0, 100.0]); - assert_eq!(s.presets.clone.active().rotation, 0.0); + assert_eq!(s.presets().clone.active().scale, [100.0, 100.0]); + assert_eq!(s.presets().clone.active().rotation, 0.0); s.close(0).unwrap(); let reset = s.execute("cloneSource.resetTransform", json!({"index": 2})).unwrap(); assert_eq!(reset["document"], 0, "closing an earlier tab changes the index, not the source identity"); @@ -611,8 +613,8 @@ fn clone_offsets_report_each_unaligned_stroke_without_persisting_its_alignment() assert_eq!(pixel(&s, target, x, y), want, "each unaligned stroke restarts at the sample"); let listed = s.execute("cloneSource.list", json!({})).unwrap(); assert_eq!(listed["sources"][0]["offset"], json!([16.0 - x as f64, 16.0 - y as f64])); - assert!(s.presets.clone.active().anchor.is_none(), "reporting an offset must not establish aligned sampling"); - assert_eq!(s.presets.clone.active().source, Some([16.0, 16.0])); + assert!(s.presets().clone.active().anchor.is_none(), "reporting an offset must not establish aligned sampling"); + assert_eq!(s.presets().clone.active().source, Some([16.0, 16.0])); } } } @@ -627,14 +629,14 @@ fn clone_offsets_follow_mode_toggles_and_manual_edits_use_the_reported_pairing() }; stamp(&mut s, 40, 30, true); stamp(&mut s, 50, 40, false); - assert_eq!(s.presets.clone.active().anchor, Some([40.0, 30.0])); + assert_eq!(s.presets().clone.active().anchor, Some([40.0, 30.0])); assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["offset"], json!([-34.0, -24.0])); stamp(&mut s, 52, 42, true); assert_eq!(pixel(&s, target, 52, 42), pixel(&s, source, 28, 28), "switching back retains the aligned pairing"); stamp(&mut s, 50, 40, false); s.execute("cloneSource.set", json!({"offset": [-30,-20]})).unwrap(); - assert_eq!(s.presets.clone.active().source, Some([20.0, 20.0]), "editing the displayed offset uses its actual destination reference"); - assert_eq!(s.presets.clone.active().anchor, Some([50.0, 40.0])); + assert_eq!(s.presets().clone.active().source, Some([20.0, 20.0]), "editing the displayed offset uses its actual destination reference"); + assert_eq!(s.presets().clone.active().anchor, Some([50.0, 40.0])); stamp(&mut s, 54, 44, false); assert_eq!(pixel(&s, target, 54, 44), pixel(&s, source, 20, 20)); stamp(&mut s, 54, 44, true); @@ -657,9 +659,9 @@ fn clone_offsets_accept_a_preview_reference_and_reject_invalid_points_atomically json!({"source": [20,20], "offset": ["bad",0]}), json!({"source": [20,20], "anchor": [999999,999999], "offset": [10,20]}), ] { - let before = s.presets.clone.clone(); + let before = s.presets().clone.clone(); assert!(s.execute("cloneSource.set", p).is_err()); - assert_eq!(s.presets.clone, before, "a rejected edit leaves all source slots unchanged"); + assert_eq!(s.presets().clone, before, "a rejected edit leaves all source slots unchanged"); } } @@ -669,16 +671,16 @@ fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sourc for cmd in ["paint.cloneStamp", "paint.healingBrush"] { let (mut s, _, target) = setup(8, "rgb"); let p = json!({"points": [[40,30]], "size": 8, "hardness": 100}); - let before = s.presets.clone.clone(); + let before = s.presets().clone.clone(); let _live = LiveRetouch::begin(&s, cmd, &p).unwrap(); - assert_eq!(s.presets.clone, before, "a live preview is read-only"); + assert_eq!(s.presets().clone, before, "a live preview is read-only"); s.edit("lock target", |doc, _| { doc.layer_mut(target).unwrap().locks.all = true; Ok(()) }) .unwrap(); assert!(s.execute(cmd, p.clone()).is_err()); - assert_eq!(s.presets.clone, before, "failed painting cannot anchor or report a successful pairing"); + assert_eq!(s.presets().clone, before, "failed painting cannot anchor or report a successful pairing"); s.edit("unlock target", |doc, _| { doc.layer_mut(target).unwrap().locks.all = false; Ok(()) @@ -687,12 +689,12 @@ fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sourc let mut explicit = p.clone(); explicit["offset"] = json!([-20, -10]); s.execute(cmd, explicit).unwrap(); - assert_eq!(s.presets.clone, before, "an explicit command source does not overwrite the picked slot"); + assert_eq!(s.presets().clone, before, "an explicit command source does not overwrite the picked slot"); let mut unaligned = p; unaligned["aligned"] = json!(false); s.execute(cmd, unaligned).unwrap(); assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["offset"], json!([-24.0, -14.0])); - assert!(s.presets.clone.active().anchor.is_none()); + assert!(s.presets().clone.active().anchor.is_none()); } } @@ -701,7 +703,7 @@ fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sourc fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repicked() { let (mut s, source, _) = setup(16, "rgb"); s.execute("paint.cloneStamp", json!({"points": [[40,30]], "size": 8, "hardness": 100})).unwrap(); - let mut old = serde_json::to_value(s.presets.clone.active()).unwrap(); + let mut old = serde_json::to_value(s.presets().clone.active()).unwrap(); old.as_object_mut().unwrap().remove("last_anchor"); let restored: crate::presets::clone_source::CloneSource = serde_json::from_value(old).unwrap(); assert_eq!(restored.offset(), Some([-24.0, -14.0])); @@ -710,12 +712,12 @@ fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repick assert!(picked["anchor"].is_null()); assert!(picked["lastAnchor"].is_null()); s.execute("cloneSource.set", json!({"source": null, "offset": null, "anchor": null, "index": null, "width": 150})).unwrap(); - assert_eq!(s.presets.clone.active().source, Some([20.0, 20.0]), "null optional coordinates remain omitted for compatibility"); + assert_eq!(s.presets().clone.active().source, Some([20.0, 20.0]), "null optional coordinates remain omitted for compatibility"); for value in [json!(u64::MAX), json!(-1), json!("bad")] { assert!(s.execute("cloneSource.set", json!({"index": value})).is_err()); assert!(s.execute("cloneSource.select", json!({"index": value})).is_err()); } - s.presets.clone.active = usize::MAX; + s.presets_mut().clone.active = usize::MAX; assert!( matches!(s.execute("cloneSource.set", json!({})), Err(EngineError::BadParams { .. })), "corrupt saved selection must be a parameter error, not an internal panic" @@ -728,12 +730,12 @@ fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repick fn clone_offsets_scaled_source_reads_are_bounded_before_allocation() { for cmd in ["paint.cloneStamp", "paint.healingBrush"] { let (mut s, _, _) = setup(8, "rgb"); - let before = s.presets.clone.clone(); + let before = s.presets().clone.clone(); let document = s.active().unwrap().doc.clone(); let result = s.execute(cmd, json!({"points": [[32,32]], "scale": [0.00001,0.00001], "size": 8, "hardness": 100})); assert!(result.is_err(), "a small dab cannot allocate an unbounded transformed source"); assert_eq!(s.active().unwrap().doc, document); - assert_eq!(s.presets.clone, before); + assert_eq!(s.presets().clone, before); } } diff --git a/crates/engine-core/src/cmd/retouch_cmds/tests.rs b/crates/engine-core/src/cmd/retouch_cmds/tests.rs index d1291be463..c2dc75dff8 100644 --- a/crates/engine-core/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine-core/src/cmd/retouch_cmds/tests.rs @@ -1,3 +1,4 @@ +use crate::presets::PresetsExt; use super::*; use photocraft_color::ColorMode; @@ -224,7 +225,7 @@ fn clone_preview_matches_source_without_mutating_session() { paint_layer(&mut s, |x, y| [x as f32 / 32.0, y as f32 / 32.0, 0.25, 1.0]); s.execute("cloneSource.set", json!({"source": [8,8]})).unwrap(); let revision = s.active().unwrap().revision; - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); let map = Mapping { source: (8.0, 8.0), anchor: (20.0, 20.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; let buf = clone_preview(&s, Rect::new(20, 20, 21, 21), &map, "current").unwrap(); let expected = rgba(&s, 8, 8); @@ -232,7 +233,7 @@ fn clone_preview_matches_source_without_mutating_session() { assert!((actual - expected).abs() < 0.001); } assert_eq!(s.active().unwrap().revision, revision); - assert_eq!(s.presets.clone, slots); + assert_eq!(s.presets().clone, slots); assert!(clone_preview(&s, Rect::new(0, 0, 2048, 2048), &map, "current").is_err()); assert!(clone_preview(&s, Rect::new(20, 20, 21, 21), &map, "invalid").is_err()); let invalid = Mapping { source: (f64::NAN, 0.0), ..map }; @@ -3232,9 +3233,9 @@ fn clone_preview_reads_another_document() { let map = Mapping { source: (10.0, 12.0), anchor: (30.0, 30.0), m: [1.0, 0.0, 0.0, 1.0], document: Some(source) }; // The public preview API's explicit mapping remains independent of the selected slot. s.execute("cloneSource.select", json!({"index": 1})).unwrap(); - let slots = s.presets.clone.clone(); + let slots = s.presets().clone.clone(); let buf = clone_preview(&s, Rect::new(30, 30, 31, 31), &map, "current").unwrap(); - assert_eq!(s.presets.clone, slots, "preview never changes the selected slot"); + assert_eq!(s.presets().clone, slots, "preview never changes the selected slot"); let want = doc_rgba(&s, 0, 10, 12); for (a, b) in buf.px[0].iter().zip(want) { assert!((a - b).abs() < 0.01, "{:?} vs {want:?}", buf.px[0]); @@ -3252,7 +3253,7 @@ fn clone_source_document_closed_or_invalid_is_an_error() { assert!(LiveRetouch::begin(&s, cmd, &json!({"points": [[20, 20]], "size": 4})).is_err()); } assert_eq!(s.active().unwrap().doc, before, "nothing painted"); - assert_eq!(s.presets.clone.active().anchor, None, "a refused stroke pairs nothing"); + assert_eq!(s.presets().clone.active().anchor, None, "a refused stroke pairs nothing"); assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["document"], Value::Null); // Explicit `source`/`offset` params sample the painted document, whatever the slot says. s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "offset": [4, 0], "size": 4})).unwrap(); @@ -3304,7 +3305,7 @@ fn clone_source_set_names_the_source_document() { ] { assert!(s.execute("cloneSource.set", bad.clone()).is_err(), "{bad}"); } - assert_eq!(s.presets.clone.active().source, Some([10.0, 12.0]), "a refused call changes nothing"); + assert_eq!(s.presets().clone.active().source, Some([10.0, 12.0]), "a refused call changes nothing"); } // --------------------------------------------------------------------------------------------- diff --git a/crates/engine-core/src/cmd/selection_cmds.rs b/crates/engine-core/src/cmd/selection_cmds.rs index 79477abbe6..895db32a14 100644 --- a/crates/engine-core/src/cmd/selection_cmds.rs +++ b/crates/engine-core/src/cmd/selection_cmds.rs @@ -2,6 +2,7 @@ //! (expand/contract/border/smooth/feather), Grow, Similar, Lasso. //! Selections are grayscale coverage surfaces clipped to the canvas. +use crate::color_cmds::ColorExt; use photocraft_algo::selection::{self as sel, SelectionMode}; use photocraft_doc::Document; use photocraft_geom::Rect; @@ -426,7 +427,7 @@ fn color_range(s: &mut Session, p: &Value) -> Result { // Pixels the current proof setup (View › Proof Setup) can't reproduce, as the gamut // warning shows them: judged on the composite. let d = s.active().ok_or(EngineError::NoDocument)?; - let pv = s.color.proof(d.doc.id); + let pv = s.color().proof(d.doc.id); let (m, _) = crate::color_cmds::gamut_mask(&d.doc, &pv.setup, pv.gamut_threshold)?; (d.doc.bounds(), m.iter().map(|v| f32::from(*v) / 255.0).collect()) } diff --git a/crates/engine-core/src/cmd/smart_cmds/unpack.rs b/crates/engine-core/src/cmd/smart_cmds/unpack.rs index d821e1fedd..a0bc6c2e73 100644 --- a/crates/engine-core/src/cmd/smart_cmds/unpack.rs +++ b/crates/engine-core/src/cmd/smart_cmds/unpack.rs @@ -4,6 +4,7 @@ //! smart object directly when those fold into it without changing the look. Smart filters are //! discarded (the result reports how many). +use crate::color_cmds::ColorExt; use std::sync::Arc; use craft_cms::Intent; @@ -176,7 +177,7 @@ fn unpacked(so: &Layer, mut layers: Vec) -> Layer { pub(super) fn convert_to_layers(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, p)?; - let (intent, bpc) = (s.color.settings.intent(), s.color.settings.bpc); + let (intent, bpc) = (s.color().settings.intent(), s.color().settings.bpc); let st = s.active().ok_or(EngineError::NoDocument)?; let doc = &st.doc; let so = doc.layer(id).ok_or(EngineError::NoLayer(id))?; diff --git a/crates/engine-core/src/cmd/smartselect_cmds.rs b/crates/engine-core/src/cmd/smartselect_cmds.rs index 4210933217..d6bf4d2c6b 100644 --- a/crates/engine-core/src/cmd/smartselect_cmds.rs +++ b/crates/engine-core/src/cmd/smartselect_cmds.rs @@ -564,13 +564,13 @@ fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result Some(r), None => { let doc = std::sync::Arc::clone(&d.doc); let found = find_object(&doc, d.active_layer, all_layers, x, y).map(std::sync::Arc::new); if let Some(r) = &found { - s.object_finder.insert(&doc, target, std::sync::Arc::clone(r)); + s.object_finder_mut().insert(&doc, target, std::sync::Arc::clone(r)); } found } @@ -580,7 +580,7 @@ fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result std::result::Result<(), String> { } fn has_styles(s: &Session) -> std::result::Result<(), String> { - if s.presets.styles.iter().any(|g| !g.items.is_empty()) { Ok(()) } else { Err("no styles".into()) } + if s.presets().styles.iter().any(|g| !g.items.is_empty()) { Ok(()) } else { Err("no styles".into()) } } const IMPORT: &str = "style.presets.importAsl"; @@ -57,7 +59,7 @@ fn import(s: &mut Session, p: &Value) -> Result { pattern_ids.push(pat.id.clone()); s.patterns.upsert(pat); } - let styles = &mut s.presets.styles; + let styles = &mut s.presets_mut().styles; if replace { styles.retain(|g| g.name != group); } @@ -78,7 +80,7 @@ fn import(s: &mut Session, p: &Value) -> Result { g.items.push(preset); } } - s.presets_changed(); + presets_changed(s); Ok(json!({"group": group, "imported": names, "count": names.len(), "patterns": pattern_ids, "warnings": imp.warnings})) } @@ -93,14 +95,14 @@ fn export(s: &mut Session, p: &Value) -> Result { list.iter() .map(|n| { let name = n.as_str().ok_or_else(|| bad(EXPORT, "`styles` must be a list of style names"))?; - let (gi, ii) = find(&s.presets.styles, name, group).ok_or_else(|| bad(EXPORT, format!("no style \"{name}\" (see style.presets.list)")))?; - s.presets.styles.get(gi).and_then(|g| g.items.get(ii)).cloned().ok_or_else(|| bad(EXPORT, format!("no style \"{name}\""))) + let (gi, ii) = find(&s.presets().styles, name, group).ok_or_else(|| bad(EXPORT, format!("no style \"{name}\" (see style.presets.list)")))?; + s.presets().styles.get(gi).and_then(|g| g.items.get(ii)).cloned().ok_or_else(|| bad(EXPORT, format!("no style \"{name}\""))) }) .collect::>()? } None => match group { - Some(g) => s.presets.styles.iter().find(|x| x.name == g).ok_or_else(|| bad(EXPORT, format!("no style group \"{g}\"")))?.items.clone(), - None => s.presets.styles.iter().flat_map(|g| g.items.iter().cloned()).collect(), + Some(g) => s.presets().styles.iter().find(|x| x.name == g).ok_or_else(|| bad(EXPORT, format!("no style group \"{g}\"")))?.items.clone(), + None => s.presets().styles.iter().flat_map(|g| g.items.iter().cloned()).collect(), }, }; if chosen.is_empty() { @@ -176,14 +178,14 @@ mod tests { #[test] fn export_then_import_round_trips_a_group() { let mut s = session(); - let before = s.presets.styles.clone(); + let before = s.presets().styles.clone(); let r = s.execute(EXPORT, json!({"group": "Text Effects"})).unwrap(); let n = before.iter().find(|g| g.name == "Text Effects").unwrap().items.len(); assert_eq!(r["count"], n); let data = r["data"].as_str().unwrap().to_string(); let r = s.execute(IMPORT, json!({"data": data, "group": "Back"})).unwrap(); assert_eq!(r["count"], n); - let back = s.presets.styles.iter().find(|g| g.name == "Back").unwrap().items.clone(); + let back = s.presets().styles.iter().find(|g| g.name == "Back").unwrap().items.clone(); let orig = &before.iter().find(|g| g.name == "Text Effects").unwrap().items; for (a, b) in back.iter().zip(orig) { // Names stay unique across the library: "Gold" comes back as "Gold 2". @@ -196,23 +198,23 @@ mod tests { let fx = &s.active().unwrap().doc.layers.last().unwrap().effects.items; assert_eq!(fx.len(), orig[0].effects.len()); // Re-import replaces the group instead of adding another. - let groups = s.presets.styles.len(); + let groups = s.presets().styles.len(); s.execute(IMPORT, json!({"data": data, "group": "Back"})).unwrap(); - assert_eq!(s.presets.styles.len(), groups); + assert_eq!(s.presets().styles.len(), groups); } #[test] fn a_file_named_like_a_built_in_group_keeps_that_group() { let mut s = session(); - let basics = s.presets.styles.iter().find(|g| g.name == "Basics").unwrap().items.clone(); + let basics = s.presets().styles.iter().find(|g| g.name == "Basics").unwrap().items.clone(); let data = s.execute(EXPORT, json!({"group": "Text Effects"})).unwrap()["data"].as_str().unwrap().to_string(); for _ in 0..2 { let r = s.execute(IMPORT, json!({"data": data, "group": "Basics"})).unwrap(); assert_eq!(r["group"], "Basics 2"); } - assert_eq!(s.presets.styles.iter().find(|g| g.name == "Basics").unwrap().items, basics); + assert_eq!(s.presets().styles.iter().find(|g| g.name == "Basics").unwrap().items, basics); // Re-importing replaces the copy instead of adding another. - assert_eq!(s.presets.styles.iter().filter(|g| g.name.starts_with("Basics")).count(), 2); + assert_eq!(s.presets().styles.iter().filter(|g| g.name.starts_with("Basics")).count(), 2); } #[test] @@ -225,7 +227,7 @@ mod tests { s.execute("style.presets.new", json!({"name": "Blended", "group": "Mine", "layer": id.0})).unwrap(); let data = s.execute(EXPORT, json!({"styles": ["Blended"]})).unwrap()["data"].as_str().unwrap().to_string(); s.execute(IMPORT, json!({"data": data, "group": "Again"})).unwrap(); - let st = s.presets.styles.iter().find(|g| g.name == "Again").unwrap().items[0].clone(); + let st = s.presets().styles.iter().find(|g| g.name == "Again").unwrap().items[0].clone(); assert_eq!(st.blend, Some(l.blend)); assert!((st.opacity.unwrap() - l.opacity).abs() < 1e-4); assert!((st.fill_opacity.unwrap() - l.fill_opacity).abs() < 1e-4); @@ -303,7 +305,7 @@ mod tests { let mut s = session(); let good = s.execute(EXPORT, json!({"group": "Basics"})).unwrap()["data"].as_str().unwrap().to_string(); let raw = b64_decode(&good).unwrap(); - let styles = s.presets.styles.clone(); + let styles = s.presets().styles.clone(); let pats = s.patterns.items.len(); let empty = b64_encode(&asl_map::write_asl(&[], &[]).unwrap()); for p in [ @@ -322,7 +324,7 @@ mod tests { ] { assert!(s.execute(IMPORT, p.clone()).is_err(), "{p}"); } - assert_eq!(s.presets.styles, styles); + assert_eq!(s.presets().styles, styles); assert_eq!(s.patterns.items.len(), pats); for p in [ json!({"group": "No Such Group"}), @@ -336,7 +338,7 @@ mod tests { ] { assert!(s.execute(EXPORT, p.clone()).is_err(), "{p}"); } - s.presets.styles.clear(); + s.presets_mut().styles.clear(); assert!(s.execute(EXPORT, json!({})).is_err()); } } diff --git a/crates/engine-core/src/cmd/swatch_cmds.rs b/crates/engine-core/src/cmd/swatch_cmds.rs index 3508bcf850..ec8d9596c4 100644 --- a/crates/engine-core/src/cmd/swatch_cmds.rs +++ b/crates/engine-core/src/cmd/swatch_cmds.rs @@ -9,6 +9,8 @@ //! across all groups, in panel order). Like the other preset commands they change the //! preferences document, not a document's history. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use craft::color_ui::palette::{SwatchFormat, SwatchNote, default_swatches, read_swatches, write_swatches}; use serde_json::{Value, json}; @@ -51,11 +53,11 @@ fn always(_: &Session) -> std::result::Result<(), String> { } fn has_swatches(s: &Session) -> std::result::Result<(), String> { - if total(&s.presets.swatches) > 0 { Ok(()) } else { Err("the Swatches panel is empty".into()) } + if total(&s.presets().swatches) > 0 { Ok(()) } else { Err("the Swatches panel is empty".into()) } } fn has_groups(s: &Session) -> std::result::Result<(), String> { - if s.presets.swatches.is_empty() { Err("there are no swatch groups".into()) } else { Ok(()) } + if s.presets().swatches.is_empty() { Err("there are no swatch groups".into()) } else { Ok(()) } } fn name_param(p: &Value, k: &str, cmd: &str) -> Result> { @@ -83,7 +85,7 @@ fn unique_group(groups: &[SwatchGroup], base: &str) -> String { /// The swatch a command names: `"swatch"` (name, narrowed by `"group"`) or `"index"`. fn locate(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> { - let groups = &s.presets.swatches; + let groups = &s.presets().swatches; if let Some(name) = str_param(p, "swatch") { return locate_swatch(groups, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no swatch \"{name}\" (see swatches.list)"))); } @@ -114,7 +116,7 @@ fn index_by_name<'a>(groups: &'a [SwatchGroup], group: Option<&str>) -> std::col } fn group_of(s: &Session, name: &str, cmd: &str) -> Result { - s.presets.swatches.iter().position(|g| g.name == name).ok_or_else(|| bad(cmd, format!("no swatch group \"{name}\""))) + s.presets().swatches.iter().position(|g| g.name == name).ok_or_else(|| bad(cmd, format!("no swatch group \"{name}\""))) } fn swatch_json(conv: &SwatchConv, sw: &SwatchEntry) -> Value { @@ -132,8 +134,8 @@ fn swatch_json(conv: &SwatchConv, sw: &SwatchEntry) -> Value { fn list(s: &mut Session, _: &Value) -> Result { let conv = SwatchConv::new(s); let groups: Vec = - s.presets.swatches.iter().map(|g| json!({"name": g.name, "swatches": g.entries.iter().map(|sw| swatch_json(&conv, sw)).collect::>()})).collect(); - Ok(json!({"groups": groups, "count": total(&s.presets.swatches)})) + s.presets().swatches.iter().map(|g| json!({"name": g.name, "swatches": g.entries.iter().map(|sw| swatch_json(&conv, sw)).collect::>()})).collect(); + Ok(json!({"groups": groups, "count": total(&s.presets().swatches)})) } fn add(s: &mut Session, p: &Value) -> Result { @@ -149,12 +151,12 @@ fn add(s: &mut Session, p: &Value) -> Result { None => SwatchKind::Process, Some(k) => parse_kind(k).ok_or_else(|| bad(CMD, format!("unknown kind `{k}` (process|global|spot)")))?, }; - if total(&s.presets.swatches) >= MAX_SWATCHES { + if total(&s.presets().swatches) >= MAX_SWATCHES { return Err(bad(CMD, format!("the Swatches panel is full ({MAX_SWATCHES} swatches)"))); } let group = name_param(p, "group", CMD)?; let explicit = name_param(p, "name", CMD)?; - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; let name = match explicit { Some(n) => unique_swatch_name(groups, &n), // Photoshop's default: "Color Swatch 1", "Color Swatch 2"… @@ -188,7 +190,7 @@ fn add(s: &mut Session, p: &Value) -> Result { }; entries.insert(at, SwatchEntry { name: name.clone(), color, kind }); let gname = groups[gi].name.clone(); - s.presets_changed(); + presets_changed(s); Ok(json!({"name": name, "group": gname, "index": at})) } @@ -196,7 +198,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { const CMD: &str = "swatches.delete"; let mut targets: Vec<(usize, usize)> = match p.get("swatch") { Some(Value::Array(a)) => { - let ix = index_by_name(&s.presets.swatches, str_param(p, "group")); + let ix = index_by_name(&s.presets().swatches, str_param(p, "group")); let mut v = Vec::with_capacity(a.len().min(MAX_SWATCHES)); for n in a { let name = n.as_str().ok_or_else(|| bad(CMD, "`swatch` names must be strings"))?; @@ -209,7 +211,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { // Remove from the back so earlier positions stay valid; duplicates count once. targets.sort_unstable(); targets.dedup(); - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; let mut names = Vec::with_capacity(targets.len()); for (gi, ii) in targets.into_iter().rev() { if let Some(g) = groups.get_mut(gi) @@ -219,7 +221,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { } } names.reverse(); - s.presets_changed(); + presets_changed(s); Ok(json!({"deleted": names})) } @@ -227,12 +229,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { const CMD: &str = "swatches.rename"; let (gi, ii) = locate(s, p, CMD)?; let to = name_param(p, "name", CMD)?.ok_or_else(|| bad(CMD, "missing `name`"))?; - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; if groups[gi].entries[ii].name != to && locate_swatch(groups, &to, None).is_some() { return Err(bad(CMD, format!("a swatch named \"{to}\" already exists"))); } groups[gi].entries[ii].name = to.clone(); - s.presets_changed(); + presets_changed(s); Ok(json!({"name": to})) } @@ -247,13 +249,13 @@ fn move_swatch(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(usize::try_from(v.as_u64().ok_or_else(|| bad(CMD, "`position` must be a non-negative integer"))?).unwrap_or(usize::MAX)), }; - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; let item = groups[gi].entries.remove(ii); let entries = &mut groups[ti].entries; let at = at.unwrap_or(entries.len()).min(entries.len()); entries.insert(at, item); let gname = groups[ti].name.clone(); - s.presets_changed(); + presets_changed(s); Ok(json!({"group": gname, "position": at})) } @@ -263,17 +265,17 @@ fn move_group(s: &mut Session, p: &Value) -> Result { let g = name_param(p, "group", CMD)?.ok_or_else(|| bad(CMD, "missing `group`"))?; let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(CMD, "`to` must be a non-negative integer"))?; let from = group_of(s, &g, CMD)?; - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; let at = usize::try_from(to).unwrap_or(usize::MAX).min(groups.len() - 1); let group = groups.remove(from); groups.insert(at, group); - s.presets_changed(); + presets_changed(s); Ok(json!({"group": g, "position": at})) } fn new_group(s: &mut Session, p: &Value) -> Result { const CMD: &str = "swatches.newGroup"; - if s.presets.swatches.len() >= MAX_GROUPS { + if s.presets().swatches.len() >= MAX_GROUPS { return Err(bad(CMD, "too many swatch groups")); } let base = name_param(p, "name", CMD)?.unwrap_or_else(|| "Group".into()); @@ -281,7 +283,7 @@ fn new_group(s: &mut Session, p: &Value) -> Result { let mut moving: Vec<(usize, usize)> = Vec::new(); if let Some(a) = p.get("swatches") { let a = a.as_array().ok_or_else(|| bad(CMD, "`swatches` must be a list of names"))?; - let ix = index_by_name(&s.presets.swatches, None); + let ix = index_by_name(&s.presets().swatches, None); for n in a { let name = n.as_str().ok_or_else(|| bad(CMD, "`swatches` names must be strings"))?; moving.push(*ix.get(name).ok_or_else(|| bad(CMD, format!("no swatch \"{name}\"")))?); @@ -289,7 +291,7 @@ fn new_group(s: &mut Session, p: &Value) -> Result { } moving.sort_unstable(); moving.dedup(); - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; let name = unique_group(groups, &base); let mut entries: Vec = Vec::with_capacity(moving.len()); for (gi, ii) in moving.into_iter().rev() { @@ -298,7 +300,7 @@ fn new_group(s: &mut Session, p: &Value) -> Result { entries.reverse(); let n = entries.len(); groups.push(SwatchGroup { name: name.clone(), entries }); - s.presets_changed(); + presets_changed(s); Ok(json!({"group": name, "moved": n})) } @@ -307,11 +309,11 @@ fn rename_group(s: &mut Session, p: &Value) -> Result { let g = name_param(p, "group", CMD)?.ok_or_else(|| bad(CMD, "missing `group`"))?; let to = name_param(p, "name", CMD)?.ok_or_else(|| bad(CMD, "missing `name`"))?; let i = group_of(s, &g, CMD)?; - if g != to && s.presets.swatches.iter().any(|x| x.name == to) { + if g != to && s.presets().swatches.iter().any(|x| x.name == to) { return Err(bad(CMD, format!("a group named \"{to}\" already exists"))); } - s.presets.swatches[i].name = to.clone(); - s.presets_changed(); + s.presets_mut().swatches[i].name = to.clone(); + presets_changed(s); Ok(json!({"group": to})) } @@ -323,7 +325,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_bool().ok_or_else(|| bad(CMD, "`keepSwatches` must be true or false"))?, }; let i = group_of(s, &g, CMD)?; - let groups = &mut s.presets.swatches; + let groups = &mut s.presets_mut().swatches; if keep && groups.len() < 2 { return Err(bad(CMD, "there is no other group to keep the swatches in")); } @@ -336,7 +338,7 @@ fn delete_group(s: &mut Session, p: &Value) -> Result { t.entries.extend(removed.entries); } } - s.presets_changed(); + presets_changed(s); Ok(json!({"group": g, if keep { "kept" } else { "deleted" }: n})) } @@ -344,7 +346,7 @@ fn use_swatch(s: &mut Session, p: &Value) -> Result { const CMD: &str = "swatches.use"; let (gi, ii) = locate(s, p, CMD)?; let target = str_param(p, "target").unwrap_or("foreground"); - let sw = s.presets.swatches[gi].entries[ii].clone(); + let sw = s.presets().swatches[gi].entries[ii].clone(); let rgb = SwatchConv::new(s).rgb(&sw.color); let c = [rgb[0], rgb[1], rgb[2], 1.0]; match target { @@ -370,21 +372,21 @@ fn reset(s: &mut Session, p: &Value) -> Result { }; let mut b = default_swatches(); if append { - if total(&s.presets.swatches) + total(&b) > MAX_SWATCHES || s.presets.swatches.len() + b.len() > MAX_GROUPS { + if total(&s.presets().swatches) + total(&b) > MAX_SWATCHES || s.presets().swatches.len() + b.len() > MAX_GROUPS { return Err(bad(CMD, "the Swatches panel is full")); } for g in &mut b { - g.name = unique_group(&s.presets.swatches, &g.name); + g.name = unique_group(&s.presets().swatches, &g.name); for sw in &mut g.entries { - sw.name = unique_swatch_name(&s.presets.swatches, &sw.name); + sw.name = unique_swatch_name(&s.presets().swatches, &sw.name); } - s.presets.swatches.push(g.clone()); + s.presets_mut().swatches.push(g.clone()); } } else { - s.presets.swatches = b; + s.presets_mut().swatches = b; } - s.presets_changed(); - Ok(json!({"groups": s.presets.swatches.len(), "count": total(&s.presets.swatches)})) + presets_changed(s); + Ok(json!({"groups": s.presets().swatches.len(), "count": total(&s.presets().swatches)})) } // ------------------------------------------------------------------ files @@ -469,7 +471,7 @@ fn import(s: &mut Session, p: &Value) -> Result { // The group name is the file stem: craft-color names ungrouped colours after it. let (groups, report) = read_swatches(&bytes, &format!("{group}.{}", format.extension())).map_err(|e| bad(CMD, e.to_string()))?; let warnings: Vec = report.notes.iter().map(|n| word_note(n, format, false)).collect(); - let base: Vec = if replace { Vec::new() } else { s.presets.swatches.clone() }; + let base: Vec = if replace { Vec::new() } else { s.presets().swatches.clone() }; if total(&base) + total(&groups) > MAX_SWATCHES || base.len() + groups.len() > MAX_GROUPS { return Err(bad(CMD, format!("too many swatches: the panel holds at most {MAX_SWATCHES} in {MAX_GROUPS} groups"))); } @@ -506,8 +508,8 @@ fn import(s: &mut Session, p: &Value) -> Result { names.push(g.name.clone()); lib.push(g); } - s.presets.swatches = lib; - s.presets_changed(); + s.presets_mut().swatches = lib; + presets_changed(s); Ok(json!({"format": format.extension(), "mode": mode, "groups": names, "count": count, "warnings": warnings})) } @@ -519,8 +521,8 @@ fn export(s: &mut Session, p: &Value) -> Result { None => path.and_then(SwatchFormat::from_name).unwrap_or(SwatchFormat::Aco), }; let mut groups: Vec = match name_param(p, "group", CMD)? { - Some(g) => vec![s.presets.swatches[group_of(s, &g, CMD)?].clone()], - None => s.presets.swatches.clone(), + Some(g) => vec![s.presets().swatches[group_of(s, &g, CMD)?].clone()], + None => s.presets().swatches.clone(), }; // Only some swatches (Photoshop: Export Selected Swatches). if let Some(a) = p.get("swatches") { diff --git a/crates/engine-core/src/cmd/swatch_cmds/tests.rs b/crates/engine-core/src/cmd/swatch_cmds/tests.rs index 0275bb5904..a2179ebc41 100644 --- a/crates/engine-core/src/cmd/swatch_cmds/tests.rs +++ b/crates/engine-core/src/cmd/swatch_cmds/tests.rs @@ -1,3 +1,5 @@ +use crate::prefs::SavedPrefsExt; +use crate::presets::PresetsExt; use super::*; use craft_psd::aco::{AcoColor, AcoSwatch}; use craft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch}; @@ -6,7 +8,7 @@ use photocraft_paint::tile::{b64_decode, b64_encode}; use crate::presets::swatches::color_model; fn names(s: &Session) -> Vec { - s.presets.swatches.iter().flat_map(|g| g.entries.iter().map(|i| i.name.clone())).collect() + s.presets().swatches.iter().flat_map(|g| g.entries.iter().map(|i| i.name.clone())).collect() } fn export_bytes(s: &mut Session, p: Value) -> Vec { @@ -31,7 +33,7 @@ fn add_from_foreground_and_explicit_models() { s.tools.foreground = [1.0, 0.5, 0.0, 1.0]; let r = s.execute("swatches.add", json!({})).unwrap(); assert_eq!((r["name"].as_str(), r["group"].as_str()), (Some("Color Swatch 1"), Some("Grays"))); - assert_eq!(s.presets.swatches[0].entries.last().unwrap().color, SwatchColor::Rgb([1.0, 0.5, 0.0])); + assert_eq!(s.presets().swatches[0].entries.last().unwrap().color, SwatchColor::Rgb([1.0, 0.5, 0.0])); let r = s.execute("swatches.add", json!({})).unwrap(); assert_eq!(r["name"], "Color Swatch 2"); // CMYK into a new group at the front, spot. @@ -39,7 +41,7 @@ fn add_from_foreground_and_explicit_models() { .execute("swatches.add", json!({"name": "Ink", "group": "Print", "index": 0, "kind": "spot", "color": {"model": "cmyk", "values": [100, 0, 0, 0]}})) .unwrap(); assert_eq!(r["group"], "Print"); - let g = s.presets.swatches.last().unwrap(); + let g = s.presets().swatches.last().unwrap(); assert_eq!(g.entries[0], SwatchEntry { name: "Ink".into(), color: SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0]), kind: SwatchKind::Spot }); // Names stay unique. let r = s.execute("swatches.add", json!({"name": "Ink"})).unwrap(); @@ -84,24 +86,24 @@ fn using_a_cmyk_swatch_remembers_its_inks() { fn rename_delete_move_and_groups() { let mut s = crate::session(); // A group moves to an index, clamped to the list, and the change is saved with the prefs. - let rev = s.presets.revision(); + let rev = s.presets().revision(); let r = s.execute("swatches.moveGroup", json!({"group": "Dark", "to": 0})).unwrap(); assert_eq!(r, json!({"group": "Dark", "position": 0})); - assert_eq!(s.presets.swatches[0].name, "Dark"); - assert_ne!(s.presets.revision(), rev, "a group move is a preset change"); + assert_eq!(s.presets().swatches[0].name, "Dark"); + assert_ne!(s.presets().revision(), rev, "a group move is a preset change"); let r = s.execute("swatches.moveGroup", json!({"group": "Dark", "to": 999})).unwrap(); assert_eq!(r["position"], 4); - assert_eq!(s.presets.swatches[4].name, "Dark"); + assert_eq!(s.presets().swatches[4].name, "Dark"); assert!(s.execute("swatches.moveGroup", json!({"group": "Nope", "to": 0})).is_err()); s.execute("swatches.rename", json!({"swatch": "Black", "name": "Ink Black"})).unwrap(); assert!(names(&s).contains(&"Ink Black".to_string())); assert!(s.execute("swatches.rename", json!({"swatch": "Ink Black", "name": "White"})).is_err(), "duplicate"); // Reorder within the group, then into another group. s.execute("swatches.move", json!({"swatch": "White", "position": 0})).unwrap(); - assert_eq!(s.presets.swatches[0].entries[0].name, "White"); + assert_eq!(s.presets().swatches[0].entries[0].name, "White"); let r = s.execute("swatches.move", json!({"swatch": "White", "to": "Dark", "position": 1})).unwrap(); assert_eq!(r, json!({"group": "Dark", "position": 1})); - assert_eq!(s.presets.swatches[4].entries[1].name, "White"); + assert_eq!(s.presets().swatches[4].entries[1].name, "White"); // Out-of-range positions clamp. let r = s.execute("swatches.move", json!({"swatch": "White", "position": 999_999})).unwrap(); assert_eq!(r["position"], 10); @@ -114,7 +116,7 @@ fn rename_delete_move_and_groups() { assert!(s.execute("swatches.renameGroup", json!({"group": "Favourites", "name": "Dark"})).is_err()); let r = s.execute("swatches.deleteGroup", json!({"group": "Favourites", "keepSwatches": true})).unwrap(); assert_eq!(r["kept"], 2); - assert!(s.presets.swatches[4].entries.iter().any(|i| i.name == "Red"), "kept in the group above"); + assert!(s.presets().swatches[4].entries.iter().any(|i| i.name == "Red"), "kept in the group above"); s.execute("swatches.deleteGroup", json!({"group": "Mine 1"})).unwrap(); // Delete several by name, and one by index. let r = s.execute("swatches.delete", json!({"swatch": ["Red", "Blue", "Red"]})).unwrap(); @@ -128,21 +130,21 @@ fn rename_delete_move_and_groups() { s.execute("swatches.reset", json!({"append": true})).unwrap(); assert_eq!(names(&s).len(), 92); assert!(names(&s).contains(&"Black 2".to_string())); - assert_eq!(s.presets.swatches[5].name, "Grays 1"); + assert_eq!(s.presets().swatches[5].name, "Grays 1"); } #[test] fn changes_persist_with_the_preferences() { let mut s = crate::session(); s.execute("swatches.add", json!({"name": "Keep me", "color": {"model": "lab", "values": [40, 12.5, -7.25]}})).unwrap(); - let saved = s.presets.to_json(&s); + let saved = s.presets().to_json(&s); let mut t = crate::session(); t.load_presets_json(saved); - assert_eq!(t.presets.swatches, s.presets.swatches); + assert_eq!(t.presets().swatches, s.presets().swatches); // A prefs file from before swatches existed keeps the defaults. let mut u = crate::session(); u.load_presets_json(json!({"gradients": null})); - assert_eq!(u.presets.swatches, default_swatches()); + assert_eq!(u.presets().swatches, default_swatches()); } #[test] @@ -160,9 +162,9 @@ fn aco_round_trip_keeps_16_bit_values_and_books() { let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Pro", "mode": "replace"})).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("aco"), Some(6))); assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the colour book is reported"); - assert_eq!(s.presets.swatches.len(), 1); - assert_eq!(s.presets.swatches[0].entries[3].color, SwatchColor::Lab([53.21, -128.0, 127.0])); - assert_eq!(color_model(&s.presets.swatches[0].entries[4].color), "gray"); + assert_eq!(s.presets().swatches.len(), 1); + assert_eq!(s.presets().swatches[0].entries[3].color, SwatchColor::Lab([53.21, -128.0, 127.0])); + assert_eq!(color_model(&s.presets().swatches[0].entries[4].color), "gray"); assert_eq!(export_bytes(&mut s, json!({"format": "aco"})), file, "byte-identical .aco"); // On disk too, with the group taken from the file name. let dir = std::env::temp_dir().join(format!("pc-swatch-{}", std::process::id())); @@ -194,8 +196,8 @@ fn act_round_trip_loads_a_photoshop_color_table() { let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Table", "mode": "replace"})).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("act"), Some(256))); assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the transparent color is reported"); - assert_eq!(s.presets.swatches[0].entries[0].color, SwatchColor::Rgb([1.0, 1.0, 1.0])); - assert_eq!(s.presets.swatches[0].entries[1].name, "Swatch 2"); + assert_eq!(s.presets().swatches[0].entries[0].color, SwatchColor::Rgb([1.0, 1.0, 1.0])); + assert_eq!(s.presets().swatches[0].entries[1].name, "Swatch 2"); // Sniffed by length without a format, and by extension from a path. let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap(); assert_eq!(r["format"].as_str(), Some("act")); @@ -236,7 +238,7 @@ fn act_that_starts_like_an_aco_is_still_an_act() { let mut s = crate::session(); let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("aco"), Some(10))); - assert_eq!(s.presets.swatches[0].entries[9].name, format!("{:0>25}", 9)); + assert_eq!(s.presets().swatches[0].entries[9].name, format!("{:0>25}", 9)); } #[test] @@ -261,7 +263,7 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() { assert_eq!(r["groups"], json!(["Exchange", "Brand"])); assert_eq!(r["count"], 4); assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the unknown model is reported"); - let brand = s.presets.swatches.iter().find(|g| g.name == "Brand").unwrap(); + let brand = s.presets().swatches.iter().find(|g| g.name == "Brand").unwrap(); assert_eq!(brand.entries[0].kind, SwatchKind::Spot); assert_eq!(brand.entries[1].color, SwatchColor::Lab([50.0, 20.0, -30.0])); assert_eq!(brand.entries[2].color, SwatchColor::Gray(0.75)); @@ -300,7 +302,7 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() { #[test] fn bad_params_fail_gracefully() { let mut s = crate::session(); - let before = s.presets.swatches.clone(); + let before = s.presets().swatches.clone(); let cases: &[(&str, Value)] = &[ ("swatches.add", json!({"color": "#12"})), ("swatches.add", json!({"color": {"model": "lab"}})), @@ -355,7 +357,7 @@ fn bad_params_fail_gracefully() { std::fs::write(&file, b"x").unwrap(); assert!(s.execute("swatches.export", json!({"path": file.join("x.aco").to_string_lossy()})).is_err()); std::fs::remove_file(&file).ok(); - assert_eq!(s.presets.swatches, before, "failed commands change nothing"); + assert_eq!(s.presets().swatches, before, "failed commands change nothing"); // Empty library: the swatch commands are disabled, not crashing. s.execute("swatches.delete", json!({"swatch": names(&s)})).unwrap(); for g in ["Grays", "RGB", "Pastel", "Pure", "Dark"] { @@ -393,13 +395,13 @@ fn unnamed_groups_are_numbered_in_linear_time() { std::thread::spawn(move || { let mut s = crate::session(); s.execute("swatches.newGroup", json!({"name": "Ink 2"})).unwrap(); - let n = MAX_GROUPS - s.presets.swatches.len(); + let n = MAX_GROUPS - s.presets().swatches.len(); let paper = AseSwatch { name: "Paper".into(), color: AseColor::Gray(1.0), kind: AseKind::Process }; let mut entries = vec![AseEntry::Group { name: String::new(), swatches: Vec::new() }; n]; entries[0] = AseEntry::Group { name: String::new(), swatches: vec![paper] }; let file = b64_encode(&craft_psd::ase::write(&AseFile { entries }).unwrap()); let r = s.execute("swatches.import", json!({"data": file, "group": "Ink"})).unwrap(); - assert_eq!(s.presets.swatches.len(), MAX_GROUPS); + assert_eq!(s.presets().swatches.len(), MAX_GROUPS); let names: Vec = r["groups"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); let _ = tx.send(names); }); @@ -434,7 +436,7 @@ fn repeated_group_names_take_the_first_free_number() { fn values_beyond_f32_range_are_rejected_so_presets_survive_a_restart() { let mut s = crate::session(); s.execute("swatches.add", json!({"name": "Keep me", "color": {"model": "lab", "values": [40, 12.5, -7.25]}})).unwrap(); - let before = s.presets.swatches.clone(); + let before = s.presets().swatches.clone(); for (model, values) in [ ("hsb", json!([1e39, 100, 100])), ("hsb", json!([-1e39, 100, 100])), @@ -446,11 +448,11 @@ fn values_beyond_f32_range_are_rejected_so_presets_survive_a_restart() { let r = s.execute("swatches.add", json!({"name": "Bad", "color": {"model": model, "values": values}})); assert!(matches!(r, Err(crate::EngineError::BadParams { .. })), "{model} {values}: {r:?}"); } - assert_eq!(s.presets.swatches, before, "a rejected colour leaves the library unchanged"); + assert_eq!(s.presets().swatches, before, "a rejected colour leaves the library unchanged"); // The largest f32 hue is still accepted and stays finite. s.execute("swatches.add", json!({"name": "Big hue", "color": {"model": "hsb", "values": [f64::from(f32::MAX), 100, 100]}})).unwrap(); let mut t = crate::session(); t.load_prefs_json(&s.prefs_to_json()).unwrap(); - assert_eq!(t.presets.swatches, s.presets.swatches, "user swatches survive a save and reload"); + assert_eq!(t.presets().swatches, s.presets().swatches, "user swatches survive a save and reload"); assert!(names(&t).contains(&"Keep me".to_string())); } diff --git a/crates/engine-core/src/cmd/table/store/file_menu.rs b/crates/engine-core/src/cmd/table/store/file_menu.rs index 6fe8f8666c..d1c8131ac5 100644 --- a/crates/engine-core/src/cmd/table/store/file_menu.rs +++ b/crates/engine-core/src/cmd/table/store/file_menu.rs @@ -1,3 +1,4 @@ +use crate::color_cmds::ColorExt; use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex}; /// File menu: New (new documents take their presets from the document preset store). @@ -55,7 +56,7 @@ pub fn specs() -> Vec { // Photoshop's New Document › Color Profile: tag the document with another profile // than the working space (#321). Checked before the document opens. if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) { - let prof = s.color.resolve(spec, Some(&doc), None)?; + let prof = s.color().resolve(spec, Some(&doc), None)?; if prof.color_space != crate::color_cmds::mode_space(doc.mode) { return Err(EngineError::BadParams { cmd: "file.new".into(), diff --git a/crates/engine-core/src/cmd/transform_cmds/multi_tests.rs b/crates/engine-core/src/cmd/transform_cmds/multi_tests.rs index 449bb4fee9..f07760ed95 100644 --- a/crates/engine-core/src/cmd/transform_cmds/multi_tests.rs +++ b/crates/engine-core/src/cmd/transform_cmds/multi_tests.rs @@ -1,5 +1,6 @@ //! Free Transform of several selected layers by one box (#6501). +use crate::actions_cmds::ActionsExt; use super::*; /// A 200 x 200 document: a red 40 x 20 block on "Paint" (x 10..50, y 10..30) and a type layer @@ -253,7 +254,7 @@ fn a_recorded_transform_of_the_selected_layers_replays_on_the_selection_in_anoth // What the canvas box commits: the ids it opened on, listed (#6501). s.execute("edit.transform", json!({"layers": [paint.0, text.0], "matrix": [1, 0, 0, 1, 30, 40]})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let step = s.actions.list.actions()[0].steps[0].params.clone(); + let step = s.actions().list.actions()[0].steps[0].params.clone(); assert!(step.get("layers").is_none(), "the step plays on the selection, not on these ids: {step}"); // Another document, its ids shifted by an extra layer under the two that get selected. s.execute("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); @@ -434,5 +435,5 @@ fn a_recorded_transform_of_other_layers_than_the_selection_keeps_their_ids() { s.execute("actions.record", json!({"name": "Paint only"})).unwrap(); s.execute("edit.transform", json!({"layers": [paint.0], "matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params["layers"], json!([paint.0])); + assert_eq!(s.actions().list.actions()[0].steps[0].params["layers"], json!([paint.0])); } diff --git a/crates/engine-core/src/cmd/type_spell_cmds.rs b/crates/engine-core/src/cmd/type_spell_cmds.rs index 6e8dfd5e74..ca2ddef252 100644 --- a/crates/engine-core/src/cmd/type_spell_cmds.rs +++ b/crates/engine-core/src/cmd/type_spell_cmds.rs @@ -312,6 +312,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::actions_cmds::ActionsExt; use super::*; use crate::actions_cmds::ActionStep; @@ -435,7 +436,7 @@ mod tests { s.execute("edit.checkSpelling", json!({"allLayers": true, "suggestions": 8})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); assert_eq!(text_of(&s, id), "The brown end"); - let action = &s.actions.list.actions()[0]; + let action = &s.actions().list.actions()[0]; assert_eq!(action.steps, vec![ActionStep::new("edit.checkSpelling", json!({"allLayers": true}))]); assert_eq!(action.dialogs.iter().copied().collect::>(), [0]); } @@ -447,9 +448,9 @@ mod tests { s.execute("edit.checkSpelling", json!({"allLayers": false})).unwrap(); s.execute("edit.checkSpelling", json!({"layer": id})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - let steps: Vec<&Value> = s.actions.list.actions()[0].steps.iter().map(|step| &step.params).collect(); + let steps: Vec<&Value> = s.actions().list.actions()[0].steps.iter().map(|step| &step.params).collect(); assert_eq!(steps, [&json!({"allLayers": false}), &json!({"allLayers": false})]); - assert_eq!(s.actions.list.actions()[0].dialogs.len(), 2); + assert_eq!(s.actions().list.actions()[0].dialogs.len(), 2); } /// `"action": null` runs Check Spelling itself, so it is recorded as one. @@ -459,7 +460,7 @@ mod tests { s.execute("actions.record", json!({"name": "Null"})).unwrap(); s.execute("edit.checkSpelling", json!({"action": null})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("edit.checkSpelling", json!({"allLayers": true}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("edit.checkSpelling", json!({"allLayers": true}))]); } #[test] diff --git a/crates/engine-core/src/display_color/tests.rs b/crates/engine-core/src/display_color/tests.rs index bfb74bc108..53a15ca009 100644 --- a/crates/engine-core/src/display_color/tests.rs +++ b/crates/engine-core/src/display_color/tests.rs @@ -1,6 +1,7 @@ //! Colour-managed display (#46): non-sRGB documents show their colours on an sRGB (or other) //! monitor. Fixtures are built-in (CC0) or synthesized profiles only. +use crate::color_cmds::ColorExt; use std::sync::Arc; use craft_cms::synth::{CmykParams, cmyk_profile}; @@ -50,7 +51,7 @@ fn test_cmyk() -> Profile { /// What the CPU canvas shows at the centre pixel (RGBA8). fn shown(s: &Session, d: &Document) -> [f32; 3] { let buf = photocraft_compose::flatten(d); - let img = s.color.canvas_display(d).unwrap().to_rgba8(&buf); + let img = s.color().canvas_display(d).unwrap().to_rgba8(&buf); let i = (4 * d.size.width as usize + 4) * 4; [0, 1, 2].map(|k| img.pixels[i + k] as f32) } @@ -76,21 +77,21 @@ fn far(a: [f32; 3], b: [f32; 3], d: f32) -> bool { fn srgb_is_the_identity_fast_path() { let s = crate::session(); for d in [rgb_doc(None, [0.8, 0.5, 0.3], SampleType::U8), rgb_doc(Some(Builtin::Srgb.profile()), [0.8, 0.5, 0.3], SampleType::U16)] { - let cd = s.color.canvas_display(&d).unwrap(); + let cd = s.color().canvas_display(&d).unwrap(); assert!(cd.is_identity(), "sRGB on an sRGB monitor costs nothing"); - assert!(s.color.canvas_lut(&d, 9).unwrap().is_none(), "no GPU LUT either"); + assert!(s.color().canvas_lut(&d, 9).unwrap().is_none(), "no GPU LUT either"); assert!(close(shown(&s, &d), [204.0, 127.5, 76.5], 0.6)); } // sGray-tagged gray and CMYK (shown in sRGB) composites are sRGB too; untagged gray takes the // default working gray (Dot Gain 20 %-compatible), which is not. let mut g = Document::with_background("g", Size::new(4, 4), ColorMode::Grayscale, SampleType::U8, Color::gray(0.3)); - assert!(!s.color.canvas_display(&g).unwrap().is_identity()); + assert!(!s.color().canvas_display(&g).unwrap().is_identity()); g.icc_profile = Some(Builtin::SGray.profile().to_bytes()); - assert!(s.color.canvas_display(&g).unwrap().is_identity()); - assert!(s.color.canvas_display(&cmyk_doc(None, [0.1, 0.5, 0.5, 0.0])).unwrap().is_identity()); + assert!(s.color().canvas_display(&g).unwrap().is_identity()); + assert!(s.color().canvas_display(&cmyk_doc(None, [0.1, 0.5, 0.5, 0.0])).unwrap().is_identity()); // Cached: the same Arc for the same profiles. let d = rgb_doc(Some(Builtin::DisplayP3.profile()), [0.5; 3], SampleType::U8); - assert!(Arc::ptr_eq(&s.color.canvas_display(&d).unwrap(), &s.color.canvas_display(&d).unwrap())); + assert!(Arc::ptr_eq(&s.color().canvas_display(&d).unwrap(), &s.color().canvas_display(&d).unwrap())); } #[test] @@ -103,7 +104,7 @@ fn display_p3_matches_hand_computed_srgb() { assert!(close(got, [216.7, 122.9, 64.3], TOL), "{got:?}"); assert!(far(got, [204.0, 127.5, 76.5], 10.0), "raw values would be desaturated: {got:?}"); // The GPU LUT maps the same value there (the lattice point nearest to it, within interpolation error). - let lut = s.color.canvas_lut(&d, 33).expect("lut").expect("not the identity"); + let lut = s.color().canvas_lut(&d, 33).expect("lut").expect("not the identity"); assert_eq!(lut.len(), 33 * 33 * 33 * 4); } @@ -126,7 +127,7 @@ fn wide_gamut_and_gray_fixtures_display_correctly() { } // Gray Gamma 2.2: gray 0.1 is L = 0.1^2.2 = 0.00631 → sRGB 18.6 (raw would be 25.5). let d = gray_doc(Builtin::GrayGamma22.profile(), 0.1); - assert!(!s.color.canvas_display(&d).unwrap().is_identity()); + assert!(!s.color().canvas_display(&d).unwrap().is_identity()); let got = shown(&s, &d); assert!(close(got, [18.6; 3], TOL), "{got:?}"); } @@ -163,7 +164,7 @@ fn linear_documents_are_encoded_for_the_texture() { let s = crate::session(); // Linear 0.2 is sRGB 0.4845 (123.5). let d = rgb_doc(Some(Builtin::LinearSrgb.profile()), [0.2, 0.2, 0.2], SampleType::F32); - let cd = s.color.canvas_display(&d).unwrap(); + let cd = s.color().canvas_display(&d).unwrap(); assert!(cd.encode_srgb && cd.transform.is_none(), "linear sRGB = sRGB primaries: encoding is all it takes"); assert!(close(shown(&s, &d), [123.5; 3], 1.0), "{:?}", shown(&s, &d)); let buf = photocraft_compose::flatten(&d); @@ -172,7 +173,7 @@ fn linear_documents_are_encoded_for_the_texture() { // An sRGB document is passed through untouched. let srgb = rgb_doc(None, [0.2; 3], SampleType::F32); let b2 = photocraft_compose::flatten(&srgb); - assert!(matches!(s.color.canvas_display(&srgb).unwrap().texture_buffer(&b2), std::borrow::Cow::Borrowed(_))); + assert!(matches!(s.color().canvas_display(&srgb).unwrap().texture_buffer(&b2), std::borrow::Cow::Borrowed(_))); } #[test] @@ -222,8 +223,8 @@ fn monitor_profile_setting() { let r = s.execute("edit.colorSettings", json!({"monitorProfile": "display-p3"})).unwrap(); assert_eq!(r["monitor"], "Display P3"); // On a P3 monitor, P3 documents are the identity and sRGB ones are converted. - assert!(s.color.canvas_display(&p3).unwrap().is_identity()); - assert!(!s.color.canvas_display(&srgb).unwrap().is_identity()); + assert!(s.color().canvas_display(&p3).unwrap().is_identity()); + assert!(!s.color().canvas_display(&srgb).unwrap().is_identity()); let got = shown(&s, &srgb); let mut want = [0.0f32; 3]; Transform::new(Builtin::Srgb.profile(), Builtin::DisplayP3.profile(), Intent::RelativeColorimetric, true) @@ -233,17 +234,17 @@ fn monitor_profile_setting() { assert!(close(got, want.map(|v| v * 255.0), TOL), "{got:?} vs {want:?}"); // `auto` uses the platform's profile when supplied, else sRGB. s.execute("edit.colorSettings", json!({"monitorProfile": "auto"})).unwrap(); - assert!(s.color.canvas_display(&srgb).unwrap().is_identity()); - s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(Builtin::DisplayP3.profile().to_bytes().to_vec()))])); - assert_eq!(s.color.monitor().description, "Display P3"); - assert!(s.color.canvas_display(&p3).unwrap().is_identity()); + assert!(s.color().canvas_display(&srgb).unwrap().is_identity()); + s.color_mut().set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(Builtin::DisplayP3.profile().to_bytes().to_vec()))])); + assert_eq!(s.color().monitor().description, "Display P3"); + assert!(s.color().canvas_display(&p3).unwrap().is_identity()); // Garbage platform bytes fall back to sRGB. - s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(vec![0u8; 16]))])); - assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash()); + s.color_mut().set_displays(Ok(vec![display(1, [0.0, 0.0, 100.0, 100.0], Some(vec![0u8; 16]))])); + assert_eq!(s.color().monitor().content_hash(), Builtin::Srgb.profile().content_hash()); // The signature follows the monitor. - let a = s.color.display_signature(&p3); + let a = s.color().display_signature(&p3); s.execute("edit.colorSettings", json!({"monitorProfile": "display-p3"})).unwrap(); - assert_ne!(a, s.color.display_signature(&p3)); + assert_ne!(a, s.color().display_signature(&p3)); } fn display(id: u32, frame: [f64; 4], icc: Option>) -> crate::display_color::Display { @@ -264,19 +265,19 @@ fn monitor_status_says_what_is_applied() { assert_eq!((st["requested"].as_str(), st["source"].as_str()), (Some("auto"), Some("fallback"))); assert_eq!(st["detection"]["state"], "unsupported"); assert!(st["reason"].as_str().unwrap().contains("doesn't report"), "{st}"); - s.color.monitor_detection = MonitorDetection::Pending; + s.color_mut().monitor_detection = MonitorDetection::Pending; assert!(status(&mut s)["reason"].as_str().unwrap().contains("hasn't been read")); // A profile read for a named display. let mut studio = display(7, [0.0, 0.0, 100.0, 100.0], p3()); studio.name = "Studio Display".into(); studio.profile_name = Some("Studio Display (calibrated)".into()); - s.color.set_displays(Ok(vec![studio])); + s.color_mut().set_displays(Ok(vec![studio])); let st = status(&mut s); assert_eq!((st["source"].as_str(), st["profile"].as_str()), (Some("auto"), Some("Display P3"))); assert_eq!((st["display"].as_str(), st["detection"]["state"].as_str()), (Some("Studio Display"), Some("found"))); assert_eq!(st["fingerprint"], format!("{:016x}", Builtin::DisplayP3.profile().content_hash())); assert!(st["reason"].is_null()); - assert_eq!(s.color.monitor_status().summary(), "Studio Display (calibrated) (auto)"); + assert_eq!(s.color().monitor_status().summary(), "Studio Display (calibrated) (auto)"); // Bytes that aren't a profile, a non-RGB profile, one that can't be a destination and none // at all fall back to sRGB with the reason. let mut link = Builtin::Srgb.profile().clone(); @@ -288,26 +289,26 @@ fn monitor_status_says_what_is_applied() { (Some(link.to_bytes().to_vec()), "can't be used as a display profile"), (None, "Display 2 has no ICC profile"), ] { - s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], icc)])); + s.color_mut().set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], icc)])); let st = status(&mut s); assert_eq!(st["source"], "fallback", "{why}"); assert!(st["reason"].as_str().unwrap().contains(why), "{st}"); - assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash()); + assert_eq!(s.color().monitor().content_hash(), Builtin::Srgb.profile().content_hash()); } // A failed re-read keeps the displays read before and is returned for the log. - s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())])); - assert_eq!(s.color.set_displays(Err("osascript failed".into())).as_deref(), Some("osascript failed")); - assert_eq!((s.color.monitor().description.as_str(), s.color.displays.len()), ("Display P3", 1)); + s.color_mut().set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())])); + assert_eq!(s.color_mut().set_displays(Err("osascript failed".into())).as_deref(), Some("osascript failed")); + assert_eq!((s.color().monitor().description.as_str(), s.color().displays.len()), ("Display P3", 1)); // ... and the status says the reading is an earlier one. let st = status(&mut s); assert_eq!((st["source"].as_str(), st["detection"]["state"].as_str()), (Some("auto"), Some("retained"))); assert_eq!(st["detection"]["reason"], "osascript failed"); // A later successful read makes it current again. - s.color.set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())])); + s.color_mut().set_displays(Ok(vec![display(2, [0.0, 0.0, 100.0, 100.0], p3())])); assert_eq!(status(&mut s)["detection"]["state"], "found"); // Without displays read before, the failure is the reason. let mut fresh = crate::session(); - assert_eq!(fresh.color.set_displays(Err("osascript failed".into())), None); + assert_eq!(fresh.color_mut().set_displays(Err("osascript failed".into())), None); let st = status(&mut fresh); assert_eq!((st["source"].as_str(), st["reason"].as_str()), (Some("fallback"), Some("osascript failed"))); // A manual choice wins over the display's profile. @@ -322,8 +323,8 @@ fn each_display_gets_its_own_profile() { let mut s = crate::session(); // Built-in (primary, menu bar) left, a wide-gamut external display right and higher up, // as on the #569 setup (frames in points, y down). - s.color.set_displays(Ok(vec![display(1, [0.0, 0.0, 1728.0, 1117.0], None), display(4, [1728.0, -667.0, 3008.0, 1692.0], p3())])); - let displays = s.color.displays.clone(); + s.color_mut().set_displays(Ok(vec![display(1, [0.0, 0.0, 1728.0, 1117.0], None), display(4, [1728.0, -667.0, 3008.0, 1692.0], p3())])); + let displays = s.color().displays.clone(); let at = |r: [f64; 4]| crate::display_color::display_at(&displays, r); assert_eq!(at([100.0, 100.0, 800.0, 600.0]), Some(1)); assert_eq!(at([2000.0, -500.0, 800.0, 600.0]), Some(4)); @@ -333,42 +334,42 @@ fn each_display_gets_its_own_profile() { assert_eq!(at([-5000.0, 0.0, 10.0, 10.0]), None); // Display 1 has no profile here (sRGB fallback); display 4 is P3; unknown = the primary. let srgb = rgb_doc(None, [0.8, 0.5, 0.3], SampleType::U8); - assert_eq!(s.color.monitor_for(Some(4)).description, "Display P3"); - assert_eq!(s.color.monitor_for(Some(1)).content_hash(), Builtin::Srgb.profile().content_hash()); - assert_eq!(s.color.monitor_for(None).content_hash(), s.color.monitor_for(Some(1)).content_hash()); - assert_eq!(s.color.monitor_for(Some(99)).content_hash(), s.color.monitor_for(Some(1)).content_hash()); + assert_eq!(s.color().monitor_for(Some(4)).description, "Display P3"); + assert_eq!(s.color().monitor_for(Some(1)).content_hash(), Builtin::Srgb.profile().content_hash()); + assert_eq!(s.color().monitor_for(None).content_hash(), s.color().monitor_for(Some(1)).content_hash()); + assert_eq!(s.color().monitor_for(Some(99)).content_hash(), s.color().monitor_for(Some(1)).content_hash()); // The same document has a different display (and LUT signature) per display; the texture key // (what the GPU canvas texture stores) is shared. - let (a, b) = (s.color.canvas_display_for(&srgb, Some(1)).unwrap(), s.color.canvas_display_for(&srgb, Some(4)).unwrap()); + let (a, b) = (s.color().canvas_display_for(&srgb, Some(1)).unwrap(), s.color().canvas_display_for(&srgb, Some(4)).unwrap()); assert!(a.is_identity() && !b.is_identity()); assert_ne!(a.key, b.key); assert_eq!(a.texture_key, b.texture_key); - assert_ne!(s.color.display_signature_for(&srgb, Some(1)), s.color.display_signature_for(&srgb, Some(4))); - assert!(s.color.gpu_canvas_lut_for(&srgb, 9, Some(1)).unwrap().is_none()); - assert!(s.color.gpu_canvas_lut_for(&srgb, 9, Some(4)).unwrap().is_some()); + assert_ne!(s.color().display_signature_for(&srgb, Some(1)), s.color().display_signature_for(&srgb, Some(4))); + assert!(s.color().gpu_canvas_lut_for(&srgb, 9, Some(1)).unwrap().is_none()); + assert!(s.color().gpu_canvas_lut_for(&srgb, 9, Some(4)).unwrap().is_some()); // The main window's display is what the unqualified methods use. - s.color.main_display = Some(4); - assert_eq!(s.color.monitor().description, "Display P3"); - assert_eq!(s.color.display_signature(&srgb), s.color.display_signature_for(&srgb, Some(4))); - let statuses = s.color.display_statuses(); + s.color_mut().main_display = Some(4); + assert_eq!(s.color().monitor().description, "Display P3"); + assert_eq!(s.color().display_signature(&srgb), s.color().display_signature_for(&srgb, Some(4))); + let statuses = s.color().display_statuses(); assert_eq!((statuses.len(), statuses[1]["main"].as_bool()), (2, Some(true))); assert_eq!(statuses[0]["status"]["source"], "fallback"); // Proof Colors follow the display too. s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); let doc = s.active().unwrap().doc.clone(); s.execute("view.proofColors", json!({"on": true})).unwrap(); - assert_ne!(s.color.gpu_canvas_lut_for(&doc, 9, Some(1)).unwrap(), s.color.gpu_canvas_lut_for(&doc, 9, Some(4)).unwrap()); + assert_ne!(s.color().gpu_canvas_lut_for(&doc, 9, Some(1)).unwrap(), s.color().gpu_canvas_lut_for(&doc, 9, Some(4)).unwrap()); } #[test] fn saved_monitor_profile_that_is_gone_is_reported() { // Preferences load settings without validating them: a saved .icc path deleted since. let mut s = crate::session(); - s.color.settings.monitor_profile = "/nonexistent/photocraft/display.icc".into(); - let st = s.color.monitor_status(); + s.color_mut().settings.monitor_profile = "/nonexistent/photocraft/display.icc".into(); + let st = s.color().monitor_status(); assert_eq!((st.requested.as_str(), st.source), ("/nonexistent/photocraft/display.icc", "fallback")); assert!(st.reason.as_deref().unwrap_or("").contains("cannot read profile"), "{st:?}"); - assert_eq!(s.color.monitor().content_hash(), Builtin::Srgb.profile().content_hash()); + assert_eq!(s.color().monitor().content_hash(), Builtin::Srgb.profile().content_hash()); } #[test] @@ -382,7 +383,7 @@ fn monitor_profile_bad_params_fail_gracefully() { ] { assert!(s.execute("edit.colorSettings", bad.clone()).is_err(), "{bad}"); } - assert_eq!(s.color.settings.monitor_profile, "auto", "unchanged after errors"); + assert_eq!(s.color().settings.monitor_profile, "auto", "unchanged after errors"); // Non-string values are ignored. assert!(s.execute("edit.colorSettings", json!({"monitorProfile": 7})).is_ok()); } @@ -393,13 +394,13 @@ fn proof_colors_still_apply_on_top() { s.execute("file.new", json!({"width": 8, "height": 8, "mode": "rgb", "depth": 8})).unwrap(); s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap(); let d = s.active().unwrap().doc.clone(); - let plain = s.color.canvas_lut(&d, 9).unwrap().unwrap(); + let plain = s.color().canvas_lut(&d, 9).unwrap().unwrap(); s.execute("view.proofColors", json!({"on": true})).unwrap(); - let proof = s.color.canvas_lut(&d, 9).unwrap().unwrap(); + let proof = s.color().canvas_lut(&d, 9).unwrap().unwrap(); assert_ne!(plain, proof, "the proof changes the LUT"); - let sig = s.color.display_signature(&d); + let sig = s.color().display_signature(&d); s.execute("view.gamutWarning", json!({"on": true})).unwrap(); - assert_ne!(sig, s.color.display_signature(&d)); + assert_ne!(sig, s.color().display_signature(&d)); } #[test] diff --git a/crates/engine-core/src/doc_path/tests.rs b/crates/engine-core/src/doc_path/tests.rs index 1e3b44c701..dea69f625e 100644 --- a/crates/engine-core/src/doc_path/tests.rs +++ b/crates/engine-core/src/doc_path/tests.rs @@ -1,6 +1,7 @@ //! Each kind of place that follows a path stored in a document goes through [`super::resolve`]: a //! link to another computer is never followed, and a relative link next to the document is. +use crate::link_watch::LinkWatchExt; use std::path::{Path, PathBuf}; use photocraft_doc::{LayerContent, LayerId, SmartSource}; diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index cdf1593f7d..7ac2d13ae7 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -349,7 +349,7 @@ pub struct ToolState { pub brush: craft_tracked::Tracked, /// Brush presets (built-ins plus user presets; see `brush.presets.*`), tracked as the brush is. pub presets: craft_tracked::Tracked>>, - /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store + /// Bumped whenever `presets` changes ([`PresetStoreExt::brush_presets_changed`](crate::preset_store::PresetStoreExt::brush_presets_changed)); the preset store /// syncs when it moves. pub presets_rev: u64, /// Mixer Brush paint carried between strokes. diff --git a/crates/engine-core/src/filters/tests.rs b/crates/engine-core/src/filters/tests.rs index a34e7d6c1d..9b4eee15d9 100644 --- a/crates/engine-core/src/filters/tests.rs +++ b/crates/engine-core/src/filters/tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use super::*; #[test] @@ -338,11 +339,11 @@ fn recorded_last_filter_replays_the_filter_it_repeated() { s.execute("actions.stop", json!({})).unwrap(); let steps = s.execute("actions.get", json!({"action": "Again"})).unwrap()["steps"].clone(); assert_eq!(steps, json!([["filter.other.offset", {"horizontal": 3}]])); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let mut fresh = session(); paint_pattern(&mut fresh); - fresh.actions.list.push(action).unwrap(); + fresh.actions_mut().list.push(action).unwrap(); let played = fresh.execute("actions.play", json!({"action": "Again"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); let mut direct = session(); diff --git a/crates/engine-core/src/jobs.rs b/crates/engine-core/src/jobs.rs index c250a61744..11bb0d7ddf 100644 --- a/crates/engine-core/src/jobs.rs +++ b/crates/engine-core/src/jobs.rs @@ -27,6 +27,7 @@ //! - While a job runs on a document, commands that would edit that document are disabled with a //! message naming the job (queries and document-independent commands still run). +use crate::color_cmds::ColorExt; use std::any::Any; use std::sync::atomic::{AtomicU8, AtomicU32, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak}; @@ -1201,7 +1202,7 @@ impl Session { /// Open a file in the background: read (for a path) and decode on a worker, with progress /// (per layer for PSD/PSB) and cancellation, then add the document like - /// [`Session::open_document`] (Color Settings policies apply). `name` names the document. + /// [`ColorExt::open_document`](crate::color_cmds::ColorExt::open_document) (Color Settings policies apply). `name` names the document. /// The job's result is `{document, docId, name, warnings, color}`; on wasm it runs inline. /// `document` is the tab index at apply time; resolve `docId` before handling a delayed /// completion, since earlier handlers may have moved or closed tabs. When @@ -1386,7 +1387,7 @@ impl Session { crate::file_cmds::raw_defaults(s, &r.warnings, &mut r.document); let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); let damaged = confirm_damage && damaged; - let question = s.color.open_question(&r.document).filter(|_| !raw); + let question = s.color().open_question(&r.document).filter(|_| !raw); if damaged || question.is_some() { let held = s.hold_open(r.document, r.source_read_only); return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged})); diff --git a/crates/engine-core/src/jobs/tests.rs b/crates/engine-core/src/jobs/tests.rs index c96eed72ca..721544d4e8 100644 --- a/crates/engine-core/src/jobs/tests.rs +++ b/crates/engine-core/src/jobs/tests.rs @@ -1,3 +1,4 @@ +use crate::actions_cmds::ActionsExt; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::time::{Duration, Instant}; @@ -1119,7 +1120,7 @@ fn admit(_: &str, _: &Value) -> Result<()> { /// Whether the action named `name` is marked as written by automation. fn marked(s: &Session, name: &str) -> bool { - s.actions.list.actions().iter().find(|a| a.name == name).unwrap().automation + s.actions().list.actions().iter().find(|a| a.name == name).unwrap().automation } /// A background step a gated client starts during the user's recording marks the recorded action diff --git a/crates/engine-core/src/layer_style.rs b/crates/engine-core/src/layer_style.rs index 37317609d5..cb4947e457 100644 --- a/crates/engine-core/src/layer_style.rs +++ b/crates/engine-core/src/layer_style.rs @@ -1,5 +1,7 @@ //! `layer.layerStyle.*` commands: add/replace layer effects on a layer. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_color::{BlendMode, Color}; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::effects::PATTERN_SCALE_RANGE; @@ -1112,8 +1114,8 @@ fn make_default(s: &mut Session, p: &Value) -> Result { _ => return Err(bad(CMD, "`params` must be an object")), }; crate::commands::check_f32_values(CMD, ¶ms)?; - s.presets.layer_defaults.insert(kind.to_string(), params); - s.presets_changed(); + s.presets_mut().layer_defaults.insert(kind.to_string(), params); + presets_changed(s); Ok(json!({"kind": kind})) } @@ -1121,7 +1123,7 @@ fn make_default(s: &mut Session, p: &Value) -> Result { fn default_for(s: &mut Session, p: &Value) -> Result { const CMD: &str = "layer.layerStyle.defaultFor"; let kind = req_str_kind(p, CMD)?; - match s.presets.layer_defaults.get(kind) { + match s.presets().layer_defaults.get(kind) { Some(v) if v.is_object() => Ok(json!({"params": v, "user": true})), _ => Ok(json!({"params": effect_defaults(kind), "user": false})), } diff --git a/crates/engine-core/src/layer_style/tests.rs b/crates/engine-core/src/layer_style/tests.rs index cf6616020c..6c9089badc 100644 --- a/crates/engine-core/src/layer_style/tests.rs +++ b/crates/engine-core/src/layer_style/tests.rs @@ -1,3 +1,4 @@ +use crate::presets::PresetsExt; use super::*; use serde_json::json; @@ -631,7 +632,7 @@ fn fresh_effects_match_the_dialog_factory_defaults() { fn layer_style_defaults_persist_with_presets() { let mut s = session(); s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap(); - let blob = s.presets.to_json(&s); + let blob = s.presets().to_json(&s); let mut t = crate::session(); t.load_presets_json(blob); let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 4748be0c82..03a6087976 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -310,10 +310,10 @@ pub struct Session { /// Each open document's linked smart objects' files: size and modification time when last /// seen ([`link_watch`]). pub link_stamps: std::collections::HashMap<(u64, String), state::Stamp>, - /// The stamps being taken on a worker thread ([`Session::start_link_scan`]). + /// The stamps being taken on a worker thread ([`LinkWatchExt::start_link_scan`](crate::link_watch::LinkWatchExt::start_link_scan)). pub link_scan: Option, /// Each open document's linked smart objects' files that were not there when last looked at - /// ([`Session::missing_links`]). Written only when the set changes, so its revision says when the list did. + /// ([`LinkWatchExt::missing_links`](crate::link_watch::LinkWatchExt::missing_links)). Written only when the set changes, so its revision says when the list did. link_missing: craft_tracked::Tracked>, /// A finished live stroke offered to the `paint.stroke` / `paint.pencil` that commits it /// ([`Session::offer_live_stroke`]). diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index 2b00f90392..b465eec1ff 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -8,9 +8,9 @@ //! edits exactly what the desktop app persists, and the shell has no second store to keep in sync. //! //! The engine never touches the filesystem for preferences (it must build for wasm). Frontends -//! persist [`Session::prefs_to_json`] wherever the platform keeps settings (the desktop app: the +//! persist [`SavedPrefsExt::prefs_to_json`](crate::prefs::SavedPrefsExt::prefs_to_json) wherever the platform keeps settings (the desktop app: the //! OS config directory; the web shell: browser storage) and restore it with -//! [`Session::load_prefs_json`]. +//! [`SavedPrefsExt::load_prefs_json`](crate::prefs::SavedPrefsExt::load_prefs_json). //! //! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit and //! History Options › Allow Non-Linear History (every open document), the effect-cache memory @@ -1897,15 +1897,16 @@ mod tests; #[cfg(test)] mod color_settings_path_tests { + use crate::color_cmds::ColorExt; use serde_json::json; #[test] fn a_path_that_only_starts_with_color_settings_is_not_in_that_section() { let mut s = crate::session(); - let before = s.color.settings.clone(); + let before = s.color().settings.clone(); for path in ["colorSettingsworkingRgb", "colorSettings.", "colorSettings..workingRgb"] { assert!(s.execute("prefs.set", json!({"path": path, "value": "/dev/zero"})).is_err(), "{path}"); } - assert_eq!(s.color.settings, before); + assert_eq!(s.color().settings, before); } } diff --git a/crates/engine-core/src/prefs/cmds.rs b/crates/engine-core/src/prefs/cmds.rs index e8f24b18d1..b3ff5d807f 100644 --- a/crates/engine-core/src/prefs/cmds.rs +++ b/crates/engine-core/src/prefs/cmds.rs @@ -1,3 +1,4 @@ +use crate::color_cmds::ColorExt; use super::customize::{keyboard_shortcuts, menus}; use super::validate::{SECTIONS, get_path, keyed}; use super::{CommandSpec, EngineError, Map, Result, Session, ToolbarCustomization, Value, json}; @@ -31,29 +32,29 @@ fn prefs_set(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`")); } // All or nothing: validate against a scratch copy first. - let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone()); + let (saved_prefs, saved_color) = (s.prefs().clone(), s.color().settings.clone()); let mut color_changed = false; for (path, v) in &changes { match super::saved::set_pref(s, path, v.clone(), false) { Ok(touched) => color_changed |= touched, Err(e) => { s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; + s.color_mut().settings = saved_color; return Err(bad(cmd, e)); } } } - if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) { + if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color().settings) { s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; + s.color_mut().settings = saved_color; return Err(bad(cmd, e)); } // `colorSettings.blendTextGamma` and `spotDotGain` live in the compositor too, as // `edit.colorSettings` sets them. Process-wide: only a colour change moves them, so another // session's values survive this one's unrelated preferences. if color_changed { - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - photocraft_compose::multichannel::set_spot_dot_gain(s.color.settings.spot_dot_gain); + photocraft_compose::psblend::set_text_gamma(s.color().settings.blend_text_gamma); + photocraft_compose::multichannel::set_spot_dot_gain(s.color().settings.spot_dot_gain); } s.apply_prefs(); let view = super::saved::prefs_view(s); @@ -72,7 +73,7 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result { } } match path { - Some("colorSettings") => s.color.settings = Default::default(), + Some("colorSettings") => s.color_mut().settings = Default::default(), // One colour setting: `Preferences` has no `colorSettings`, so take the default // from `ColorSettings` and route it like `prefs.set` does. Some(path) if path.starts_with("colorSettings.") => { @@ -82,7 +83,7 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result { super::saved::set_pref(s, path, def, true).map_err(|e| bad("prefs.reset", e))?; } None => { - s.color.settings = Default::default(); + s.color_mut().settings = Default::default(); s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?; } Some(path) => { @@ -93,8 +94,8 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result { } s.prefs.edit(|_| ()); if path.is_none_or(|path| path == "colorSettings" || path.starts_with("colorSettings.")) { - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - photocraft_compose::multichannel::set_spot_dot_gain(s.color.settings.spot_dot_gain); + photocraft_compose::psblend::set_text_gamma(s.color().settings.blend_text_gamma); + photocraft_compose::multichannel::set_spot_dot_gain(s.color().settings.spot_dot_gain); } s.apply_prefs(); if path.is_some_and(|path| keyed(path).is_some()) { diff --git a/crates/engine-core/src/prefs/saved.rs b/crates/engine-core/src/prefs/saved.rs index 7bd0426ab9..f4c903b41f 100644 --- a/crates/engine-core/src/prefs/saved.rs +++ b/crates/engine-core/src/prefs/saved.rs @@ -2,6 +2,8 @@ //! preset libraries ([`SavedPrefs`]), how it is read, and the session methods that move it in and //! out. +use crate::presets::PresetsExt; +use crate::color_cmds::ColorExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -184,9 +186,9 @@ impl SavedPrefsExt for Session { fn prefs_value(&self) -> Value { let mut v = self.prefs().to_json(); if let Value::Object(m) = &mut v { - m.insert("colorSettings".into(), serde_json::to_value(&self.color.settings).unwrap_or(Value::Null)); + m.insert("colorSettings".into(), serde_json::to_value(&self.color().settings).unwrap_or(Value::Null)); m.insert("version".into(), json!(PREFS_VERSION)); - m.insert("presets".into(), self.presets.to_json(self)); + m.insert("presets".into(), self.presets().to_json(self)); } v } @@ -198,7 +200,7 @@ impl SavedPrefsExt for Session { } fn saved_prefs(&self) -> SavedPrefs { - SavedPrefs { prefs: self.prefs().clone(), color_settings: self.color.settings.clone(), presets: self.presets.to_json(self) } + SavedPrefs { prefs: self.prefs().clone(), color_settings: self.color().settings.clone(), presets: self.presets().to_json(self) } } fn set_saved_prefs(&mut self, saved: SavedPrefs) -> Vec { @@ -208,16 +210,16 @@ impl SavedPrefsExt for Session { // or by a 64-bit build; a hand-edited 0) loads as the nearest value it does. Otherwise // Apply from another Preferences tab, which validates every value, would reject it. prefs.performance.effect_cache_mb = accepted_effect_cache_mb(prefs.performance.effect_cache_mb, SMALL_ADDRESS_SPACE); - self.color.settings = color_settings; + self.color_mut().settings = color_settings; // A number outside 0..MAX reads, but `validate_settings` would then refuse every later // Color Settings edit: reset it like an unreadable value. - let gain = self.color.settings.spot_dot_gain; + let gain = self.color().settings.spot_dot_gain; if !(gain.is_finite() && (0.0..=photocraft_compose::multichannel::MAX_SPOT_DOT_GAIN).contains(&gain)) { invalid.push(InvalidPref { keys: vec!["colorSettings".into(), "spotDotGain".into()], value: json!(gain) }); - self.color.settings.spot_dot_gain = photocraft_compose::multichannel::SPOT_DOT_GAIN; + self.color_mut().settings.spot_dot_gain = photocraft_compose::multichannel::SPOT_DOT_GAIN; } - photocraft_compose::psblend::set_text_gamma(self.color.settings.blend_text_gamma); - photocraft_compose::multichannel::set_spot_dot_gain(self.color.settings.spot_dot_gain); + photocraft_compose::psblend::set_text_gamma(self.color().settings.blend_text_gamma); + photocraft_compose::multichannel::set_spot_dot_gain(self.color().settings.spot_dot_gain); self.prefs.edit(|p| *p = prefs); self.load_presets_json(presets); self.apply_prefs(); @@ -229,7 +231,7 @@ impl SavedPrefsExt for Session { pub(super) fn prefs_view(s: &Session) -> Value { let mut v = s.prefs().to_json(); if let Value::Object(m) = &mut v { - m.insert("colorSettings".into(), serde_json::to_value(&s.color.settings).unwrap_or(Value::Null)); + m.insert("colorSettings".into(), serde_json::to_value(&s.color().settings).unwrap_or(Value::Null)); } // Old clients read the single-theme preference: the theme the appearance mode shows. if let Some(interface) = v.get_mut("interface").and_then(Value::as_object_mut) { @@ -247,7 +249,7 @@ pub(super) fn set_pref(s: &mut Session, path: &str, value: Value, validate_color if let Some(rest) = path.strip_prefix("colorSettings").filter(|r| r.is_empty() || r.strip_prefix('.').is_some_and(|c| c.split('.').all(|part| !part.is_empty()))) { - let mut cur = serde_json::to_value(&s.color.settings).map_err(|e| e.to_string())?; + let mut cur = serde_json::to_value(&s.color().settings).map_err(|e| e.to_string())?; let rest = rest.trim_start_matches('.'); if rest.is_empty() { cur = value; @@ -258,7 +260,7 @@ pub(super) fn set_pref(s: &mut Session, path: &str, value: Value, validate_color if validate_color { crate::color_cmds::validate_settings(&next)?; } - s.color.settings = next; + s.color_mut().settings = next; s.prefs.edit(|_| ()); return Ok(true); } diff --git a/crates/engine-core/src/prefs/store.rs b/crates/engine-core/src/prefs/store.rs index 10194488c8..f27efc0d6b 100644 --- a/crates/engine-core/src/prefs/store.rs +++ b/crates/engine-core/src/prefs/store.rs @@ -47,11 +47,11 @@ impl PrefsStore { } } -/// The preferences file format written by [`Session::prefs_value`]. 2: Use Shift Key for Tool +/// The preferences file format written by [`SavedPrefsExt::prefs_value`](crate::prefs::SavedPrefsExt::prefs_value). 2: Use Shift Key for Tool /// Switch stored as chosen (before, a stored `false` was the old default; see `load_prefs_json`). pub const PREFS_VERSION: u64 = 2; -/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown +/// A saved preference [`SavedPrefsExt::load_prefs_json`](crate::prefs::SavedPrefsExt::load_prefs_json) couldn't read (a wrong type, an unknown /// choice) and left at its default. #[derive(Clone, Debug, PartialEq)] pub struct InvalidPref { @@ -98,7 +98,7 @@ where } } -/// One section of a preferences file (`performance`, …) read as [`Session::load_prefs_json`] +/// One section of a preferences file (`performance`, …) read as [`SavedPrefsExt::load_prefs_json`](crate::prefs::SavedPrefsExt::load_prefs_json) /// reads it: a value of the wrong type keeps its default and the rest still loads (#6611). /// Startup reads the graphics settings with it before a session exists. pub fn read_section(v: Value) -> T diff --git a/crates/engine-core/src/prefs/tests.rs b/crates/engine-core/src/prefs/tests.rs index 9eada16482..0b286704a9 100644 --- a/crates/engine-core/src/prefs/tests.rs +++ b/crates/engine-core/src/prefs/tests.rs @@ -1,3 +1,5 @@ +use crate::prefs::SavedPrefsExt; +use crate::color_cmds::ColorExt; use super::*; #[test] @@ -275,10 +277,10 @@ fn reset_one_colour_setting() { let mut s = session(); s.execute("prefs.set", json!({"values": {"colorSettings.bpc": false, "colorSettings.workingRgb": "display-p3"}})).unwrap(); assert_eq!(s.execute("prefs.reset", json!({"path": "colorSettings.bpc"})).unwrap(), json!(true)); - assert!(s.color.settings.bpc); - assert_eq!(s.color.settings.working_rgb, "display-p3", "other colour settings are untouched"); + assert!(s.color().settings.bpc); + assert_eq!(s.color().settings.working_rgb, "display-p3", "other colour settings are untouched"); s.execute("prefs.reset", json!({"path": "colorSettings.workingRgb"})).unwrap(); - assert_eq!(s.color.settings, crate::color_cmds::ColorSettings::default()); + assert_eq!(s.color().settings, crate::color_cmds::ColorSettings::default()); assert!(s.execute("prefs.reset", json!({"path": "colorSettings.notAField"})).is_err()); } @@ -402,8 +404,8 @@ fn json_round_trip_tolerates_unknown_and_missing_keys() { let mut t = crate::session(); t.load_prefs_json(&text).unwrap(); assert_eq!(t.prefs(), s.prefs()); - assert_eq!(t.color.settings.working_rgb, "display-p3"); - assert_eq!(t.color.settings.policy_rgb, crate::color_cmds::Policy::Convert); + assert_eq!(t.color().settings.working_rgb, "display-p3"); + assert_eq!(t.color().settings.policy_rgb, crate::color_cmds::Policy::Convert); // Older/newer files: unknown keys ignored, missing ones default. let mut u = crate::session(); u.load_prefs_json(r#"{"general": {"beepWhenDone": true, "futureThing": 1}, "someNewSection": {}}"#).unwrap(); @@ -1154,7 +1156,7 @@ fn a_wrongly_typed_section_or_colour_setting_resets_only_that_part() { .unwrap(); assert_eq!(s.prefs().general, General::default()); assert_eq!(s.prefs().performance.history_states, 20); - assert_eq!(s.color.settings.working_rgb, "display-p3", "the rest of the colour settings load"); + assert_eq!(s.color().settings.working_rgb, "display-p3", "the rest of the colour settings load"); let paths: Vec = invalid.iter().map(InvalidPref::path).collect(); assert_eq!(paths, ["general", "colorSettings.askOnMismatch"]); // A valid file reports nothing; one that isn't an object still fails as a whole. diff --git a/crates/engine-core/src/preset_store.rs b/crates/engine-core/src/preset_store.rs index 8fbdb01003..840a2f4497 100644 --- a/crates/engine-core/src/preset_store.rs +++ b/crates/engine-core/src/preset_store.rs @@ -17,20 +17,20 @@ //! preview ([`GrayTile::preview`], at most [`PREVIEW_SIDE`] px), which the Brushes panel and the //! picker draw. Opening the store reads previews, never a full tip, and once a group is written //! its presets drop their bitmaps the same way. A tip is decoded when its brush is used -//! ([`Session::load_brush_tips`]: picking a preset, a stroke naming one, exporting), and kept in a +//! ([`PresetStoreExt::load_brush_tips`](crate::preset_store::PresetStoreExt::load_brush_tips): picking a preset, a stroke naming one, exporting), and kept in a //! byte-capped least-recently-used cache ([`TIP_CACHE_BYTES`]), so memory grows with the brushes //! in use, not with the size of the library. Stores written before #1843 have no previews: their //! tips are decoded once at the next start, a few at a time, and the groups rewritten. //! //! Built-in presets are never written (they are regenerated on start). The store syncs after -//! every command that changes the brush presets ([`Session::brush_presets_changed`]); only groups +//! every command that changes the brush presets ([`PresetStoreExt::brush_presets_changed`](crate::preset_store::PresetStoreExt::brush_presets_changed)); only groups //! whose content changed are rewritten. Every write is atomic (temp file + rename) and bounded //! ([`MAX_GROUP_BYTES`], [`MAX_TIP_BYTES`], [`MAX_STORE_BYTES`]); corrupt or oversized files are //! skipped with a warning and left on disk, never a panic. //! //! A [`Session`] has no store by default, so headless CLI/MCP sessions and tests never write. //! The desktop app opens the store on a background thread ([`open`]) and attaches it with -//! [`Session::attach_preset_store`] once loaded, so the first frame never waits for it. The web +//! [`PresetStoreExt::attach_preset_store`](crate::preset_store::PresetStoreExt::attach_preset_store) once loaded, so the first frame never waits for it. The web //! app hydrates a bounded memory backend from IndexedDB before accepting edits and commits //! changes asynchronously. Gradient presets, including imported `.grd` groups, are small and persist with //! the preferences document (`presets.gradients`). @@ -47,6 +47,7 @@ //! Legacy and corrupt data are preserved; an existing index is authoritative even when corrupt. //! A failed migration leaves the legacy library usable and retries at the next startup. +use crate::actions_cmds::ActionsExt; use std::collections::{BTreeMap, HashMap, HashSet}; use std::io::Read; use std::sync::{Arc, Mutex, PoisonError}; @@ -1198,31 +1199,31 @@ impl PresetStoreExt for Session { // Otherwise in-memory actions (created before the store finished loading) win on name and // disk-only names are appended. An empty session takes the disk list and does not rewrite // it, unless loading moved stored ids to names: that is written once. - if std::mem::take(&mut self.actions.replaced_before_attachment) { + if std::mem::take(&mut self.actions_mut().replaced_before_attachment) { // The command replaced the action shortcuts too: the stored ids' keys have no action. name_id_shortcuts(self, &[]); - } else if self.actions.list.actions().is_empty() && self.actions.list.sets().is_empty() { - self.actions.list.replace(disk); + } else if self.actions().list.actions().is_empty() && self.actions().list.sets().is_empty() { + self.actions_mut().list.replace(disk); name_id_shortcuts(self, &action_ids); - let rev = self.actions.list.revision(); + let rev = self.actions().list.revision(); if let Some(st) = self.preset_store_mut() { st.actions_rev = rev; } if !action_ids.is_empty() { - self.actions.list.touch(); + self.actions_mut().list.touch(); } } else { name_id_shortcuts(self, &action_ids); let ActionsFile { actions, sets, .. } = disk.to_file(); for action in actions { // A name the session already has is refused: the session's wins. - let _ = self.actions.list.push(action); + let _ = self.actions_mut().list.push(action); } for set in sets { - let _ = self.actions.list.new_set(&set); + let _ = self.actions_mut().list.new_set(&set); } // The merged list differs from the file even when nothing was added. - self.actions.list.touch(); + self.actions_mut().list.touch(); } self.brush_presets_changed(); self.sync_preset_store(); @@ -1250,7 +1251,7 @@ impl PresetStoreExt for Session { self.tools.brush_changed(); } } - st.sync_actions(&self.actions.list); + st.sync_actions(&self.actions().list); st.sync_patterns(&self.patterns); if let Ok(slot) = self.slot_mut::>() { *slot = Some(st); diff --git a/crates/engine-core/src/preset_store/tests.rs b/crates/engine-core/src/preset_store/tests.rs index 9c7723e6f8..64f7ead278 100644 --- a/crates/engine-core/src/preset_store/tests.rs +++ b/crates/engine-core/src/preset_store/tests.rs @@ -1,3 +1,5 @@ +use crate::preset_store::PresetStoreExt; +use crate::actions_cmds::ActionsExt; use super::*; use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; use serde_json::json; @@ -812,9 +814,9 @@ fn stored_action_ids_move_to_names_on_load() { prefs.shortcuts.insert(format!("actions.playById:{id}"), "F6".into()); }); s.attach_preset_store(open(Box::new(mem.clone()))); - let names: Vec<&str> = s.actions.list.actions().iter().map(|action| action.name.as_str()).collect(); + let names: Vec<&str> = s.actions().list.actions().iter().map(|action| action.name.as_str()).collect(); assert_eq!(names, ["Same", "Same 2", "Caller"]); - assert_eq!(s.actions.list.actions()[2].steps[0].params, json!({"action": "Same 2"})); + assert_eq!(s.actions().list.actions()[2].steps[0].params, json!({"action": "Same 2"})); assert_eq!(s.prefs().shortcuts.get("actions.play:Same 2").map(String::as_str), Some("F6")); assert!(!s.prefs().shortcuts.keys().any(|key| key.starts_with("actions.playById:"))); let saved = String::from_utf8(mem.files.lock().unwrap()[ACTIONS_FILE].clone()).unwrap(); diff --git a/crates/engine-core/src/presets/clone_source.rs b/crates/engine-core/src/presets/clone_source.rs index cbf690ab6b..d82bf4c4e9 100644 --- a/crates/engine-core/src/presets/clone_source.rs +++ b/crates/engine-core/src/presets/clone_source.rs @@ -11,6 +11,7 @@ //! A slot remembers the document its source was set in, so ⌥-clicking in one open document and //! painting in another clones across them, as in Photoshop. +use crate::presets::PresetsExt; use photocraft_doc::{DocId, LayerId}; use photocraft_geom::Rect; use photocraft_paint::retouch::Region; @@ -232,7 +233,7 @@ pub fn remember_mapping(s: &mut Session, p: &Value, map: &Mapping) { if !uses_slot(p) { return; } - let slot = s.presets.clone.active_mut(); + let slot = s.presets_mut().clone.active_mut(); let anchor = [map.anchor.0, map.anchor.1]; slot.last_anchor = Some(anchor); if p.get("aligned").and_then(Value::as_bool).unwrap_or(true) { @@ -249,7 +250,7 @@ pub fn resolve(s: &Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<( let offset = input_point(p, "offset", cmd)?; let anchor_param = input_point(p, "anchor", cmd)?.map(|a| (a[0], a[1])); let aligned = p.get("aligned").and_then(Value::as_bool).unwrap_or(true); - let slot = s.presets.clone.active().clone(); + let slot = s.presets().clone.active().clone(); let explicit_tf = ["scale", "rotation", "flipH", "flipV"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); let m = if explicit_tf { let sc = p @@ -361,7 +362,7 @@ pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option) -> fn index(s: &Session, p: &Value, cmd: &str) -> Result { let i = match p.get("index") { Some(v) if !v.is_null() => v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(cmd, "index must be a source-slot number"))?, - _ => s.presets.clone.active, + _ => s.presets().clone.active, }; if i < SLOTS { Ok(i) } else { Err(bad(cmd, format!("index {i} out of range (0..{SLOTS})"))) } } @@ -393,14 +394,14 @@ fn valid_point(point: [f64; 2]) -> bool { /// Describe a slot with both its stable document identity and its current open-tab index. fn slot_json(s: &Session, i: usize) -> Value { - let slot = &s.presets.clone.slots[i.min(SLOTS - 1)]; + let slot = &s.presets().clone.slots[i.min(SLOTS - 1)]; let document = slot.open_document().and_then(|id| s.documents().iter().position(|st| st.doc.id == id)); slot.to_json(i, document) } /// Report all slot geometry and stable identities with their current open-document indexes. fn list(s: &mut Session, _: &Value) -> Result { - let c = &s.presets.clone; + let c = &s.presets().clone; Ok( json!({"active": c.active, "sources": (0..SLOTS).map(|i| slot_json(s, i)).collect::>(), "overlay": serde_json::to_value(&c.overlay).unwrap_or(Value::Null)}), ) @@ -411,7 +412,7 @@ fn select(s: &mut Session, p: &Value) -> Result { const CMD: &str = "cloneSource.select"; p.get("index").filter(|v| !v.is_null()).ok_or_else(|| bad(CMD, "missing `index`"))?; let i = index(s, p, CMD)?; - s.presets.clone.active = i; + s.presets_mut().clone.active = i; Ok(slot_json(s, i)) } @@ -437,7 +438,7 @@ fn set(s: &mut Session, p: &Value) -> Result { }; let (document, active_layer) = (doc.map(|st| st.doc.id), doc.and_then(|st| st.active_layer).map(|id| id.0)); // Build the edited slot off to the side so a rejected coordinate or sum is atomic. - let mut slot = s.presets.clone.slots[i].clone(); + let mut slot = s.presets().clone.slots[i].clone(); if let Some([x, y]) = source { // A new sample point re-pairs with the next stroke. slot.source = Some([x, y]); @@ -497,9 +498,9 @@ fn set(s: &mut Session, p: &Value) -> Result { if [slot.source, slot.anchor, slot.last_anchor].into_iter().flatten().any(|p| !valid_point(p)) { return Err(bad(CMD, "the edited clone coordinates exceed their range")); } - s.presets.clone.slots[i] = slot; + s.presets_mut().clone.slots[i] = slot; if p.get("select").and_then(Value::as_bool).unwrap_or(true) { - s.presets.clone.active = i; + s.presets_mut().clone.active = i; } Ok(slot_json(s, i)) } @@ -507,14 +508,14 @@ fn set(s: &mut Session, p: &Value) -> Result { /// Reset scale/rotation/flips while retaining source identity and established pairings. fn reset_transform(s: &mut Session, p: &Value) -> Result { let i = index(s, p, "cloneSource.resetTransform")?; - let slot = &mut s.presets.clone.slots[i]; + let slot = &mut s.presets_mut().clone.slots[i]; (slot.scale, slot.rotation, slot.flip_h, slot.flip_v) = ([100.0, 100.0], 0.0, false, false); Ok(slot_json(s, i)) } /// Update transient overlay appearance without editing image pixels or source geometry. fn overlay(s: &mut Session, p: &Value) -> Result { - let o = &mut s.presets.clone.overlay; + let o = &mut s.presets_mut().clone.overlay; let flag = |k: &str| p.get(k).and_then(Value::as_bool); if let Some(b) = flag("show") { o.show = b; @@ -617,11 +618,11 @@ mod tests { let mut s = crate::session(); s.execute("cloneSource.set", json!({"width": 50, "height": 200})).unwrap(); s.execute("cloneSource.set", json!({"width": 100})).unwrap(); - assert_eq!(s.presets.clone.active().scale, [100.0, 200.0], "unlinked: H stays"); + assert_eq!(s.presets().clone.active().scale, [100.0, 200.0], "unlinked: H stays"); let r = s.execute("cloneSource.set", json!({"linked": true, "width": 150})).unwrap(); assert_eq!((r["width"].as_f64(), r["height"].as_f64(), r["linked"].as_bool()), (Some(150.0), Some(300.0), Some(true))); s.execute("cloneSource.set", json!({"height": 60})).unwrap(); - assert_eq!(s.presets.clone.active().scale, [30.0, 60.0], "linked: W follows H"); + assert_eq!(s.presets().clone.active().scale, [30.0, 60.0], "linked: W follows H"); } #[test] diff --git a/crates/engine-core/src/presets/gradients.rs b/crates/engine-core/src/presets/gradients.rs index 64d6ae63ce..2fb141d78c 100644 --- a/crates/engine-core/src/presets/gradients.rs +++ b/crates/engine-core/src/presets/gradients.rs @@ -5,6 +5,8 @@ //! Photoshop's "Foreground to Background") and transparency stops, both at `0..=1`. Midpoints are //! always 50 %. Built-in colours are our own. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_doc::{Color, Fill, Layer, LayerContent}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -416,32 +418,32 @@ fn tool_preset(s: &Session, p: &Value) -> Result> { return Ok(None); } Ok(Some(if let Some(name) = str_param(p, "gradient") { - let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; - s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)? + let (gi, ii) = find(&s.presets().gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; + s.presets().gradients[gi].items[ii].clone().with_transparency(p, CMD)? } else if p.get("stops").is_some() { GradientPreset::from_params("Custom", p, CMD)? } else { - s.presets.gradient.clone().with_transparency(p, CMD)? + s.presets().gradient.clone().with_transparency(p, CMD)? })) } /// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { if let Some(name) = str_param(p, "preset") { - let (gi, ii) = find(&s.presets.gradients, name, str_param(p, "group")) + let (gi, ii) = find(&s.presets().gradients, name, str_param(p, "group")) .ok_or_else(|| bad(cmd, format!("no gradient preset \"{name}\" (see gradient.presets.list)")))?; - return Ok(s.presets.gradients[gi].items[ii].clone()); + return Ok(s.presets().gradients[gi].items[ii].clone()); } if p.get("stops").is_some() { return GradientPreset::from_params(str_param(p, "name").unwrap_or("Custom"), p, cmd); } - Ok(s.presets.gradient.clone()) + Ok(s.presets().gradient.clone()) } fn list(s: &mut Session, _: &Value) -> Result { let groups: Vec = - s.presets.gradients.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(GradientPreset::to_json).collect::>()})).collect(); - Ok(json!({"groups": groups, "current": s.presets.gradient.to_json()})) + s.presets().gradients.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(GradientPreset::to_json).collect::>()})).collect(); + Ok(json!({"groups": groups, "current": s.presets().gradient.to_json()})) } fn active_gradient_fill(s: &Session) -> Option { @@ -467,8 +469,8 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD_SELECT, "the selected shape layer is locked")); } } - s.presets.gradient = g.clone(); - s.presets_changed(); + s.presets_mut().gradient = g.clone(); + presets_changed(s); let mut out = json!({"current": g.to_json()}); // Clicking a preset with a shape layer selected fills the shape with it (Photoshop, #5568); // a gradient fill keeps its angle, style, scale and reverse. @@ -642,10 +644,10 @@ pub fn apply_preset_stop(g: &GradientPreset, p: &Value, fg: [f32; 4], bg: [f32; } fn stop(s: &mut Session, p: &Value) -> Result { - let g = apply_preset_stop(&s.presets.gradient, p, s.tools.foreground, s.tools.background, STOP)?; - s.presets.gradient = g; - s.presets_changed(); - Ok(json!({"current": s.presets.gradient.to_json()})) + let g = apply_preset_stop(&s.presets().gradient, p, s.tools.foreground, s.tools.background, STOP)?; + s.presets_mut().gradient = g; + presets_changed(s); + Ok(json!({"current": s.presets().gradient.to_json()})) } fn apply(s: &mut Session, p: &Value) -> Result { @@ -668,19 +670,19 @@ fn apply(s: &mut Session, p: &Value) -> Result { fn new_preset(s: &mut Session, p: &Value) -> Result { const CMD: &str = "gradient.presets.new"; - let mut g = if p.get("stops").is_some() { GradientPreset::from_params("", p, CMD)? } else { s.presets.gradient.clone() }; - g.name = unique_name(&s.presets.gradients, str_param(p, "name").unwrap_or("Custom")); - let gi = group_index(&mut s.presets.gradients, str_param(p, "group")); - s.presets.gradients[gi].items.push(g.clone()); - let group = s.presets.gradients[gi].name.clone(); - s.presets_changed(); + let mut g = if p.get("stops").is_some() { GradientPreset::from_params("", p, CMD)? } else { s.presets().gradient.clone() }; + g.name = unique_name(&s.presets().gradients, str_param(p, "name").unwrap_or("Custom")); + let gi = group_index(&mut s.presets_mut().gradients, str_param(p, "group")); + s.presets_mut().gradients[gi].items.push(g.clone()); + let group = s.presets().gradients[gi].name.clone(); + presets_changed(s); Ok(json!({"name": g.name, "group": group})) } fn edit(s: &mut Session, p: &Value) -> Result { let action = req_str(p, "action", "gradient.presets.edit")?.to_string(); - let r = edit_groups(&mut s.presets.gradients, &action, p, "gradient.presets.edit")?; - s.presets_changed(); + let r = edit_groups(&mut s.presets_mut().gradients, &action, p, "gradient.presets.edit")?; + presets_changed(s); Ok(r) } @@ -689,14 +691,14 @@ fn reset(s: &mut Session, p: &Value) -> Result { let mut b = builtin(); if append { for g in &mut b { - g.name = unique_group(&s.presets.gradients, &g.name); + g.name = unique_group(&s.presets().gradients, &g.name); } - s.presets.gradients.extend(b); + s.presets_mut().gradients.extend(b); } else { - s.presets.gradients = b; + s.presets_mut().gradients = b; } - s.presets_changed(); - Ok(json!({"groups": s.presets.gradients.len()})) + presets_changed(s); + Ok(json!({"groups": s.presets().gradients.len()})) } pub(crate) fn unique_group(groups: &[Group], base: &str) -> String { diff --git a/crates/engine-core/src/presets/patterns.rs b/crates/engine-core/src/presets/patterns.rs index 9644af6bb0..142142d362 100644 --- a/crates/engine-core/src/presets/patterns.rs +++ b/crates/engine-core/src/presets/patterns.rs @@ -4,6 +4,8 @@ //! Groups hold pattern **ids**. Library patterns that are in no group (newly defined or imported) //! are shown in a trailing "Patterns" group; ids whose pattern was deleted are dropped. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_doc::{Fill, LayerContent}; use serde_json::{Value, json}; @@ -26,13 +28,13 @@ pub fn builtin_groups() -> Vec> { pub fn sync(s: &mut Session) { let lib = &s.patterns.items; let in_lib = |id: &String| lib.iter().any(|p| &p.id == id); - let groups = &s.presets.pattern_groups; + let groups = &s.presets().pattern_groups; let stale = groups.iter().any(|g| !g.items.iter().all(in_lib)); let loose: Vec = lib.iter().map(|p| &p.id).filter(|id| !groups.iter().any(|g| g.items.contains(id))).cloned().collect(); if !stale && loose.is_empty() { return; } - let groups = &mut s.presets.pattern_groups; + let groups = &mut s.presets_mut().pattern_groups; for g in groups.iter_mut() { g.items.retain(in_lib); } @@ -46,14 +48,14 @@ pub fn sync(s: &mut Session) { /// The selected pattern, if it is still in the library. pub fn current(s: &Session) -> Option<&photocraft_doc::Pattern> { - let id = s.presets.pattern.as_deref()?; + let id = s.presets().pattern.as_deref()?; s.patterns.items.iter().find(|p| p.id == id) } fn list(s: &mut Session, _: &Value) -> Result { sync(s); let groups: Vec = s - .presets + .presets() .pattern_groups .iter() .map(|g| { @@ -83,7 +85,7 @@ fn active_pattern_fill(s: &Session) -> Option { fn select(s: &mut Session, p: &Value) -> Result { const CMD: &str = "pattern.presets.select"; let pat = pattern_key(s, p, CMD)?; - s.presets.pattern = Some(pat.id.clone()); + s.presets_mut().pattern = Some(pat.id.clone()); let mut out = json!({"pattern": pat.id, "name": pat.display_name()}); if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true) && let Some(id) = active_pattern_fill(s) @@ -115,13 +117,13 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { let id = r.get("pattern").and_then(Value::as_str).unwrap_or_default().to_string(); sync(s); if let Some(g) = str_param(p, "group") { - for gr in &mut s.presets.pattern_groups { + for gr in &mut s.presets_mut().pattern_groups { gr.items.retain(|x| *x != id); } - let gi = group_index(&mut s.presets.pattern_groups, Some(g)); - s.presets.pattern_groups[gi].items.push(id.clone()); + let gi = group_index(&mut s.presets_mut().pattern_groups, Some(g)); + s.presets_mut().pattern_groups[gi].items.push(id.clone()); } - s.presets_changed(); + presets_changed(s); Ok(json!({"pattern": id})) } @@ -164,8 +166,8 @@ fn edit(s: &mut Session, p: &Value) -> Result { "deleteGroup" => { // Deleting a folder deletes its patterns, as in Photoshop. let g = req_str(p, "group", CMD)?; - let i = s.presets.pattern_groups.iter().position(|x| x.name == g).ok_or_else(|| bad(CMD, format!("no group \"{g}\"")))?; - let gone = s.presets.pattern_groups.remove(i); + let i = s.presets().pattern_groups.iter().position(|x| x.name == g).ok_or_else(|| bad(CMD, format!("no group \"{g}\"")))?; + let gone = s.presets_mut().pattern_groups.remove(i); s.patterns.items.retain(|q| !gone.items.contains(&q.id)); json!({"group": g, "deleted": gone.items.len()}) } @@ -174,12 +176,12 @@ fn edit(s: &mut Session, p: &Value) -> Result { let id = crate::pattern_cmds::resolve_id(s, key).ok_or_else(|| bad(CMD, format!("no pattern \"{key}\"")))?; let mut q = p.clone(); q["preset"] = json!(id); - edit_groups(&mut s.presets.pattern_groups, "move", &q, CMD)? + edit_groups(&mut s.presets_mut().pattern_groups, "move", &q, CMD)? } - a => edit_groups(&mut s.presets.pattern_groups, a, p, CMD)?, + a => edit_groups(&mut s.presets_mut().pattern_groups, a, p, CMD)?, }; sync(s); - s.presets_changed(); + presets_changed(s); Ok(r) } diff --git a/crates/engine-core/src/presets/shapes.rs b/crates/engine-core/src/presets/shapes.rs index 7b4c99edb3..a376ab3d24 100644 --- a/crates/engine-core/src/presets/shapes.rs +++ b/crates/engine-core/src/presets/shapes.rs @@ -6,6 +6,8 @@ //! (a circle) and `!` before `M`/`O` to subtract that subpath (holes). Shapes defined with Edit › //! Define Custom Shape appear in a trailing "Custom Shapes" group. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_doc::vector::{Knot, Path, PathOp, Subpath}; use photocraft_geom::{Affine, Point, Rect}; use serde::{Deserialize, Serialize}; @@ -285,7 +287,7 @@ pub fn builtin() -> Vec> { /// Every shape the panel shows: the preset groups plus Define Custom Shape results. pub fn all_groups(s: &Session) -> Vec> { - let mut g = s.presets.shapes.clone(); + let mut g = s.presets().shapes.clone(); let custom: Vec = s.edit_state.custom_shapes.iter().map(|c| ShapePreset { name: c.name.clone(), path: c.path.clone(), id: None }).collect(); if !custom.is_empty() { g.push(Group::new(CUSTOM_GROUP, custom)); @@ -304,7 +306,7 @@ pub(crate) fn filter_path(s: &Session, p: &Value) -> Result { const CMD: &str = "filter.blur.shapeBlur"; if let Some(value) = p.get("shapeId") { let id = value.as_str().filter(|id| !id.is_empty()).ok_or_else(|| bad(CMD, "shapeId must be a nonempty string"))?; - let mut matches = s.presets.shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id)); + let mut matches = s.presets().shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id)); let found = matches.next().ok_or_else(|| bad(CMD, format!("no installed shape with id \"{id}\"")))?; // Reimporting an unchanged library adds another display name for the same asset. // Different geometry under one ID is ambiguous and must not pick the first match. @@ -411,7 +413,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { Some(Value::String(id)) if !id.is_empty() => Some(id.clone()), _ => return Err(bad(CMD, "id must be a nonempty string")), }; - if id.as_deref().is_some_and(|id| s.presets.shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(id))) { + if id.as_deref().is_some_and(|id| s.presets().shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(id))) { return Err(bad(CMD, "a shape with this id is already installed")); } let path = match p.get("path") { @@ -428,11 +430,11 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { } // Normalise into the 100 box so thumbnails and placing don't depend on where it was drawn. let path = fit(&path, [0.0, 0.0, 100.0, 100.0], true); - let name = unique_name(&s.presets.shapes, str_param(p, "name").unwrap_or("Shape")); - let gi = group_index(&mut s.presets.shapes, str_param(p, "group")); - let group = s.presets.shapes[gi].name.clone(); - s.presets.shapes[gi].items.push(ShapePreset { name: name.clone(), path, id }); - s.presets_changed(); + let name = unique_name(&s.presets().shapes, str_param(p, "name").unwrap_or("Shape")); + let gi = group_index(&mut s.presets_mut().shapes, str_param(p, "group")); + let group = s.presets().shapes[gi].name.clone(); + s.presets_mut().shapes[gi].items.push(ShapePreset { name: name.clone(), path, id }); + presets_changed(s); Ok(json!({"name": name, "group": group})) } @@ -442,7 +444,7 @@ fn edit(s: &mut Session, p: &Value) -> Result { // Define Custom Shape results live in the edit state; rename/delete them there. let custom = |s: &Session, n: &str| { str_param(p, "group").is_none_or(|g| g == CUSTOM_GROUP) - && find(&s.presets.shapes, n, None).is_none() + && find(&s.presets().shapes, n, None).is_none() && s.edit_state.custom_shapes.iter().any(|c| c.name == n) }; let r = match action.as_str() { @@ -458,9 +460,9 @@ fn edit(s: &mut Session, p: &Value) -> Result { s.edit_state.custom_shapes.retain(|c| c.name != n); json!({"deleted": 1}) } - a => edit_groups(&mut s.presets.shapes, a, p, CMD)?, + a => edit_groups(&mut s.presets_mut().shapes, a, p, CMD)?, }; - s.presets_changed(); + presets_changed(s); Ok(r) } @@ -468,14 +470,14 @@ fn reset(s: &mut Session, p: &Value) -> Result { let mut b = builtin(); if p.get("append").and_then(Value::as_bool).unwrap_or(false) { for g in &mut b { - g.name = super::gradients::unique_group(&s.presets.shapes, &g.name); + g.name = super::gradients::unique_group(&s.presets().shapes, &g.name); } - s.presets.shapes.extend(b); + s.presets_mut().shapes.extend(b); } else { - s.presets.shapes = b; + s.presets_mut().shapes = b; } - s.presets_changed(); - Ok(json!({"groups": s.presets.shapes.len()})) + presets_changed(s); + Ok(json!({"groups": s.presets().shapes.len()})) } pub fn specs() -> Vec { diff --git a/crates/engine-core/src/presets/shapes/csh.rs b/crates/engine-core/src/presets/shapes/csh.rs index 290d1f0367..fbca925e48 100644 --- a/crates/engine-core/src/presets/shapes/csh.rs +++ b/crates/engine-core/src/presets/shapes/csh.rs @@ -1,5 +1,7 @@ //! Import a complete custom-shape set before changing the persistent library. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; @@ -68,8 +70,8 @@ fn import(s: &mut Session, p: &Value) -> Result { Ok((group, items)) }, |s, (group, mut items)| { - let group = super::super::gradients::unique_group(&s.presets.shapes, &group); - let mut taken: HashSet = s.presets.shapes.iter().flat_map(|g| g.items.iter().map(|i| i.name.clone())).collect(); + let group = super::super::gradients::unique_group(&s.presets().shapes, &group); + let mut taken: HashSet = s.presets().shapes.iter().flat_map(|g| g.items.iter().map(|i| i.name.clone())).collect(); taken.extend(s.edit_state.custom_shapes.iter().map(|c| c.name.clone())); let mut suffixes: HashMap = HashMap::new(); for item in &mut items { @@ -82,8 +84,8 @@ fn import(s: &mut Session, p: &Value) -> Result { } let names: Vec = items.iter().map(|i| i.name.clone()).collect(); let result = json!({"group": group, "count": items.len(), "names": names}); - s.presets.shapes.push(Group::new(&group, items)); - s.presets_changed(); + s.presets_mut().shapes.push(Group::new(&group, items)); + presets_changed(s); Ok(result) }, ) diff --git a/crates/engine-core/src/presets/styles.rs b/crates/engine-core/src/presets/styles.rs index e2ae82e52d..67cf718139 100644 --- a/crates/engine-core/src/presets/styles.rs +++ b/crates/engine-core/src/presets/styles.rs @@ -5,6 +5,8 @@ //! The built-in groups are our own designs, built from the same effect params as //! `layer.layerStyle.*`. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_doc::{Document, Effect, Layer, Pattern, Size}; use photocraft_geom::Rect; @@ -149,13 +151,13 @@ pub fn builtin() -> Vec> { pub fn find_style<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<&'a StylePreset> { let name = req_str(p, "preset", cmd)?; - let (gi, ii) = find(&s.presets.styles, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no style \"{name}\" (see style.presets.list)")))?; - Ok(&s.presets.styles[gi].items[ii]) + let (gi, ii) = find(&s.presets().styles, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no style \"{name}\" (see style.presets.list)")))?; + Ok(&s.presets().styles[gi].items[ii]) } fn list(s: &mut Session, _: &Value) -> Result { let groups: Vec = - s.presets.styles.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(StylePreset::to_json).collect::>()})).collect(); + s.presets().styles.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(StylePreset::to_json).collect::>()})).collect(); Ok(json!({"groups": groups})) } @@ -269,7 +271,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { }) .transpose()?; let style = StylePreset { - name: unique_name(&s.presets.styles, str_param(p, "name").unwrap_or("Style")), + name: unique_name(&s.presets().styles, str_param(p, "name").unwrap_or("Style")), effects: match listed { Some(fx) => fx, None => { @@ -284,17 +286,17 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { fill_opacity: p.get("fillOpacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.fill_opacity)), opacity: p.get("opacity").and_then(Value::as_f64).map(|v| (v / 100.0).clamp(0.0, 1.0) as f32).or_else(|| with_blend.then_some(l.opacity)), }; - let gi = group_index(&mut s.presets.styles, str_param(p, "group")); - let out = json!({"name": style.name, "group": s.presets.styles[gi].name, "effects": style.effects.len()}); - s.presets.styles[gi].items.push(style); - s.presets_changed(); + let gi = group_index(&mut s.presets_mut().styles, str_param(p, "group")); + let out = json!({"name": style.name, "group": s.presets().styles[gi].name, "effects": style.effects.len()}); + s.presets_mut().styles[gi].items.push(style); + presets_changed(s); Ok(out) } fn edit(s: &mut Session, p: &Value) -> Result { let action = req_str(p, "action", "style.presets.edit")?.to_string(); - let r = edit_groups(&mut s.presets.styles, &action, p, "style.presets.edit")?; - s.presets_changed(); + let r = edit_groups(&mut s.presets_mut().styles, &action, p, "style.presets.edit")?; + presets_changed(s); Ok(r) } @@ -302,14 +304,14 @@ fn reset(s: &mut Session, p: &Value) -> Result { let mut b = builtin(); if p.get("append").and_then(Value::as_bool).unwrap_or(false) { for g in &mut b { - g.name = super::gradients::unique_group(&s.presets.styles, &g.name); + g.name = super::gradients::unique_group(&s.presets().styles, &g.name); } - s.presets.styles.extend(b); + s.presets_mut().styles.extend(b); } else { - s.presets.styles = b; + s.presets_mut().styles = b; } - s.presets_changed(); - Ok(json!({"groups": s.presets.styles.len()})) + presets_changed(s); + Ok(json!({"groups": s.presets().styles.len()})) } /// Swatch for the Styles panel: the style on a rounded square, `size`² RGBA8 (straight alpha, diff --git a/crates/engine-core/src/presets/swatches.rs b/crates/engine-core/src/presets/swatches.rs index 279c6ff481..bb5bd6c8ea 100644 --- a/crates/engine-core/src/presets/swatches.rs +++ b/crates/engine-core/src/presets/swatches.rs @@ -11,6 +11,7 @@ //! [`super::PresetState::to_json`]). The default set is `default_swatches()`. The commands live in //! `crate::swatch_cmds`; the file formats are craft-color's. +use crate::color_cmds::ColorExt; use std::sync::Arc; use craft_cms::{Builtin, Profile, Transform, TransformOptions}; @@ -180,7 +181,7 @@ pub struct SwatchConv { fn working(s: Option<&Session>, mode: ColorMode) -> Arc { let spec = s.map(|s| { - let c = &s.color.settings; + let c = &s.color().settings; match mode { ColorMode::Cmyk => c.working_cmyk.clone(), ColorMode::Grayscale => c.working_gray.clone(), @@ -248,6 +249,7 @@ pub fn hex(c: [f32; 3]) -> String { #[cfg(test)] mod tests { + use crate::presets::PresetsExt; use super::*; use crate::presets::PresetState; @@ -303,7 +305,7 @@ mod tests { #[test] fn a_wide_gamut_working_space_changes_cmyk_but_not_rgb() { let mut s = crate::session(); - s.color.settings.working_rgb = "display-p3".into(); + s.color_mut().settings.working_rgb = "display-p3".into(); let p3 = SwatchConv::new(&s); let srgb = SwatchConv::builtin(); let cmyk = SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0]); @@ -346,7 +348,7 @@ mod tests { ]}]}); let mut s = crate::session(); s.load_presets_json(saved); - let groups = &s.presets.swatches; + let groups = &s.presets().swatches; assert_eq!(groups.len(), 1); assert_eq!(groups[0].name, "Old"); let e = &groups[0].entries; @@ -354,7 +356,7 @@ mod tests { assert_eq!((e[1].color, e[1].kind), (SwatchColor::Lab([50.0, -1.5, 2.25]), SwatchKind::Spot)); assert_eq!(e[2].color, SwatchColor::Book { space: 3, values: [1, 2, 3, 4] }); let mut t = crate::session(); - t.load_presets_json(s.presets.to_json(&s)); - assert_eq!(t.presets.swatches, s.presets.swatches); + t.load_presets_json(s.presets().to_json(&s)); + assert_eq!(t.presets().swatches, s.presets().swatches); } } diff --git a/crates/engine-core/src/presets/tests.rs b/crates/engine-core/src/presets/tests.rs index e3be3ea930..881c49b845 100644 --- a/crates/engine-core/src/presets/tests.rs +++ b/crates/engine-core/src/presets/tests.rs @@ -1,3 +1,5 @@ +use crate::prefs::SavedPrefsExt; +use crate::presets::PresetsExt; use serde_json::{Value, json}; use crate::Session; @@ -165,7 +167,7 @@ fn preset_stop_edits_the_current_gradient() { fn the_tool_gradient_takes_a_whole_set_of_stops() { let mut s = session(8); let revision = s.active().unwrap().revision; - let name = s.presets.gradient.name.clone(); + let name = s.presets().gradient.name.clone(); let v = s .execute( "gradient.presets.stop", @@ -393,7 +395,7 @@ fn presets_persist_through_preferences_json() { // Older preference files without presets keep the defaults. let mut u = crate::session(); u.load_prefs_json("{}").unwrap(); - assert_eq!(names(&mut u, "gradient.presets.list", "presets").len(), crate::session().presets.gradients.iter().map(|g| g.items.len()).sum::()); + assert_eq!(names(&mut u, "gradient.presets.list", "presets").len(), crate::session().presets().gradients.iter().map(|g| g.items.len()).sum::()); } // ------------------------------------------------------------------ patterns @@ -439,20 +441,20 @@ fn pattern_groups_select_apply_and_sync() { fn pattern_sync_writes_only_when_the_groups_change() { let mut s = session(8); super::patterns::sync(&mut s); - let settled = s.presets.revision(); + let settled = s.presets().revision(); super::patterns::sync(&mut s); - assert_eq!(s.presets.revision(), settled, "groups in line with the library are not written"); + assert_eq!(s.presets().revision(), settled, "groups in line with the library are not written"); let mut extra = s.patterns.items[0].clone(); extra.id = "sync-test-extra".into(); s.patterns.items.push(extra); super::patterns::sync(&mut s); - assert_ne!(s.presets.revision(), settled, "a new library pattern joins a group"); - assert!(s.presets.pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); - let joined = s.presets.revision(); + assert_ne!(s.presets().revision(), settled, "a new library pattern joins a group"); + assert!(s.presets().pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); + let joined = s.presets().revision(); s.patterns.items.retain(|p| p.id != "sync-test-extra"); super::patterns::sync(&mut s); - assert_ne!(s.presets.revision(), joined, "a deleted pattern leaves its group"); - assert!(!s.presets.pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); + assert_ne!(s.presets().revision(), joined, "a deleted pattern leaves its group"); + assert!(!s.presets().pattern_groups.iter().any(|g| g.items.iter().any(|id| id == "sync-test-extra"))); } #[test] @@ -523,7 +525,7 @@ fn styles_apply_to_selected_layers_and_new_from_layer() { assert_eq!(fx(&s, b), 4); assert!(s.execute("style.presets.apply", json!({"preset": "nope"})).is_err()); // Thumbnails render the effect around the swatch. - let st = s.presets.styles[0].items.iter().find(|x| x.name == "Outer Glow").unwrap().clone(); + let st = s.presets().styles[0].items.iter().find(|x| x.name == "Outer Glow").unwrap().clone(); let px = super::styles::thumbnail(&s, &st, 48); assert_eq!(px.len(), 48 * 48 * 4); assert!(px[(4 * 48 + 24) * 4 + 3] == 0 || px[(7 * 48 + 24) * 4 + 3] > 0, "glow reaches outside the square"); @@ -554,7 +556,7 @@ fn styles_with_pattern_overlay_copy_the_pattern() { let mut s = session(8); s.execute("layer.new.layer", json!({})).unwrap(); let id = active(&s); - s.presets.styles[0].items.push(super::styles::StylePreset { + s.presets_mut().styles[0].items.push(super::styles::StylePreset { name: "Bricky".into(), effects: vec![crate::layer_style::effect_from_params("patternOverlay", &json!({"pattern": "Bricks"})).unwrap()], blend: None, @@ -630,7 +632,7 @@ fn custom_shapes_join_the_shapes_panel() { assert!(s.edit_state.custom_shapes.is_empty()); // New preset from the active shape layer, normalised to the 100 box. s.execute("shape.presets.new", json!({"name": "From Layer", "group": "Mine"})).unwrap(); - let g = s.presets.shapes.iter().find(|g| g.name == "Mine").unwrap(); + let g = s.presets().shapes.iter().find(|g| g.name == "Mine").unwrap(); let b = g.items[0].path.control_bounds().unwrap(); assert!(b.2.max(b.3) > 99.9); } @@ -749,16 +751,16 @@ fn crop_presets_are_tool_presets_that_persist() { assert_eq!(r["options"]["toolOptions"]["crop_width"], "4 in"); // Deleting several is all or nothing. assert!(t.execute("tool.presets.edit", json!({"action": "delete", "preset": ["4 x 5 in 300 ppi", "missing"]})).is_err()); - assert_eq!(t.presets.tool_presets.iter().filter(|p| p.tool == "crop").count(), 2); + assert_eq!(t.presets().tool_presets.iter().filter(|p| p.tool == "crop").count(), 2); let r = t.execute("tool.presets.edit", json!({"action": "delete", "preset": ["4 x 5 in 300 ppi 2", "4 x 5 in 300 ppi", "4 x 5 in 300 ppi"]})).unwrap(); assert_eq!(r["deleted"], 2); - assert!(t.presets.tool_presets.iter().all(|p| p.tool != "crop")); + assert!(t.presets().tool_presets.iter().all(|p| p.tool != "crop")); } #[test] fn tool_preset_names_and_params_are_checked() { let mut s = crate::session(); - let n = s.presets.tool_presets.len(); + let n = s.presets().tool_presets.len(); let long = "x".repeat(crate::brush_preset_cmds::MAX_NAME + 1); for bad in [ json!({"name": long, "tool": "crop"}), @@ -772,7 +774,7 @@ fn tool_preset_names_and_params_are_checked() { ] { assert!(s.execute("tool.presets.new", bad.clone()).is_err(), "{bad}"); } - assert_eq!(s.presets.tool_presets.len(), n); + assert_eq!(s.presets().tool_presets.len(), n); // An empty or blank name falls back to the tool's; the longest name fits. assert_eq!(s.execute("tool.presets.new", json!({"name": " ", "tool": "crop"})).unwrap()["name"], "crop"); let max = "é".repeat(crate::brush_preset_cmds::MAX_NAME); @@ -780,9 +782,9 @@ fn tool_preset_names_and_params_are_checked() { assert!(s.execute("tool.presets.edit", json!({"action": "rename", "preset": "crop", "name": long})).is_err()); assert!(s.execute("tool.presets.edit", json!({"action": "rename", "preset": "crop", "name": " "})).is_err()); // The store is capped. - while s.presets.tool_presets.len() < super::tools::MAX_PRESETS { - let i = s.presets.tool_presets.len(); - s.presets.tool_presets.push(super::tools::ToolPreset { name: format!("p{i}"), tool: "crop".into(), options: json!({}) }); + while s.presets().tool_presets.len() < super::tools::MAX_PRESETS { + let i = s.presets().tool_presets.len(); + s.presets_mut().tool_presets.push(super::tools::ToolPreset { name: format!("p{i}"), tool: "crop".into(), options: json!({}) }); } assert!(s.execute("tool.presets.new", json!({"name": "one more", "tool": "crop"})).is_err()); } @@ -807,15 +809,15 @@ fn damaged_tool_presets_skip_only_the_bad_entries() { ]); let mut t = crate::session(); t.load_prefs_json(&prefs.to_string()).unwrap(); - let names: Vec<&str> = t.presets.tool_presets.iter().map(|p| p.name.as_str()).collect(); + let names: Vec<&str> = t.presets().tool_presets.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["Good", "Odd options"]); - assert!(t.presets.tool_presets[1].options.is_object()); - assert!(t.presets.gradients.iter().any(|g| g.items.iter().any(|p| p.name == "Kept")), "other presets still load"); + assert!(t.presets().tool_presets[1].options.is_object()); + assert!(t.presets().gradients.iter().any(|g| g.items.iter().any(|p| p.name == "Kept")), "other presets still load"); // Not an array at all: no tool presets, still no crash. prefs["presets"]["tool_presets"] = json!({"a": 1}); let mut u = crate::session(); u.load_prefs_json(&prefs.to_string()).unwrap(); - assert!(u.presets.tool_presets.is_empty()); + assert!(u.presets().tool_presets.is_empty()); } // ------------------------------------------------------------------ clone source @@ -939,12 +941,12 @@ fn gradient_preset_click_fills_the_selected_shape_layer() { fn gradient_preset_click_on_a_locked_shape_changes_nothing() { let mut s = session(8); let id = LayerId(s.execute("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#336699"})).unwrap()["layer"].as_u64().unwrap()); - let (before, gradient) = (shape_fill(&s, id), s.presets.gradient.name.clone()); + let (before, gradient) = (shape_fill(&s, id), s.presets().gradient.name.clone()); s.execute("layer.lockLayers", json!({"all": true})).unwrap(); let err = s.execute("gradient.presets.select", json!({"preset": "Red 01"})).unwrap_err().to_string(); assert!(err.contains("locked"), "{err}"); assert_eq!(shape_fill(&s, id), before); - assert_eq!(s.presets.gradient.name, gradient); + assert_eq!(s.presets().gradient.name, gradient); } // ------------------------------------------------------------------ persistence @@ -961,7 +963,7 @@ fn a_damaged_preset_set_keeps_the_other_sets() { "lockAspect": true, "sizing": "pixels", "metadata": "exif", "profile": "srgb", "embedProfile": false, "tgaBits": "24" }); s.execute("file.export.presets.save", json!({"name": "Web JPEG", "settings": export})).unwrap(); - let saved = s.presets.to_json(&s); + let saved = s.presets().to_json(&s); for key in ["gradients", "gradient", "styles", "shapes", "pattern_groups", "recent_documents", "custom_shapes", "layer_defaults", "swatches", "export_presets"] { @@ -969,33 +971,33 @@ fn a_damaged_preset_set_keeps_the_other_sets() { blob[key] = json!("not a preset set"); let mut next = crate::session(); next.load_presets_json(blob); - assert_eq!(next.presets.documents, s.presets.documents, "damaged `{key}`"); - assert_eq!(next.presets.tool_presets.len(), crate::session().presets.tool_presets.len(), "damaged `{key}`"); + assert_eq!(next.presets().documents, s.presets().documents, "damaged `{key}`"); + assert_eq!(next.presets().tool_presets.len(), crate::session().presets().tool_presets.len(), "damaged `{key}`"); if key != "export_presets" { - assert_eq!(next.presets.export_presets, s.presets.export_presets, "damaged `{key}`"); + assert_eq!(next.presets().export_presets, s.presets().export_presets, "damaged `{key}`"); } } let mut blob = saved.clone(); blob["export_presets"] = json!("not a preset set"); let mut next = crate::session(); next.load_presets_json(blob); - assert!(next.presets.export_presets.is_empty()); - assert_eq!(next.presets.documents, s.presets.documents); + assert!(next.presets().export_presets.is_empty()); + assert_eq!(next.presets().documents, s.presets().documents); let mut blob = saved.clone(); blob["documents"] = json!("not a preset set"); let mut next = crate::session(); next.load_presets_json(blob); - assert!(next.presets.documents.is_empty()); - assert_eq!(next.presets.export_presets, s.presets.export_presets); + assert!(next.presets().documents.is_empty()); + assert_eq!(next.presets().export_presets, s.presets().export_presets); // Null sets keep their defaults, as before. let mut next = crate::session(); next.load_presets_json( json!({"tool_presets": null, "gradients": null, "documents": saved["documents"].clone(), "export_presets": saved["export_presets"].clone()}), ); - assert_eq!(next.presets.tool_presets.len(), crate::session().presets.tool_presets.len()); - assert_eq!(next.presets.gradients.len(), crate::session().presets.gradients.len()); - assert_eq!(next.presets.documents, s.presets.documents); - assert_eq!(next.presets.export_presets, s.presets.export_presets); + assert_eq!(next.presets().tool_presets.len(), crate::session().presets().tool_presets.len()); + assert_eq!(next.presets().gradients.len(), crate::session().presets().gradients.len()); + assert_eq!(next.presets().documents, s.presets().documents); + assert_eq!(next.presets().export_presets, s.presets().export_presets); } #[test] @@ -1008,24 +1010,24 @@ fn restoring_duplicate_gradient_names_preserves_addressable_presets() { Group::new("First", vec![GradientPreset::new("Foo", &["#ff0000", "#000000"]), GradientPreset::new("Foo", &["#00ff00", "#000000"])]), Group::new("Second", vec![GradientPreset::new("Foo 2", &["#0000ff", "#000000"]), GradientPreset::new("FOO", &["#ffff00", "#000000"])]), ]; - s.presets.gradient = presets[0].items[1].clone(); - s.presets.gradients = presets; - let saved = s.presets.to_json(&s); + s.presets_mut().gradient = presets[0].items[1].clone(); + s.presets_mut().gradients = presets; + let saved = s.presets().to_json(&s); let mut restored = crate::session(); restored.load_presets_json(saved.clone()); - let names: Vec = restored.presets.gradients.iter().flat_map(|g| g.items.iter().map(|p| p.name.clone())).collect(); + let names: Vec = restored.presets().gradients.iter().flat_map(|g| g.items.iter().map(|p| p.name.clone())).collect(); assert_eq!(names, ["Foo", "Foo 3", "Foo 2", "FOO"]); - assert_eq!(restored.presets.gradient.name, "Foo 3"); - assert_eq!(restored.presets.gradient.stops, GradientPreset::new("", &["#00ff00", "#000000"]).stops); + assert_eq!(restored.presets().gradient.name, "Foo 3"); + assert_eq!(restored.presets().gradient.stops, GradientPreset::new("", &["#00ff00", "#000000"]).stops); for (name, color) in [("Foo 2", "#0000ff"), ("FOO", "#ffff00")] { restored.execute("gradient.presets.select", json!({"preset": name})).unwrap(); - assert_eq!(restored.presets.gradient.stops, GradientPreset::new("", &[color, "#000000"]).stops); + assert_eq!(restored.presets().gradient.stops, GradientPreset::new("", &[color, "#000000"]).stops); } - let current = restored.presets.gradient.clone(); - let once = restored.presets.to_json(&restored); + let current = restored.presets().gradient.clone(); + let once = restored.presets().to_json(&restored); restored.load_presets_json(once); - assert_eq!(restored.presets.gradient, current); - let names: Vec = restored.presets.gradients.iter().flat_map(|g| g.items.iter().map(|p| p.name.clone())).collect(); + assert_eq!(restored.presets().gradient, current); + let names: Vec = restored.presets().gradients.iter().flat_map(|g| g.items.iter().map(|p| p.name.clone())).collect(); assert_eq!(names, ["Foo", "Foo 3", "Foo 2", "FOO"]); } @@ -1035,16 +1037,16 @@ fn restoring_duplicate_gradient_names_preserves_addressable_presets() { fn export_presets_survive_a_presets_json_round_trip() { let mut s = crate::session(); s.execute("file.export.presets.save", json!({"name": "Web", "settings": {"format": "jpg", "quality": 70}})).unwrap(); - assert_eq!(s.presets.export_presets.len(), 1); + assert_eq!(s.presets().export_presets.len(), 1); - let saved = s.presets.to_json(&s); + let saved = s.presets().to_json(&s); assert_eq!(saved["export_presets"].as_array().map(Vec::len), Some(1)); let mut restored = crate::session(); restored.load_presets_json(saved); - assert_eq!(restored.presets.export_presets.len(), 1); - assert_eq!(restored.presets.export_presets[0].name, "Web"); - assert_eq!(restored.presets.export_presets[0].settings.format, "jpg"); + assert_eq!(restored.presets().export_presets.len(), 1); + assert_eq!(restored.presets().export_presets[0].name, "Web"); + assert_eq!(restored.presets().export_presets[0].settings.format, "jpg"); } /// A nested command a preset command runs answers to the session's authorization hook: a denied one diff --git a/crates/engine-core/src/presets/tools.rs b/crates/engine-core/src/presets/tools.rs index f73ed84008..6ae7156daa 100644 --- a/crates/engine-core/src/presets/tools.rs +++ b/crates/engine-core/src/presets/tools.rs @@ -8,6 +8,8 @@ //! The Crop tool's options-bar presets (New / Delete Crop Preset…) are tool presets of the //! `"crop"` tool, as in Photoshop, so they also show in the Tool Presets panel. +use crate::presets::presets_changed; +use crate::presets::PresetsExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -91,7 +93,7 @@ pub fn builtin() -> Vec { fn list(s: &mut Session, p: &Value) -> Result { let filter = str_param(p, "tool").map(norm); let items: Vec = s - .presets + .presets() .tool_presets .iter() .filter(|t| filter.as_ref().is_none_or(|f| norm(&t.tool) == *f)) @@ -133,7 +135,7 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { let f = s.tools.foreground; options["foreground"] = json!(f); } - if s.presets.tool_presets.len() >= MAX_PRESETS { + if s.presets().tool_presets.len() >= MAX_PRESETS { return Err(bad(CMD, format!("at most {MAX_PRESETS} tool presets can be saved; delete some first"))); } let base = match p.get("name") { @@ -142,10 +144,10 @@ fn new_preset(s: &mut Session, p: &Value) -> Result { Some(Value::String(n)) => checked_name(n, CMD)?, Some(_) => return Err(bad(CMD, "`name` must be a string")), }; - let groups = [Group::new("", s.presets.tool_presets.clone())]; + let groups = [Group::new("", s.presets().tool_presets.clone())]; let name = super::unique_name(&groups, &base); - s.presets.tool_presets.push(ToolPreset { name: name.clone(), tool: tool.clone(), options }); - s.presets_changed(); + s.presets_mut().tool_presets.push(ToolPreset { name: name.clone(), tool: tool.clone(), options }); + presets_changed(s); Ok(json!({"name": name, "tool": tool})) } @@ -153,7 +155,7 @@ fn select(s: &mut Session, p: &Value) -> Result { const CMD: &str = "tool.presets.select"; let name = req_str(p, "preset", CMD)?; let t = s - .presets + .presets() .tool_presets .iter() .find(|t| t.name == name) @@ -186,18 +188,18 @@ fn edit(s: &mut Session, p: &Value) -> Result { if action == "rename" { checked_name(req_str(p, "name", CMD)?, CMD)?; } - let mut groups = vec![Group::new("", std::mem::take(&mut s.presets.tool_presets))]; + let mut groups = vec![Group::new("", std::mem::take(&mut s.presets_mut().tool_presets))]; let r = edit_groups(&mut groups, &action, p, CMD); - s.presets.tool_presets = groups.pop().map(|g| g.items).unwrap_or_default(); + s.presets_mut().tool_presets = groups.pop().map(|g| g.items).unwrap_or_default(); let r = r?; - s.presets_changed(); + presets_changed(s); Ok(r) } fn reset(s: &mut Session, _: &Value) -> Result { - s.presets.tool_presets = builtin(); - s.presets_changed(); - Ok(json!({"presets": s.presets.tool_presets.len()})) + s.presets_mut().tool_presets = builtin(); + presets_changed(s); + Ok(json!({"presets": s.presets().tool_presets.len()})) } pub fn specs() -> Vec { diff --git a/crates/engine-core/src/proof_sim.rs b/crates/engine-core/src/proof_sim.rs index 32fcdc48c9..bdf4a4c0de 100644 --- a/crates/engine-core/src/proof_sim.rs +++ b/crates/engine-core/src/proof_sim.rs @@ -16,6 +16,7 @@ //! display unchanged: the canvas texture is clamped to 0–1, so there is nothing above white //! to compress. +use crate::color_cmds::ColorExt; use craft_cms::{Builtin, Intent, Lut3d, Transform}; use photocraft_color::SampleType; use photocraft_color::convert::{linear_to_srgb, srgb_to_linear}; @@ -238,8 +239,8 @@ pub fn set_kind(s: &mut Session, kind: ProofKind) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let (id, doc) = (st.doc.id, st.doc.clone()); let plates = matches!(kind, ProofKind::Plate(_) | ProofKind::CmyPlate); - let working = if plates { Some(s.color.resolve("working-cmyk", Some(&doc), Some(photocraft_color::ColorMode::Cmyk))?) } else { None }; - let pv = s.color.proof_mut(id); + let working = if plates { Some(s.color().resolve("working-cmyk", Some(&doc), Some(photocraft_color::ColorMode::Cmyk))?) } else { None }; + let pv = s.color_mut().proof_mut(id); if let Some(w) = working { pv.setup.profile = w; pv.setup.name = "working-cmyk".into(); @@ -258,7 +259,7 @@ fn run_kind(s: &mut Session, id: &str) -> Result { fn preview_32(s: &mut Session, p: &Value) -> Result { const CMD: &str = "view.thirtyTwoBitPreviewOptions"; let id = s.active().ok_or(EngineError::NoDocument)?.doc.id; - let mut h = s.color.hdr.get(&id).copied().unwrap_or_default(); + let mut h = s.color().hdr.get(&id).copied().unwrap_or_default(); if let Some(m) = p.get("method").and_then(Value::as_str) { h.highlight_compression = match m { "exposureGamma" | "exposureAndGamma" => false, @@ -272,7 +273,7 @@ fn preview_32(s: &mut Session, p: &Value) -> Result { if let Some(g) = p.get("gamma").and_then(Value::as_f64) { h.gamma = (g as f32).clamp(0.1, 9.99); } - s.color.hdr.insert(id, h); + s.color_mut().hdr.insert(id, h); Ok(json!({"method": if h.highlight_compression { "highlightCompression" } else { "exposureGamma" }, "exposure": h.exposure, "gamma": h.gamma})) } @@ -317,6 +318,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests { + use crate::color_cmds::ColorExt; use super::*; /// The shared sRGB functions match the removed copies bit for bit. @@ -380,11 +382,11 @@ mod tests { let r = s.execute(id, json!({})).unwrap(); assert_eq!(r["proofColors"], true); let d = s.active().unwrap().doc.clone(); - let pv = s.color.proof(d.id); + let pv = s.color().proof(d.id); assert_eq!(pv.setup.kind.id(), id.trim_start_matches("view.proofSetup.")); - let lut = s.color.display_lut(&d, 5).unwrap(); + let lut = s.color().display_lut(&d, 5).unwrap(); assert_eq!(lut.data().len(), 125); - let bytes = s.color.canvas_lut(&d, 5).unwrap().unwrap(); + let bytes = s.color().canvas_lut(&d, 5).unwrap().unwrap(); assert_eq!(bytes.len(), 125 * 4); } } @@ -395,7 +397,7 @@ mod tests { let mut s = session("rgb", 8); s.execute("view.proofSetup.workingCyanPlate", json!({})).unwrap(); let d = s.active().unwrap().doc.clone(); - let lut = s.color.display_lut(&d, 5).unwrap(); + let lut = s.color().display_lut(&d, 5).unwrap(); // Pure cyan: heavy cyan plate → dark gray; white: no ink → white; red: little cyan. let cyan = sample(&lut, [0, 4, 4]); let white = sample(&lut, [4, 4, 4]); @@ -407,7 +409,7 @@ mod tests { assert!(cyan[0] < red[0] && cyan[0] < 0.6, "cyan {cyan:?} red {red:?}"); // Back to the plain working CMYK proof via Proof Setup. s.execute("view.proofSetup", json!({"profile": "working-cmyk"})).unwrap(); - assert_eq!(s.color.proof(d.id).setup.kind, ProofKind::Profile); + assert_eq!(s.color().proof(d.id).setup.kind, ProofKind::Profile); } #[test] @@ -415,7 +417,7 @@ mod tests { let mut s = session("rgb", 8); s.execute("view.proofSetup.legacyMacintoshRgb", json!({})).unwrap(); let d = s.active().unwrap().doc.clone(); - let lut = s.color.display_lut(&d, 5).unwrap(); + let lut = s.color().display_lut(&d, 5).unwrap(); let mid = sample(&lut, [2, 2, 2]); let white = sample(&lut, [4, 4, 4]); // 0.5^1.8 = 0.287 linear vs 0.214 for sRGB 0.5: the gamma-1.8 display is brighter. @@ -429,21 +431,21 @@ mod tests { assert!(s.execute("view.thirtyTwoBitPreviewOptions", json!({"exposure": 1})).is_err(), "8-bit: disabled"); let mut s = session("rgb", 32); let d = s.active().unwrap().doc.clone(); - assert!(s.color.canvas_lut(&d, 5).unwrap().is_none()); + assert!(s.color().canvas_lut(&d, 5).unwrap().is_none()); let r = s.execute("view.thirtyTwoBitPreviewOptions", json!({"exposure": 1.0, "gamma": 1.0})).unwrap(); assert_eq!(r["exposure"], 1.0); - assert!(hdr_active(&s.color, &d)); - let lut = s.color.display_lut(&d, 5).unwrap(); + assert!(hdr_active(s.color(), &d)); + let lut = s.color().display_lut(&d, 5).unwrap(); // +1 stop doubles linear light: sRGB 0.25 (0.0508 linear) → 0.1016 linear ≈ 0.354 sRGB. let q = sample(&lut, [1, 1, 1]); assert!((q[0] - 0.354).abs() < 0.02, "{q:?}"); - assert!(s.color.canvas_lut(&d, 5).unwrap().is_some()); + assert!(s.color().canvas_lut(&d, 5).unwrap().is_some()); // The GPU canvas applies it in its shader: its LUT leaves it out (none for sRGB). - assert_eq!(s.color.hdr_preview(&d), Some(HdrPreview { highlight_compression: false, exposure: 1.0, gamma: 1.0 })); - assert!(s.color.gpu_canvas_lut(&d, 5).unwrap().is_none()); + assert_eq!(s.color().hdr_preview(&d), Some(HdrPreview { highlight_compression: false, exposure: 1.0, gamma: 1.0 })); + assert!(s.color().gpu_canvas_lut(&d, 5).unwrap().is_none()); // Highlight Compression: identity mapping, so no LUT. s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "highlightCompression"})).unwrap(); - assert!(!hdr_active(&s.color, &d)); + assert!(!hdr_active(s.color(), &d)); assert!(s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "nope"})).is_err()); // Clamped ranges. let r = s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "exposureGamma", "exposure": 99, "gamma": 0})).unwrap(); diff --git a/crates/engine/examples/bench_content_aware_scale.rs b/crates/engine/examples/bench_content_aware_scale.rs index dd137fefd5..0796c4eb07 100644 --- a/crates/engine/examples/bench_content_aware_scale.rs +++ b/crates/engine/examples/bench_content_aware_scale.rs @@ -2,6 +2,7 @@ //! synthetic 24 MP RGB photo opened from JPEG like `perf_scenarios`' (gradients, soft blobs, fine //! noise and a high-contrast disc), scaled to 90 % width, undone between runs. //! `cargo run --release -p photocraft-engine --example bench_content_aware_scale [reps] [width height]` +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use photocraft_engine::Session; diff --git a/crates/engine/examples/bench_display.rs b/crates/engine/examples/bench_display.rs index b30f920d80..7bf8a7b45f 100644 --- a/crates/engine/examples/bench_display.rs +++ b/crates/engine/examples/bench_display.rs @@ -9,6 +9,7 @@ //! per-frame display lookup (`display_signature`, what the GPU canvas checks each frame) and //! building the 33³ GPU display LUT (once per profile/monitor change). +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use craft_cms::Builtin; @@ -59,16 +60,16 @@ fn main() { let before = time(reps, || { std::hint::black_box(buf.to_rgba8()); }); - let display = s.color.canvas_display(&d).expect("display"); + let display = s.color().canvas_display(&d).expect("display"); let after = time(reps, || { - let d = s.color.canvas_display(&d).expect("display"); + let d = s.color().canvas_display(&d).expect("display"); std::hint::black_box(if d.is_identity() { buf.to_rgba8() } else { d.to_rgba8(&buf) }); }); let frame = time(reps * 200, || { - std::hint::black_box(s.color.display_signature(&d)); + std::hint::black_box(s.color().display_signature(&d)); }); let lut = time(reps, || { - std::hint::black_box(s.color.canvas_lut(&d, 33).expect("lut")); + std::hint::black_box(s.color().canvas_lut(&d, 33).expect("lut")); }); let tag = if display.is_identity() { " (identity)" } else { "" }; println!("{:<22} {composite:>8.1}ms {before:>12.1}ms {after:>12.1}ms {:>10.1}µs {lut:>8.1}ms{tag}", name, frame * 1000.0); diff --git a/crates/engine/examples/content_aware_bench.rs b/crates/engine/examples/content_aware_bench.rs index 0fbf30ccb1..00401e2b29 100644 --- a/crates/engine/examples/content_aware_bench.rs +++ b/crates/engine/examples/content_aware_bench.rs @@ -12,6 +12,7 @@ //! (every sampling and adaptation option), Edit › Fill Content-Aware, Delete and Fill, Spot //! Healing, Patch and Content-Aware Move at 8, 16 and 32 bits, and for the algorithms called //! directly on synthetic buffers (1, 3 and 4 channels). +use photocraft_engine::color_cmds::ColorExt; use std::time::{Duration, Instant}; use photocraft_algo::content_aware::{self, FillOptions}; diff --git a/crates/engine/tests/global_state/spot_dot_gain.rs b/crates/engine/tests/global_state/spot_dot_gain.rs index 88bd13a2f5..3841c4daeb 100644 --- a/crates/engine/tests/global_state/spot_dot_gain.rs +++ b/crates/engine/tests/global_state/spot_dot_gain.rs @@ -7,6 +7,8 @@ //! concurrent test could flatten one document under two settings. Keep any other test that //! changes the spot dot gain in this file. +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::color_cmds::ColorExt; use photocraft_compose::multichannel::{SPOT_DOT_GAIN, spot_dot_gain}; use photocraft_engine::Session; use serde_json::json; @@ -22,7 +24,7 @@ fn half_tint(s: &mut Session) { fn spot_dot_gain_setting() { let _process = crate::lock(&crate::PROCESS); let mut s = Session::new(); - assert_eq!(s.color.settings.spot_dot_gain, SPOT_DOT_GAIN, "Photoshop's default Spot working space: Dot Gain 20 %"); + assert_eq!(s.color().settings.spot_dot_gain, SPOT_DOT_GAIN, "Photoshop's default Spot working space: Dot Gain 20 %"); for bad in [json!(-1), json!(50), json!("20%"), json!(true)] { assert!(s.execute("edit.colorSettings", json!({"spotDotGain": bad})).is_err(), "{bad}"); } @@ -42,7 +44,7 @@ fn spot_dot_gain_setting() { // `prefs.set` and `prefs.reset` on `colorSettings` move the compositor's gain too. Same // function, not a second test: tests in one binary run concurrently. - let in_sync = |s: &Session| spot_dot_gain() == s.color.settings.spot_dot_gain; + let in_sync = |s: &Session| spot_dot_gain() == s.color().settings.spot_dot_gain; s.execute("prefs.set", json!({"path": "colorSettings.spotDotGain", "value": 25})).unwrap(); assert_eq!(spot_dot_gain(), 25.0); assert!(in_sync(&s)); @@ -70,7 +72,7 @@ fn spot_dot_gain_setting() { photocraft_compose::multichannel::set_spot_dot_gain(SPOT_DOT_GAIN); let mut again = Session::new(); again.load_prefs_json(&saved).unwrap(); - assert_eq!(again.color.settings.spot_dot_gain, 38.0); + assert_eq!(again.color().settings.spot_dot_gain, 38.0); assert_eq!(spot_dot_gain(), 38.0); // A saved gain out of range is reported and reset, so later Color Settings edits still pass. @@ -79,7 +81,7 @@ fn spot_dot_gain_setting() { let mut third = Session::new(); let invalid = third.load_prefs_json(&bad.to_string()).unwrap(); assert!(invalid.iter().any(|p| p.path() == "colorSettings.spotDotGain"), "{:?}", invalid.iter().map(|p| p.path()).collect::>()); - assert_eq!(third.color.settings.spot_dot_gain, SPOT_DOT_GAIN); + assert_eq!(third.color().settings.spot_dot_gain, SPOT_DOT_GAIN); assert_eq!(spot_dot_gain(), SPOT_DOT_GAIN); third.execute("edit.colorSettings", json!({"intent": "relative"})).unwrap(); photocraft_compose::multichannel::set_spot_dot_gain(SPOT_DOT_GAIN); diff --git a/crates/engine/tests/global_state/text_gamma.rs b/crates/engine/tests/global_state/text_gamma.rs index de7c16353d..351e91e2b9 100644 --- a/crates/engine/tests/global_state/text_gamma.rs +++ b/crates/engine/tests/global_state/text_gamma.rs @@ -8,6 +8,7 @@ //! with the one after its undo, and failed on Windows CI that way). Keep any other test that //! changes the gamma in this file. +use photocraft_engine::color_cmds::ColorExt; use photocraft_engine::Session; use serde_json::json; @@ -15,7 +16,7 @@ use serde_json::json; fn blend_text_gamma_setting() { let _process = crate::lock(&crate::PROCESS); let mut s = Session::new(); - assert!((s.color.settings.blend_text_gamma - 1.45).abs() < 1e-6); + assert!((s.color().settings.blend_text_gamma - 1.45).abs() < 1e-6); assert!(s.execute("edit.colorSettings", json!({"blendTextGamma": 3.0})).is_err()); // The compositor's (application-wide) gamma follows the setting. s.execute("edit.colorSettings", json!({"blendTextGamma": 1.45})).unwrap(); @@ -26,12 +27,12 @@ fn blend_text_gamma_setting() { s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap(); assert!((photocraft_compose::psblend::text_gamma() - 1.8).abs() < 1e-6); s.execute("edit.colorSettings", json!({"blendTextGamma": true})).unwrap(); - assert!((s.color.settings.blend_text_gamma - 1.45).abs() < 1e-6); + assert!((s.color().settings.blend_text_gamma - 1.45).abs() < 1e-6); assert!((photocraft_compose::psblend::text_gamma() - 1.45).abs() < 1e-6); // `prefs.set` and `prefs.reset` on `colorSettings` move the compositor's gamma too (#987). // Same function, not a second test: tests in one binary run concurrently. - let in_sync = |s: &Session| (photocraft_compose::psblend::text_gamma() - s.color.settings.blend_text_gamma).abs() < 1e-6; + let in_sync = |s: &Session| (photocraft_compose::psblend::text_gamma() - s.color().settings.blend_text_gamma).abs() < 1e-6; s.execute("edit.colorSettings", json!({"blendTextGamma": 1.8})).unwrap(); s.execute("prefs.set", json!({"path": "colorSettings.blendTextGamma", "value": 1.0})).unwrap(); assert_eq!(photocraft_compose::psblend::text_gamma(), 1.0); diff --git a/crates/engine/tests/it/actions_duplicate.rs b/crates/engine/tests/it/actions_duplicate.rs index 5f0460be60..0cd258716e 100644 --- a/crates/engine/tests/it/actions_duplicate.rs +++ b/crates/engine/tests/it/actions_duplicate.rs @@ -1,4 +1,5 @@ //! Duplicate keeps action identities, complete settings and per-step flags stable. +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::{ Session, actions_cmds::{Action, ActionColor, ActionList, ActionStep, ActionsFile}, @@ -27,7 +28,7 @@ fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() source.set = Some("Retouch".into()); source.color = ActionColor::from_name("red"); let foreign = json!({"actions": [{"name": "Foreign", "steps": [["actions.play", {"action": 1}]]}]}); - s.actions.list = list_of(vec![ + s.actions_mut().list = list_of(vec![ source.clone(), Action::new("Target", vec![ActionStep::new("select.all", json!({}))]), Action::new( @@ -47,13 +48,13 @@ fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() let revision = s.active().unwrap().revision; let result = s.execute("actions.duplicate", json!({"action": "Source"})).unwrap(); assert_eq!(result["index"], 1); - assert_eq!(s.actions.list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["Source", "Source copy", "Target", "Caller"]); + assert_eq!(s.actions().list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["Source", "Source copy", "Target", "Caller"]); let mut expected = source; expected.name = "Source copy".into(); expected.steps[0].params["action"] = json!(2); - assert_eq!(s.actions.list.actions()[1], expected); - assert_eq!(s.actions.list.actions()[0].steps[0].params["action"], 2); - let caller = &s.actions.list.actions()[3]; + assert_eq!(s.actions().list.actions()[1], expected); + assert_eq!(s.actions().list.actions()[0].steps[0].params["action"], 2); + let caller = &s.actions().list.actions()[3]; assert_eq!(caller.steps[0].params["action"], 2); assert_eq!(caller.steps[1].params["action"], 4); assert_eq!(caller.steps[2].params["action"], 2.0); @@ -66,9 +67,9 @@ fn action_copies_follow_the_source_without_retargeting_calls_or_function_keys() assert!(played.get("failed").is_none(), "{played}"); assert!(s.active().unwrap().doc.selection.is_some(), "the copied call still plays Target rather than itself"); s.execute("actions.duplicate", json!({"action": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[1].name, "Source copy 2"); - assert_eq!(s.actions.list.actions()[2].name, "Source copy"); - assert_eq!(s.actions.list.actions()[1].steps[0].params["action"], 3); + assert_eq!(s.actions().list.actions()[1].name, "Source copy 2"); + assert_eq!(s.actions().list.actions()[2].name, "Source copy"); + assert_eq!(s.actions().list.actions()[1].steps[0].params["action"], 3); } #[test] @@ -81,23 +82,23 @@ fn step_copies_preserve_payloads_and_shift_both_flag_columns() { ); a.disabled.extend([0, 2]); a.dialogs.extend([0, 1]); - s.actions.list.push(a).unwrap(); + s.actions_mut().list.push(a).unwrap(); let revision = s.active().unwrap().revision; let result = s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap(); assert_eq!(result["step"], 1); assert_eq!(result["index"], 0); - let a = &s.actions.list.actions()[0]; + let a = &s.actions().list.actions()[0]; assert_eq!(a.name, "Steps"); assert_eq!(a.steps[0], a.steps[1]); assert_eq!(a.disabled.iter().copied().collect::>(), [0, 1, 3]); assert_eq!(a.dialogs.iter().copied().collect::>(), [0, 1, 2]); s.execute("actions.duplicate", json!({"action": 0, "step": 2})).unwrap(); - assert!(s.actions.list.actions()[0].steps[2].params.is_null()); - assert!(s.actions.list.actions()[0].steps[3].params.is_null(), "copying does not normalize null settings to an empty object"); - let mut edited = s.actions.list.actions()[0].steps[1].clone(); + assert!(s.actions().list.actions()[0].steps[2].params.is_null()); + assert!(s.actions().list.actions()[0].steps[3].params.is_null(), "copying does not normalize null settings to an empty object"); + let mut edited = s.actions().list.actions()[0].steps[1].clone(); edited.params["layer"] = json!(99); - s.actions.list.replace_step(0, 1, edited).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps[0].params, payload, "the copy owns its settings"); + s.actions_mut().list.replace_step(0, 1, edited).unwrap(); + assert_eq!(s.actions().list.actions()[0].steps[0].params, payload, "the copy owns its settings"); assert_eq!(s.active().unwrap().revision, revision); } @@ -106,7 +107,7 @@ fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() let mut s = session(); s.execute("actions.record", json!({"name": "Recording"})).unwrap(); s.execute("select.all", json!({})).unwrap(); - let before = s.actions.list.clone(); + let before = s.actions().list.clone(); let recording = s.recording.target; let revision = s.active().unwrap().revision; for params in [ @@ -118,19 +119,19 @@ fn invalid_copies_do_not_flush_recording_and_valid_step_copies_keep_recording() json!({"action": 0, "step": "x"}), ] { assert!(s.execute("actions.duplicate", params.clone()).is_err(), "{params}"); - assert_eq!(s.actions.list, before); + assert_eq!(s.actions().list, before); assert_eq!(s.recording.target, recording); assert_eq!(s.active().unwrap().revision, revision); } s.execute("actions.duplicate", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("select.all", json!({})); 2]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("select.all", json!({})); 2]); assert!(s.recording.target.is_some()); s.execute("select.deselect", json!({})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps.len(), 3); - s.actions.list.push(Action::new("Edit during playback", vec![ActionStep::new("actions.duplicate", json!({"action": 0}))])).unwrap(); - let before = s.actions.list.clone(); + assert_eq!(s.actions().list.actions()[0].steps.len(), 3); + s.actions_mut().list.push(Action::new("Edit during playback", vec![ActionStep::new("actions.duplicate", json!({"action": 0}))])).unwrap(); + let before = s.actions().list.clone(); let played = s.execute("actions.play", json!({"action": "Edit during playback"})).unwrap(); assert!(played["failed"]["error"].as_str().is_some_and(|e| e.contains("playback")), "{played}"); - assert_eq!(s.actions.list, before); + assert_eq!(s.actions().list, before); } diff --git a/crates/engine/tests/it/actions_panel_menu.rs b/crates/engine/tests/it/actions_panel_menu.rs index 1f6c8557f8..9c08441582 100644 --- a/crates/engine/tests/it/actions_panel_menu.rs +++ b/crates/engine/tests/it/actions_panel_menu.rs @@ -1,4 +1,5 @@ //! The remaining panel commands compose with the same definitions, journal and ATN boundary. +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::{ Session, actions_cmds::{Action, ActionColor, ActionList, ActionStep}, @@ -11,7 +12,7 @@ use serde_json::json; fn session() -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width":40,"height":30})).unwrap(); - s.actions.list.push(Action::new("A", vec![])).unwrap(); + s.actions_mut().list.push(Action::new("A", vec![])).unwrap(); s } @@ -27,17 +28,17 @@ fn tool_recording_is_opt_in_and_toggles_do_not_reclassify_pending_steps() { s.execute("actions.record", json!({"action":"A"})).unwrap(); stroke(&mut s, "#ff0000"); s.execute("select.all", json!({})).unwrap(); - let original = (s.actions.clone(), s.recording.clone()); + let original = (s.actions().clone(), s.recording.clone()); assert!(s.execute("actions.allowToolRecording", json!({"enabled":"yes"})).is_err()); - assert_eq!((s.actions.clone(), s.recording.clone()), original, "invalid mode must not flush pending work"); + assert_eq!((s.actions().clone(), s.recording.clone()), original, "invalid mode must not flush pending work"); s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap(); stroke(&mut s, "#00ff00"); s.execute("actions.allowToolRecording", json!({"enabled":false})).unwrap(); stroke(&mut s, "#0000ff"); s.execute("select.deselect", json!({})).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(), ["select.all", "paint.stroke", "select.deselect"]); - assert_eq!(s.actions.list.actions()[0].steps[1].params["color"], "#00ff00"); + assert_eq!(s.actions().list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(), ["select.all", "paint.stroke", "select.deselect"]); + assert_eq!(s.actions().list.actions()[0].steps[1].params["color"], "#00ff00"); assert_eq!(s.journal.iter().filter(|s| s.0 == "paint.stroke").count(), 3, "all actual painting remains journaled"); assert_eq!(s.execute("actions.list", json!({})).unwrap()["toolRecording"], false); } @@ -63,7 +64,7 @@ fn background_stroke_ownership_does_not_suppress_ordinary_filter_jobs() { s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap(); } s.execute("actions.stop", json!({})).unwrap(); - let ids = s.actions.list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(); + let ids = s.actions().list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(); if command == "paint.remove" { assert!(ids.is_empty()); } else { @@ -93,7 +94,7 @@ fn background_strokes_from_outside_the_current_take_do_not_block_the_toggle() { assert_eq!(s.execute("actions.allowToolRecording", json!({"enabled":true})).unwrap()["enabled"], true); s.wait_job(job).unwrap(); s.execute("actions.stop", json!({})).unwrap(); - assert!(s.actions.list.actions()[0].steps.is_empty()); + assert!(s.actions().list.actions()[0].steps.is_empty()); assert_eq!(s.journal.iter().filter(|step| step.0 == "paint.remove").count(), 1); } } @@ -102,14 +103,14 @@ fn background_strokes_from_outside_the_current_take_do_not_block_the_toggle() { #[test] fn set_duplication_preserves_metadata_call_targets_and_empty_folder_order() { let mut s = session(); - s.actions.list = ActionList::new(); + s.actions_mut().list = ActionList::new(); for (name, set) in [("A", "S"), ("Other", "T"), ("B", "S")] { let mut a = Action::new(name, vec![ActionStep::new("actions.play", json!({"action":2}))]); a.set = Some(set.into()); a.color = ActionColor::from_name("red"); a.disabled.insert(0); a.dialogs.insert(0); - s.actions.list.push(a).unwrap(); + s.actions_mut().list.push(a).unwrap(); } s.prefs.edit(|p| { p.shortcuts.insert("actions.play:A".into(), "F5".into()); @@ -118,8 +119,8 @@ fn set_duplication_preserves_metadata_call_targets_and_empty_folder_order() { assert_eq!(result["set"], "S copy"); assert_eq!(actions_edit_cmds::set_names(&s), ["S", "T", "S copy"]); // The copies go after the set's last action, so a call to an action before that point keeps its target. - assert_eq!(s.actions.list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["A", "Other", "B", "A copy", "B copy"]); - for a in s.actions.list.actions() { + assert_eq!(s.actions().list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["A", "Other", "B", "A copy", "B copy"]); + for a in s.actions().list.actions() { assert_eq!(a.steps[0].params["action"], 2); assert_eq!(a.color, ActionColor::from_name("red")); assert!(a.disabled.contains(&0)); @@ -132,10 +133,10 @@ fn set_duplication_preserves_metadata_call_targets_and_empty_folder_order() { } empty.execute("actions.duplicate", json!({"set":"E"})).unwrap(); assert_eq!(actions_edit_cmds::set_names(&empty), ["E", "E copy", "F"]); - let original = (empty.actions.clone(), empty.recording.clone()); + let original = (empty.actions().clone(), empty.recording.clone()); for params in [json!({"set":"Missing"}), json!({"set":"E","action":0}), json!({"set":false})] { assert!(empty.execute("actions.duplicate", params).is_err()); - assert_eq!((empty.actions.clone(), empty.recording.clone()), original); + assert_eq!((empty.actions().clone(), empty.recording.clone()), original); } } @@ -149,7 +150,7 @@ fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() for kind in ["name", "code"] { let mut s = session(); s.execute("actions.insertMenuItem", json!({"action":"A","id":id,"eventKind":kind})).unwrap(); - let bytes = atn_cmds::export("S", &[&s.actions.list.actions()[0]], &[], false).unwrap().0; + let bytes = atn_cmds::export("S", &[&s.actions().list.actions()[0]], &[], false).unwrap().0; let raw = craft_psd::atn::parse(&bytes).unwrap(); assert!(raw.actions[0].items[0].descriptor.is_none()); let imported = atn_cmds::import(&bytes).unwrap(); @@ -166,12 +167,12 @@ fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() } } let mut s = session(); - let original = (s.actions.clone(), s.recording.clone()); + let original = (s.actions().clone(), s.recording.clone()); for params in [json!({"action":"A","id":"layer.setProps"}), json!({"action":"A","id":"file.open"}), json!({"action":"A","id":"image.imageSize","params":{"width":4}})] { assert!(s.execute("actions.insertMenuItem", params).is_err()); - assert_eq!((s.actions.clone(), s.recording.clone()), original); + assert_eq!((s.actions().clone(), s.recording.clone()), original); } let mut raw = craft_psd::atn::AtnFile::default(); raw.actions.push(craft_psd::atn::AtnAction { @@ -204,7 +205,7 @@ fn set_bytes(set: &str, action: &str) -> Vec { /// The action names in the list. fn names(s: &Session) -> Vec { - s.actions.list.actions().iter().map(|a| a.name.clone()).collect() + s.actions().list.actions().iter().map(|a| a.name.clone()).collect() } /// Load Actions waits for the recording or playback that holds the library, as the reference @@ -220,7 +221,7 @@ fn load_actions_waits_for_a_running_recording_or_playback() { assert_eq!(names(&s), ["A", "Rec"], "the refused load changes nothing"); s.execute("actions.stop", json!({})).unwrap(); // A running playback holds it the same way: the step fails instead of editing mid-play. - s.actions.list.push(Action::new("Loader", vec![ActionStep::new("actions.load", json!({"data":during}))])).unwrap(); + s.actions_mut().list.push(Action::new("Loader", vec![ActionStep::new("actions.load", json!({"data":during}))])).unwrap(); let played = s.execute("actions.play", json!({"action":"Loader"})).unwrap(); assert!(played["failed"]["error"].as_str().unwrap().contains("playing"), "{played}"); assert!(!names(&s).iter().any(|name| name == "MidLoaded"), "nothing loaded during the playback"); @@ -239,13 +240,13 @@ fn insert_path_captures_cubic_geometry_without_editing_the_document() { let expected = s.execute("path.info", json!({"name":"Curve"})).unwrap()["path"].clone(); let revision = s.active().unwrap().revision; assert!(s.execute("actions.insertPath", json!({"action":"A","name":"work"})).is_err()); - assert!(s.actions.list.actions()[0].steps.is_empty()); + assert!(s.actions().list.actions()[0].steps.is_empty()); s.execute("actions.insertPath", json!({"action":"A","name":"Curve"})).unwrap(); assert_eq!(s.active().unwrap().revision, revision); - assert_eq!(s.actions.list.actions()[0].steps[0].params["path"], expected); + assert_eq!(s.actions().list.actions()[0].steps[0].params["path"], expected); s.execute("path.set", json!({"name":"Curve","path":{"subpaths":[]}})).unwrap(); let played = s.execute("actions.play", json!({"action":"A"})).unwrap(); assert!(played.get("failed").is_none(), "{played}"); assert_eq!(s.execute("path.info", json!({"name":"work"})).unwrap()["path"], expected); - assert!(atn_cmds::export("S", &[&s.actions.list.actions()[0]], &[], false).is_err(), "the measured ATN descriptor cannot represent inversion"); + assert!(atn_cmds::export("S", &[&s.actions().list.actions()[0]], &[], false).is_err(), "the measured ATN descriptor cannot represent inversion"); } diff --git a/crates/engine/tests/it/actions_record_again.rs b/crates/engine/tests/it/actions_record_again.rs index 2f710a27d9..75936a6e5b 100644 --- a/crates/engine/tests/it/actions_record_again.rs +++ b/crates/engine/tests/it/actions_record_again.rs @@ -1,4 +1,5 @@ //! Record Again edits one definition only after its concrete command succeeds. +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::{ EngineError, Session, actions_cmds::{Action, ActionStep}, @@ -16,7 +17,7 @@ fn session() -> Session { ); a.disabled.insert(0); a.dialogs.insert(0); - s.actions.list.push(a).unwrap(); + s.actions_mut().list.push(a).unwrap(); s } @@ -26,20 +27,20 @@ fn successful_rerecording_updates_one_step_and_roundtrips_new_settings() { for menu in [false, true] { let mut s = session(); if menu { - s.actions.list.replace_step(0, 0, ActionStep::new(atn_cmds::MENU_ITEM, json!({"id": "image.imageSize"}))).unwrap(); + s.actions_mut().list.replace_step(0, 0, ActionStep::new(atn_cmds::MENU_ITEM, json!({"id": "image.imageSize"}))).unwrap(); } - let revision = s.actions.list.revision(); + let revision = s.actions().list.revision(); s.execute("actions.recordAgain", json!({"action": "A", "step": 0, "revision": revision, "params": {"width": 6, "height": 5, "resample": "nearest"}})) .unwrap(); assert_eq!(s.active().unwrap().doc.size, photocraft_engine::doc::Size::new(6, 5)); assert!(s.active().unwrap().doc.selection.is_none(), "the following step did not play"); - let a = &s.actions.list.actions()[0]; + let a = &s.actions().list.actions()[0]; assert_eq!(a.steps.len(), 2); assert_eq!(a.steps[0].command, "image.imageSize"); assert_eq!(a.steps[0].params["width"], 6); assert!(a.disabled.contains(&0)); assert!(a.dialogs.contains(&0)); - assert_eq!(s.actions.list.revision(), revision + 1); + assert_eq!(s.actions().list.revision(), revision + 1); assert_eq!(s.journal.last().unwrap().0, "image.imageSize"); let bytes = atn_cmds::export("Set", &[a], &[], false).unwrap().0; let loaded = atn_cmds::import(&bytes).unwrap(); @@ -58,7 +59,7 @@ fn deny_resize(id: &str, _: &Value) -> photocraft_engine::Result<()> { #[test] fn failed_or_stale_rerecording_never_replaces_the_original_step() { let mut s = session(); - let original = s.actions.list.clone(); + let original = s.actions().list.clone(); let revision = s.active().unwrap().revision; for request in [ json!({"action":"A","step":0}), @@ -69,16 +70,16 @@ fn failed_or_stale_rerecording_never_replaces_the_original_step() { json!({"action":"A","step":0,"revision":original.revision() + 1,"params":{}}), ] { assert!(s.execute("actions.recordAgain", request.clone()).is_err(), "{request}"); - assert_eq!(s.actions.list, original); - assert_eq!(s.actions.list.revision(), original.revision()); + assert_eq!(s.actions().list, original); + assert_eq!(s.actions().list.revision(), original.revision()); assert_eq!(s.active().unwrap().revision, revision); } s.authorize = Some(deny_resize); assert!(s.execute("actions.recordAgain", json!({"action":"A","step":0,"params":{"width":6,"height":5}})).is_err()); - assert_eq!(s.actions.list, original); + assert_eq!(s.actions().list, original); s.authorize = None; s.execute("actions.record", json!({"action":"A"})).unwrap(); s.execute("select.all", json!({})).unwrap(); assert!(s.execute("actions.recordAgain", json!({"action":"A","step":0,"params":{}})).is_err()); - assert_eq!(s.actions.list, original, "recording was not flushed by a refused edit"); + assert_eq!(s.actions().list, original, "recording was not flushed by a refused edit"); } diff --git a/crates/engine/tests/it/actions_single_history.rs b/crates/engine/tests/it/actions_single_history.rs index edf895404c..91c2eddc31 100644 --- a/crates/engine/tests/it/actions_single_history.rs +++ b/crates/engine/tests/it/actions_single_history.rs @@ -1,4 +1,6 @@ //! Public playback history semantics, independent of the Actions panel implementation. +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::{ Session, actions_cmds::{Action, ActionList, ActionStep, ActionsFile}, @@ -18,7 +20,7 @@ fn only(name: &str, steps: Vec<(String, Value)>) -> ActionList { fn session() -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width":4,"height":4,"background":"#804020"})).unwrap(); - s.actions + s.actions_mut() .list .push(Action::new("Two layers", ["First", "Second"].into_iter().map(|name| ActionStep::new("layer.new.layer", json!({"name":name}))).collect())) .unwrap(); @@ -52,7 +54,7 @@ fn recorded_clear_preserves_its_boundary_and_grouped_suffix() { if suffix { steps.extend([("layer.renameLayer".into(), json!({"name":"Suffix one"})), ("layer.renameLayer".into(), json!({"name":"Suffix two"}))]); } - s.actions.list = only("Clear", steps); + s.actions_mut().list = only("Clear", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let after = s.active().unwrap().doc.clone(); @@ -95,7 +97,7 @@ fn recorded_source_change_preserves_selected_pixels_and_grouping() { ("edit.fill".into(), json!({"color":"#00ffff"})), ("layer.renameLayer".into(), json!({"name":"After source"})), ]); - s.actions.list = only("Source", steps); + s.actions_mut().list = only("Source", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let added = if single_state { 1 } else { 2 + usize::from(prefix) }; @@ -139,7 +141,7 @@ fn recorded_purge_histories_does_not_restore_discarded_states() { ("layer.renameLayer".into(), json!({"name":"Suffix one"})), ("layer.renameLayer".into(), json!({"name":"Suffix two"})), ]); - s.actions.list = only("Purge", steps); + s.actions_mut().list = only("Purge", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let after = s.active().unwrap().doc.clone(); @@ -163,7 +165,7 @@ fn recorded_purge_histories_does_not_restore_discarded_states() { fn per_step_playback_also_binds_its_dialog_continuation() { use photocraft_engine::actions_cmds; let mut s = history_control_session(false); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let recording = actions_cmds::begin_playback(&mut s, &action).unwrap(); s.execute("layer.renameLayer", json!({"name":"Prefix"})).unwrap(); let continuation = actions_cmds::suspend_history(&mut s).expect("per-step playback still needs a document/history binding"); @@ -184,7 +186,7 @@ fn snapshot_source_identity_is_bound_to_the_dialog_continuation() { let a = s.execute("history.newSnapshot", json!({"name":"Source A"})).unwrap()["snapshot"].clone(); let b = s.execute("history.newSnapshot", json!({"name":"Source B"})).unwrap()["snapshot"].clone(); s.execute("history.setSource", json!({"snapshot":a})).unwrap(); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let recording = actions_cmds::begin_playback(&mut s, &action).unwrap(); s.execute("layer.renameLayer", json!({"name":"Prefix"})).unwrap(); let continuation = actions_cmds::suspend_history(&mut s).unwrap(); @@ -217,7 +219,7 @@ fn in_action_undo_clear_restores_history_and_keeps_grouped_image_undo() { ("edit.undo".into(), json!({})), ("edit.redo".into(), json!({})), ]); - s.actions.list = only("Undo Clear", steps); + s.actions_mut().list = only("Undo Clear", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); assert!(!s.active().unwrap().history.is_cleared(), "singleState={single_state}, prefix={prefix}"); @@ -244,7 +246,7 @@ fn cleared_intermediate_source_restores_exact_pixels_after_undo_redo() { let mut s = history_control_session(single_state); let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); - s.actions.list = only( + s.actions_mut().list = only( "Cleared Source", vec![ ("edit.fill".into(), json!({"color":"#0000ff"})), @@ -323,7 +325,7 @@ fn disabled_single_history_keeps_each_step() { fn failures_and_nested_calls_keep_the_outer_history_entry() { let mut s = session(); let layers = s.active().unwrap().doc.layers.len(); - s.actions + s.actions_mut() .list .push(action( "Outer", @@ -355,7 +357,7 @@ fn no_op_and_repeated_plays_preserve_history_boundaries() { assert!(s.undo()); let entries = s.active().unwrap().history.entries(); let redo = s.active().unwrap().history.redo_label().map(str::to_owned); - s.actions.list.push(Action::new("Empty", vec![])).unwrap(); + s.actions_mut().list.push(Action::new("Empty", vec![])).unwrap(); s.execute("actions.play", json!({"action":"Empty"})).unwrap(); assert_eq!(s.active().unwrap().history.entries(), entries); assert_eq!(s.active().unwrap().history.redo_label(), redo.as_deref()); @@ -420,7 +422,7 @@ fn a_real_action_still_refuses_history_setting_changes_with_grouping_on_or_off() for single in [false, true] { let mut s = session(); s.execute("actions.setHistory", json!({"singleState": single})).unwrap(); - s.actions.list = only("Setting", vec![("actions.setHistory".into(), json!({"singleState": !single}))]); + s.actions_mut().list = only("Setting", vec![("actions.setHistory".into(), json!({"singleState": !single}))]); let result = s.execute("actions.play", json!({"action": 0})).unwrap(); assert_eq!(result["failed"]["id"], "actions.setHistory"); assert_eq!(s.prefs().actions.create_single_history_state, single); @@ -435,7 +437,7 @@ fn an_accepted_clear_survives_an_action_that_returns_to_empty_captured_history() let original = s.active().unwrap().doc.clone(); assert_eq!(s.active().unwrap().history.past_len(), 0); assert!(s.execute("history.clear", json!({})).is_err(), "ordinary empty Clear still refuses"); - s.actions.list = only( + s.actions_mut().list = only( "Empty capture Clear", vec![ ("edit.fill".into(), json!({"color": "#000000"})), @@ -468,7 +470,7 @@ fn frame_compound_retains_undo_redo_content_and_layer_targets() { let target = s.active().unwrap().active_layer; let selected = s.active().unwrap().selected_layers.clone(); let count = s.active().unwrap().history.past_len(); - s.actions.list = only("Frame", vec![("layer.new.frameFromLayers".into(), json!({}))]); + s.actions_mut().list = only("Frame", vec![("layer.new.frameFromLayers".into(), json!({}))]); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let after = s.active().unwrap().doc.clone(); @@ -492,7 +494,7 @@ fn tilted_crop_between_edits_is_one_action() { let mut s = session(); let before = s.active().unwrap().doc.clone(); let count = s.active().unwrap().history.past_len(); - s.actions.list = only( + s.actions_mut().list = only( "Crop", vec![ ("layer.renameLayer".into(), json!({"name":"Prefix"})), @@ -520,7 +522,7 @@ fn again_copy_failure_preserves_the_completed_prefix() { s.execute("layer.setProps", json!({"locks":{"position":true}})).unwrap(); let before = s.active().unwrap().doc.clone(); let count = s.active().unwrap().history.past_len(); - s.actions.list = only("Prefix", vec![("layer.renameLayer".into(), json!({"name":"Completed prefix"})), ("edit.transform.againCopy".into(), json!({}))]); + s.actions_mut().list = only("Prefix", vec![("layer.renameLayer".into(), json!({"name":"Completed prefix"})), ("edit.transform.againCopy".into(), json!({}))]); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["failed"]["step"], 1, "{result}"); let after = s.active().unwrap().doc.clone(); @@ -547,7 +549,7 @@ fn same_name_rename_does_not_record_or_clear_redo() { let ids: Vec<_> = (0..entries.len() + redo.len()).map(|i| st.history.row_id(i)).collect(); let dirty = st.is_dirty(); let name = st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone(); - s.actions.list = only("No change", vec![("layer.renameLayer".into(), json!({"name":name}))]); + s.actions_mut().list = only("No change", vec![("layer.renameLayer".into(), json!({"name":name}))]); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let st = s.active().unwrap(); @@ -566,7 +568,7 @@ fn stop_message_retains_the_completed_prefix() { let mut s = session(); let before = s.active().unwrap().doc.clone(); let count = s.active().unwrap().history.past_len(); - s.actions.list = only( + s.actions_mut().list = only( "Stop", vec![ ("layer.renameLayer".into(), json!({"name":"Prefix"})), @@ -593,7 +595,7 @@ fn stop_message_retains_the_completed_prefix() { fn suspended_history_resumes_the_same_action() { use photocraft_engine::actions_cmds; let mut s = session(); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let before = s.active().unwrap().doc.clone(); let count = s.active().unwrap().history.past_len(); let recording = actions_cmds::begin_playback(&mut s, &action).unwrap(); @@ -622,7 +624,7 @@ fn suspended_history_refuses_document_or_history_drift() { use photocraft_engine::actions_cmds; for drift in 0..3 { let mut s = session(); - let action = s.actions.list.actions()[0].clone(); + let action = s.actions().list.actions()[0].clone(); let recording = actions_cmds::begin_playback(&mut s, &action).unwrap(); s.execute("layer.renameLayer", json!({"name":"Prefix"})).unwrap(); let continuation = actions_cmds::suspend_history(&mut s).unwrap(); @@ -653,7 +655,7 @@ fn grouping_preserves_non_undoable_visibility() { s.execute("history.options", json!({"makeLayerVisibilityChangesUndoable":false})).unwrap(); let before = s.active().unwrap().doc.clone(); let layer = s.active().unwrap().active_layer.unwrap(); - s.actions.list = only( + s.actions_mut().list = only( "Mixed", vec![ ("layer.renameLayer".into(), json!({"name":"Prefix"})), @@ -687,7 +689,7 @@ fn grouping_preserves_nonlinear_history_and_a_one_state_limit() { s.active_mut().unwrap().history.max_states = 1; } let before = s.active().unwrap().doc.clone(); - s.actions.list = only("Many", (0..5).map(|i| ("layer.renameLayer".into(), json!({"name":format!("Name{i}")}))).collect()); + s.actions_mut().list = only("Many", (0..5).map(|i| ("layer.renameLayer".into(), json!({"name":format!("Name{i}")}))).collect()); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let after = s.active().unwrap().doc.clone(); @@ -791,7 +793,7 @@ fn recorded_delete_case(case: &str) { ("edit.fill".into(), json!({"color":"#ffff00"})), ("edit.fill".into(), json!({"color":"#ff00ff"})), ]); - s.actions.list = only("Delete state", steps); + s.actions_mut().list = only("Delete state", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{case}, singleState={single_state}: {result}"); let after = s.active().unwrap().doc.clone(); @@ -871,7 +873,7 @@ fn recorded_user_purge_undo_case(suffix: bool) { if suffix { steps.extend([("edit.fill".into(), json!({"color":"#ffff00"})), ("edit.fill".into(), json!({"color":"#ff00ff"}))]); } - s.actions.list = only("Purge Undo", steps); + s.actions_mut().list = only("Purge Undo", steps); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "singleState={single_state}, prefix={prefix}, suffix={suffix}: {result}"); let st = s.active().unwrap(); diff --git a/crates/engine/tests/it/atn_adjustment_make_props.rs b/crates/engine/tests/it/atn_adjustment_make_props.rs index e4dea9e9f1..e6b4232672 100644 --- a/crates/engine/tests/it/atn_adjustment_make_props.rs +++ b/crates/engine/tests/it/atn_adjustment_make_props.rs @@ -1,5 +1,6 @@ //! #8384: an adjustment layer's Make step keeps the new layer's name (`Nm `), blend mode //! (`Md `) and clipping (`Grup`) on load, playback and save. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_doc::{BlendMode, LayerContent}; @@ -70,7 +71,7 @@ fn make_keeps_name_mode_and_clipping_through_play_and_save_at_both_depths() { let base = s.active().unwrap().active_layer.unwrap(); let loaded = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes(descriptor.clone()))})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{params}"); - let steps = &s.actions.list.actions()[0].steps; + let steps = &s.actions().list.actions()[0].steps; assert_eq!(steps.len(), 1, "{params}"); assert_eq!(steps[0].command, "layer.newAdjustmentLayer.levels"); for (k, v) in params.as_object().unwrap() { diff --git a/crates/engine/tests/it/atn_calculations.rs b/crates/engine/tests/it/atn_calculations.rs index 6fc4f6b21e..48efdf5ba6 100644 --- a/crates/engine/tests/it/atn_calculations.rs +++ b/crates/engine/tests/it/atn_calculations.rs @@ -1,4 +1,5 @@ //! Recorded Calculations Make forms, using the measured reference and ScriptListener types. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; @@ -75,7 +76,7 @@ fn alpha(s: &Session, index: usize) -> Vec { } fn play(s: &mut Session, action: Action) -> Value { - s.actions.list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); s.execute("actions.play", json!({"action": "Calculate"})).unwrap() } diff --git a/crates/engine/tests/it/atn_classic_gradient.rs b/crates/engine/tests/it/atn_classic_gradient.rs index 6906991f78..f1ec71c50e 100644 --- a/crates/engine/tests/it/atn_classic_gradient.rs +++ b/crates/engine/tests/it/atn_classic_gradient.rs @@ -1,4 +1,5 @@ //! Synthetic measured-layout recordings through public ATN load/save and playback. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, @@ -257,7 +258,7 @@ fn omitted_transparency_and_dither_use_recorded_defaults_during_playback() { for s in [&mut actual, &mut control] { s.execute("file.new", json!({"width":8,"height":4,"depth":depth,"background":"#204060"})).unwrap(); } - actual.actions.list = ActionList::from_file(ActionsFile::new(loaded.actions, Vec::new())); + actual.actions_mut().list = ActionList::from_file(ActionsFile::new(loaded.actions, Vec::new())); actual.execute("actions.play", json!({"action":0})).unwrap(); // The descriptor contains non-opaque Trns, but omitted UsMs disables them. // Dthr=false is explicit, overriding the native command's true default. @@ -295,7 +296,7 @@ fn recorded_gradients_match_native_pixels_and_undo_at_each_depth() { s.execute("file.new", json!({"width":8,"height":4,"depth":depth,"background":"#204060"})).unwrap(); } let before = actual.active().unwrap().doc.clone(); - actual.actions.list = ActionList::from_file(ActionsFile::new(loaded.actions, Vec::new())); + actual.actions_mut().list = ActionList::from_file(ActionsFile::new(loaded.actions, Vec::new())); actual.execute("actions.play", json!({"action":0})).unwrap(); control .execute( diff --git a/crates/engine/tests/it/atn_color_lookup.rs b/crates/engine/tests/it/atn_color_lookup.rs index bbceb9d7be..8a4cfc91de 100644 --- a/crates/engine/tests/it/atn_color_lookup.rs +++ b/crates/engine/tests/it/atn_color_lookup.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_doc::{Adjustment, LayerContent}; @@ -81,7 +82,7 @@ fn embedded_lookup_bytes_replay_invert_and_save_the_exact_descriptor() { let mut s = fixture(depth); let before = saved(&s); let original = pixels(&s); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); assert_eq!(s.execute("actions.play", json!({"action":"Lookup"})).unwrap()["ran"], 1); for (got, old) in pixels(&s).iter().zip(&original) { for c in 0..3 { @@ -169,7 +170,7 @@ fn embedded_three_dl_retains_its_nonlinear_shaper_through_action_playback() { for depth in [8, 16, 32] { let mut s = fixture(depth); let original = pixels(&s); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); assert_eq!(s.execute("actions.play", json!({"action":"Lookup"})).unwrap()["ran"], 1); for (got, old) in pixels(&s).iter().zip(&original) { for c in 0..3 { @@ -240,7 +241,7 @@ fn recorded_dither_changes_float_pixels_within_its_documented_bound() { let imported = atn_cmds::import(&encoded(d)).unwrap(); assert!(imported.unsupported.is_empty()); let mut s = fixture(32); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); assert_eq!(s.execute("actions.play", json!({"action":"Lookup"})).unwrap()["ran"], 1); pixels(&s) }; diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index 454f70dd5c..bbe606dc91 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -1,4 +1,5 @@ //! Recorded CAF settings use the native operation; unsupported descriptors stay whole. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::{ @@ -199,7 +200,7 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); for action in imported.actions { - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); } let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 0); @@ -282,7 +283,7 @@ fn caf_action_matches_native_pixels_and_undo_at_each_depth() { let before = s.active().unwrap().doc.clone(); let source = s.active().unwrap().active_layer.unwrap(); let past = s.active().unwrap().history.past_len(); - s.actions.list.push(load(descriptor())).unwrap(); + s.actions_mut().list.push(load(descriptor())).unwrap(); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert!(result.get("failed").is_none(), "{depth}: {result}"); assert_eq!(result["ran"], 1); @@ -323,7 +324,7 @@ fn caf_action_matches_native_pixels_and_undo_at_each_depth() { let past = recorded.active().unwrap().history.past_len(); let mut d = descriptor(); d.items[6].1 = enm("cafOutput", "cafOutputToCurrentLayer"); - recorded.actions.list.push(load(d)).unwrap(); + recorded.actions_mut().list.push(load(d)).unwrap(); let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{depth}: {result}"); @@ -380,7 +381,7 @@ fn caf_current_layer_sampling_matches_distinct_multilayer_controls() { let mut d = descriptor(); d.items[1].1 = D::Boolean(all_layers); d.items[6].1 = enm("cafOutput", "cafOutputToCurrentLayer"); - recorded.actions.list.push(load(d)).unwrap(); + recorded.actions_mut().list.push(load(d)).unwrap(); let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{depth}/{all_layers}: {result}"); @@ -416,7 +417,7 @@ fn caf_action_without_selection_fails_without_an_edit() { s.execute("file.new", json!({"width":8,"height":8})).unwrap(); let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); - s.actions.list.push(load(descriptor())).unwrap(); + s.actions_mut().list.push(load(descriptor())).unwrap(); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 0); assert!(result.get("failed").is_some()); diff --git a/crates/engine/tests/it/atn_crystallize_cell_size.rs b/crates/engine/tests/it/atn_crystallize_cell_size.rs index e9b35bde71..d5be036a9a 100644 --- a/crates/engine/tests/it/atn_crystallize_cell_size.rs +++ b/crates/engine/tests/it/atn_crystallize_cell_size.rs @@ -1,4 +1,5 @@ //! #7669: strict ATN export must not replace a native fractional Crystallize cell size. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; use photocraft_engine::{Session, atn_cmds}; @@ -39,7 +40,7 @@ fn fractional_cell_sizes_remain_native_and_are_refused_by_strict_export() { direct.execute(CRYSTALLIZE, params).unwrap(); let expected = pixels(&direct); let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": "Fractional Crystallize"})).unwrap(); assert_eq!(pixels(&native), expected); @@ -53,7 +54,7 @@ fn fractional_cell_sizes_remain_native_and_are_refused_by_strict_export() { assert!(skipped.is_empty() && imported.unsupported.is_empty() && imported.warnings.is_empty()); let exported = imported.actions[0].steps[0].params["cellSize"].clone(); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Fractional Crystallize"})).unwrap(); let changed = pixels(&replay) != expected; if cell_size == 5.4 { @@ -77,7 +78,7 @@ fn integer_cell_sizes_and_defaults_preserve_playback() { let mut direct = fixture(depth); direct.execute(CRYSTALLIZE, params.clone()).unwrap(); let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": "Integer Crystallize"})).unwrap(); assert_eq!(pixels(&native), pixels(&direct)); @@ -94,7 +95,7 @@ fn integer_cell_sizes_and_defaults_preserve_playback() { assert_eq!(imported.actions[0].steps.len(), 1); assert_eq!(imported.actions[0].steps[0].command, CRYSTALLIZE); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Integer Crystallize"})).unwrap(); assert_eq!(pixels(&replay), pixels(&direct), "depth {depth}: {params}"); } diff --git a/crates/engine/tests/it/atn_dialog_filters.rs b/crates/engine/tests/it/atn_dialog_filters.rs index 5ebbd41ab6..4826584778 100644 --- a/crates/engine/tests/it/atn_dialog_filters.rs +++ b/crates/engine/tests/it/atn_dialog_filters.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::actions_cmds::{ActionList, ActionsFile}; @@ -76,7 +77,7 @@ fn custom_and_fibers_recordings_round_trip_replay_native_settings_and_undo() { native.execute(id, p.clone()).unwrap(); let mut s = fixture(depth); let before = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); assert_eq!(s.execute("actions.play", json!({"action":"Dialog"})).unwrap()["ran"], 1); assert_eq!( photocraft_compose::flatten(&s.active().unwrap().doc).px, @@ -104,7 +105,7 @@ fn fibers_missing_seed_is_stable_across_playback_and_save() { assert_eq!(saved.actions[0].steps[0].params, *p); let render = |actions| { let mut s = fixture(8); - s.actions.list = ActionList::from_file(ActionsFile::new(actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(actions, Vec::new())); s.execute("actions.play", json!({"action":"Dialog"})).unwrap(); photocraft_compose::flatten(&s.active().unwrap().doc).px.clone() }; diff --git a/crates/engine/tests/it/atn_direct_adjustments.rs b/crates/engine/tests/it/atn_direct_adjustments.rs index 98a1a864ed..7bc64e80a0 100644 --- a/crates/engine/tests/it/atn_direct_adjustments.rs +++ b/crates/engine/tests/it/atn_direct_adjustments.rs @@ -1,4 +1,5 @@ //! Recorded direct Gradient Map and Replace Color forms from #10603 / #10607. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, @@ -71,24 +72,24 @@ fn load(event: [u8; 4], descriptor: Descriptor, command: &str) -> Session { let bytes = bytes(event, descriptor); let report = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); assert_eq!(report["unsupported"], json!([]), "recorded {} must map to {command}", String::from_utf8_lossy(&event)); - assert_eq!(s.actions.list.actions()[0].steps[0].command, command); + assert_eq!(s.actions().list.actions()[0].steps[0].command, command); s } #[test] fn recorded_grmp_imports_as_direct_gradient_map() { let s = load(*b"GrMp", gradient(), "image.adjustments.gradientMap"); - assert_eq!(s.actions.list.actions()[0].steps[0].params["stops"], json!([[0, [0, 0, 1]], [1, [1, 0, 0]]])); + assert_eq!(s.actions().list.actions()[0].steps[0].params["stops"], json!([[0, [0, 0, 1]], [1, [1, 0, 0]]])); } #[test] fn recorded_rplc_imports_as_direct_replace_color() { let s = load(*b"RplC", replace(), "image.adjustments.replaceColor"); - assert_eq!(s.actions.list.actions()[0].steps[0].params["hue"], json!(30)); + assert_eq!(s.actions().list.actions()[0].steps[0].params["hue"], json!(30)); } fn saved(s: &Session) -> AtnItem { - let refs = s.actions.list.actions().iter().collect::>(); + let refs = s.actions().list.actions().iter().collect::>(); let (bytes, skipped) = atn_cmds::export("Direct adjustments", &refs, &[], false).unwrap(); assert!(skipped.is_empty()); atn::parse(&bytes).unwrap().actions.remove(0).items.remove(0) @@ -196,7 +197,7 @@ fn fractional_gradient_changes_pixels_and_preserves_selection_and_undo() { assert_eq!(&expected[12..], &original[12..], "outside the selection"); let mut replay = fixture("rgb", depth); replay.execute("select.rect", json!({"x":0,"y":0,"width":3,"height":1})).unwrap(); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); play(&mut replay); assert_eq!(raw(&replay), expected); assert!(replay.undo()); @@ -294,7 +295,7 @@ fn kept(event: [u8; 4], d: Descriptor) { let imported = atn_cmds::import(&bytes(event, d.clone())).unwrap(); assert_eq!(imported.unsupported.len(), 1, "{d:?}"); let mut s = Session::new(); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); assert_eq!(saved(&s).descriptor, Some(d)); } @@ -339,10 +340,10 @@ fn invalid_replace_descriptors_and_lossy_exports_are_refused() { kept(*b"RplC", d); } let mut s = load(*b"GrMp", gradient(), "image.adjustments.gradientMap"); - let mut stale = s.actions.list.actions()[0].steps[0].clone(); + let mut stale = s.actions().list.actions()[0].steps[0].clone(); stale.params["stops"][0][1][0] = json!(0.2); - s.actions.list.replace_step(0, 0, stale).unwrap(); - assert!(atn_cmds::export("Direct adjustments", &[&s.actions.list.actions()[0]], &[], false).is_err(), "stale color metadata must not fall through to GdMp"); + s.actions_mut().list.replace_step(0, 0, stale).unwrap(); + assert!(atn_cmds::export("Direct adjustments", &[&s.actions().list.actions()[0]], &[], false).is_err(), "stale color metadata must not fall through to GdMp"); for p in [json!({"color":"#ff0000"}), json!({"labMinimum":[40,0,0],"labMaximum":[60,0,0],"hue":0.5})] { let a = photocraft_engine::actions_cmds::Action::new("Native", vec![ActionStep::new("image.adjustments.replaceColor", p)]); assert!(atn_cmds::export("Direct adjustments", &[&a], &[], false).is_err()); @@ -376,7 +377,7 @@ fn recorded_replace_color_clamps_shifts_and_plays_the_lab_box_at_every_depth() { std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).selection = Some(mask); } let before = raw(&s); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); play(&mut s); let after = raw(&s); if inverse { diff --git a/crates/engine/tests/it/atn_layer_style.rs b/crates/engine/tests/it/atn_layer_style.rs index 8fe473536e..f6b4ad72be 100644 --- a/crates/engine/tests/it/atn_layer_style.rs +++ b/crates/engine/tests/it/atn_layer_style.rs @@ -1,4 +1,5 @@ //! Measured layer-style action steps retain their settings and use the existing native commands. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value as D}, @@ -145,7 +146,7 @@ fn create_layers_playback_matches_native_effect_layers_and_undo_at_each_depth() let (mut recorded, source) = fixture(depth); let before = recorded.active().unwrap().doc.clone(); let past = recorded.active().unwrap().history.past_len(); - recorded.actions.list.push(action(vec![item(CREATE, create())])).unwrap(); + recorded.actions_mut().list.push(action(vec![item(CREATE, create())])).unwrap(); let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{depth}: {result}"); @@ -176,7 +177,7 @@ fn scale_effects_playback_matches_native_settings_and_undo_at_each_depth() { recorded.execute("actions.setHistory", json!({"singleState":single_state})).unwrap(); let before = recorded.active().unwrap().doc.clone(); let past = recorded.active().unwrap().history.past_len(); - recorded.actions.list.push(action(vec![item(SCALE, scale(percent))])).unwrap(); + recorded.actions_mut().list.push(action(vec![item(SCALE, scale(percent))])).unwrap(); let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{depth}/{percent}: {result}"); @@ -202,7 +203,7 @@ fn scale_then_create_layers_matches_native_sequence() { recorded.execute("actions.setHistory", json!({"singleState":single_state})).unwrap(); let before = recorded.active().unwrap().doc.clone(); let past = recorded.active().unwrap().history.past_len(); - recorded.actions.list.push(action(vec![item(SCALE, scale(200.0)), item(CREATE, create())])).unwrap(); + recorded.actions_mut().list.push(action(vec![item(SCALE, scale(200.0)), item(CREATE, create())])).unwrap(); let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 2); assert!(result.get("failed").is_none()); @@ -369,7 +370,7 @@ fn layer_style_malformed_records_stay_kept_without_an_edit() { let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); for action in loaded.actions { - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); } let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 0); @@ -390,7 +391,7 @@ fn miskeyed_effects_reference_stays_whole_without_a_blank_layer_edit() { let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); for action in loaded.actions.clone() { - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); } let result = s.execute("actions.play", json!({"action": 0})).unwrap(); // Play before checking import classification: the old path actually creates a blank layer. @@ -426,7 +427,7 @@ fn ordinary_layer_make_remains_a_legitimate_control() { assert_eq!(a.steps[0].command, "layer.new.layer"); let (mut s, source) = fixture(8); let before = s.active().unwrap().doc.clone(); - s.actions.list.push(a).unwrap(); + s.actions_mut().list.push(a).unwrap(); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none()); @@ -470,7 +471,7 @@ fn nested_effects_references_stay_whole_without_a_blank_layer_edit() { let before = s.active().unwrap().doc.clone(); let past = s.active().unwrap().history.past_len(); for action in loaded.actions.clone() { - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); } let result = s.execute("actions.play", json!({"action": 0})).unwrap(); // Playback precedes classification so the baseline exposes the actual blank-layer edit. @@ -514,7 +515,7 @@ fn ordinary_layer_make_native_export_matches_native_playback() { let (mut recorded, source) = fixture(8); let before = recorded.active().unwrap().doc.clone(); let past = recorded.active().unwrap().history.past_len(); - recorded.actions.list.push(a).unwrap(); + recorded.actions_mut().list.push(a).unwrap(); let result = recorded.execute("actions.play", json!({"action": 0})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none()); diff --git a/crates/engine/tests/it/atn_mapped_identifiers.rs b/crates/engine/tests/it/atn_mapped_identifiers.rs index 6fb8097bb2..0293f7aa7b 100644 --- a/crates/engine/tests/it/atn_mapped_identifiers.rs +++ b/crates/engine/tests/it/atn_mapped_identifiers.rs @@ -1,5 +1,6 @@ //! Recorded identifiers must match Photoshop, even when a local round trip would accept a typo. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, @@ -30,7 +31,7 @@ fn replay_saved(s: &mut Session, action: &Action) { let imported = atn_cmds::import(&bytes).unwrap(); assert!(imported.unsupported.is_empty()); assert_eq!(imported.actions[0].steps, action.steps); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = s.execute("actions.play", json!({"action":"Recorded"})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{result}"); @@ -112,7 +113,7 @@ fn review_null_percent_is_omitted_by_the_native_resize() { assert!(skipped.is_empty()); let imported = atn_cmds::import(&bytes).unwrap(); let mut replayed = sized_document(20, 10, 144); - replayed.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replayed.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = replayed.execute("actions.play", json!({"action":"Recorded"})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); assert_eq!(replayed.active().unwrap().doc.size, expected.active().unwrap().doc.size); @@ -134,7 +135,7 @@ fn review_point_resize_exports_the_default_resampler() { let mut expected = sized_document(40, 20, 144); expected.execute("image.imageSize", params).unwrap(); let mut actual = sized_document(40, 20, 144); - actual.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + actual.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = actual.execute("actions.play", json!({"action":"Recorded"})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); let (a, b) = (&actual.active().unwrap().doc, &expected.active().unwrap().doc); @@ -157,7 +158,7 @@ fn review_copy_cut_opacity_is_validated_before_any_step_runs() { let mut s = sized_document(8, 6, 72); s.execute("select.rect", json!({"x":0,"y":0,"width":2,"height":2})).unwrap(); let before = s.active().unwrap().doc.clone(); - s.actions.list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); let result = s.execute("actions.play", json!({"action":"Recorded"})).unwrap(); assert!(result.get("failed").is_some()); assert_eq!(s.active().unwrap().doc, before); @@ -384,7 +385,7 @@ fn review_10702_transparency_names_resolve_at_playback() { } s.execute("layer.new.layer", json!({"name":"Active"})).unwrap(); s.execute("edit.fill", json!({"contents":"color","color":"#ffffff"})).unwrap(); - s.actions.list = ActionList::from_file(ActionsFile::new(vec![action.clone()], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![action.clone()], Vec::new())); let played = s.execute("actions.play", json!({"action":"Recorded"})).unwrap(); assert_eq!(played["ran"], 1, "{played}"); let doc = &s.active().unwrap().doc; diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 67e3f60b9a..80f6c1058d 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -1,4 +1,5 @@ //! #10700: recorded Link and Unlink must not replay as a state-dependent toggle. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, @@ -184,7 +185,7 @@ fn atn_link_events_keep_descriptors_and_replay_the_requested_operation() { let descriptor = Descriptor::new("null").with("null", target()); let mut s = fixture(&initial, &[0, 1]); assert_eq!(load(&mut s, &file(event, descriptor.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("layer.linkLayers", json!({"linked": linked}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("layer.linkLayers", json!({"linked": linked}))]); let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); @@ -262,7 +263,7 @@ fn targeted(event: &str, explicit: bool) -> Descriptor { fn load_targeted(s: &mut Session, event: &str, id: &str, explicit: bool) { assert_eq!(load(s, &file(event, targeted(event, explicit)))["unsupported"], json!([]), "{event}"); let p = if explicit { json!({}) } else { json!({"_atnNoTarget": true}) }; - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new(id, p)]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new(id, p)]); } #[test] @@ -297,7 +298,7 @@ fn bare_link_events_keep_their_operation_and_empty_keys() { let initial = if linked { None } else { Some(77) }; let mut s = fixture(&[initial, initial], &[0, 1]); assert_eq!(load(&mut s, &file(event, Descriptor::new(event)))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"linked": linked, "_atnNoTarget": true})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"linked": linked, "_atnNoTarget": true})); let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0].descriptor, Some(Descriptor::new("null"))); @@ -445,7 +446,7 @@ fn crop_parent_runs_once_and_the_kept_helper_stops_the_duplicate_crop_tail() { let report = load(&mut s, &atn::write(&f).unwrap()); assert_eq!(report["unsupported"].as_array().unwrap().len(), 1); assert_eq!( - s.actions.list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect::>(), + s.actions().list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect::>(), ["file.automate.cropAndStraightenPhotos", "actions.photoshopStep", "image.duplicate", "image.crop"] ); let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); @@ -510,8 +511,8 @@ fn artboard_recorded_flags_and_guides_roundtrip_without_resizing() { d.items.pop(); } assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].command, "layer.new.artboardFromGroup"); - assert_eq!(s.actions.list.actions()[0].steps[0].params["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(s.actions().list.actions()[0].steps[0].command, "layer.new.artboardFromGroup"); + assert_eq!(s.actions().list.actions()[0].steps[0].params["color"], json!([0.25, 0.5, 0.75])); assert_eq!(saved_item(&mut s).descriptor, Some(d)); play(&mut s); let doc = &s.active().unwrap().doc; @@ -539,7 +540,7 @@ fn artboard_target_only_form_keeps_existing_native_group_behavior() { let before = s.active().unwrap().doc.clone(); let d = Descriptor::new("null").with("null", target()); assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("layer.new.artboardFromGroup", json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("layer.new.artboardFromGroup", json!({}))]); assert_eq!(saved_item(&mut s).descriptor, Some(d)); play(&mut s); assert!(s.active().unwrap().doc.layers[0].artboard().is_some()); @@ -599,7 +600,7 @@ fn artboard_fractional_colors_survive_import_save_and_playback() { D::Descriptor(["Rd ", "Grn ", "Bl "].into_iter().zip(rgb).fold(Descriptor::new("RGBC"), |color, (key, n)| color.with(key, D::Double(n)))); assert_eq!(load(&mut s, &file(event, d.clone()))["unsupported"], json!([])); assert_eq!(saved_item(&mut s).descriptor, Some(d)); - let ActionStep { command: id, params: mut changed } = s.actions.list.actions()[0].steps[0].clone(); + let ActionStep { command: id, params: mut changed } = s.actions().list.actions()[0].steps[0].clone(); changed["color"][0] = 0.5.into(); assert!(atn_cmds::export("Links", &[&Action::new("Changed", vec![ActionStep::new(id, changed)])], &[], false).is_err()); let before = s.active().unwrap().doc.clone(); @@ -649,7 +650,7 @@ fn artboard_omitted_type_defaults_to_white_and_invalid_native_settings_are_atomi Descriptor::new("null").with("null", target()).with("artboard", D::Descriptor(artboard_settings(None, vec![]))).with("changeBackground", D::Integer(1)); assert_eq!(load(&mut s, &file("artboardFromLayerGroupEvent", d.clone()))["unsupported"], json!([])); assert_eq!(saved_item(&mut s).descriptor, Some(d)); - let mut changed = s.actions.list.actions()[0].steps[0].params.clone(); + let mut changed = s.actions().list.actions()[0].steps[0].params.clone(); changed["background"] = "black".into(); assert!(atn_cmds::export("Links", &[&Action::new("A", vec![ActionStep::new("layer.new.artboardFromGroup", changed)])], &[], false).is_err()); play(&mut s); @@ -703,7 +704,7 @@ fn artboard_background_edit_roundtrips_without_replaying_recorded_geometry() { let history = s.active().unwrap().history.past_len(); let d = artboard_edit_descriptor(kind, 8); assert_eq!(load(&mut s, &file("editArtboardEvent", d.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].command, "layer.artboard.set"); + assert_eq!(s.actions().list.actions()[0].steps[0].command, "layer.artboard.set"); assert_eq!(saved_item(&mut s).descriptor, Some(d)); play(&mut s); let doc = &s.active().unwrap().doc; @@ -738,7 +739,7 @@ fn artboard_edit_refuses_unmeasured_modes_and_lossy_native_exports() { assert_eq!(s.active().unwrap().history.past_len(), history); } load(&mut s, &file("editArtboardEvent", artboard_edit_descriptor(4, 8))); - let params = s.actions.list.actions()[0].steps[0].params.clone(); + let params = s.actions().list.actions()[0].steps[0].params.clone(); for (key, value) in [("rect", json!([0, 0, 100, 100])), ("preset", json!("iPhone 14")), ("changeSizes", json!(4)), ("changeBackground", json!(0))] { let mut edited = params.clone(); edited[key] = value; @@ -932,7 +933,7 @@ fn make_type_shape_roundtrips_and_converts_actual_glyphs_with_undo() { Arc::make_mut(s.active_mut().unwrap().doc_mut()).layer_mut(id).unwrap().psd_blocks.push((*b"TySh", Arc::new(vec![1, 2, 3]))); let before = s.active().unwrap().doc.clone(); assert_eq!(load(&mut s, &file("Mk ", make_type_descriptor()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new("type.convertToShape", json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("type.convertToShape", json!({}))]); let saved = saved_item(&mut s); assert_eq!(saved.event, AtnEvent::Code(*b"Mk ")); let mut canonical = make_type_descriptor(); @@ -967,7 +968,7 @@ fn make_type_shape_keeps_wrong_references_and_preserves_fill_mappings() { assert!(skipped.is_empty()); let mut s = Session::new(); assert_eq!(load(&mut s, &bytes)["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].command, id); + assert_eq!(s.actions().list.actions()[0].steps[0].command, id); } let action = Action::new("A", vec![ActionStep::new("type.convertToShape", json!({"layer": 1}))]); assert!(atn_cmds::export("Links", &[&action], &[], false).is_err()); @@ -1019,7 +1020,7 @@ fn shape_blur_radius_boundaries_keep_their_value_without_running_large_kernels() let mut s = Session::new(); let mut canonical = radius_descriptor(radius); assert_eq!(load(&mut s, &file("shapeBlur", canonical.clone()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].params["radius"].as_f64(), Some(radius)); + assert_eq!(s.actions().list.actions()[0].steps[0].params["radius"].as_f64(), Some(radius)); canonical.class_id = Id::new("null"); assert_eq!(saved_item(&mut s).descriptor, Some(canonical)); } @@ -1143,7 +1144,7 @@ fn smart_paths_roundtrip_and_play_real_files_on_the_current_target() { recorded = recorded.with("LyrI", D::Integer(hint)); } assert_eq!(load(&mut s, &file(event, recorded))["unsupported"], json!([]), "{event}"); - assert_eq!(s.actions.list.actions()[0].steps, [ActionStep::new(id, json!({"path": path}))]); + assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new(id, json!({"path": path}))]); let saved = s.execute("actions.save", json!({"set": "Links"})).unwrap(); assert_eq!(saved["skipped"], json!([])); let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); diff --git a/crates/engine/tests/it/atn_perspective_warp.rs b/crates/engine/tests/it/atn_perspective_warp.rs index 680b0c0fb0..436745df24 100644 --- a/crates/engine/tests/it/atn_perspective_warp.rs +++ b/crates/engine/tests/it/atn_perspective_warp.rs @@ -1,5 +1,6 @@ //! The measured Perspective Warp descriptor shape through ATN conversion and action playback. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, @@ -171,7 +172,7 @@ fn action_playback_matches_the_native_raster_warp() { let decoy = actual.active().unwrap().active_layer.unwrap(); let decoy_before = actual.active().unwrap().doc.layer(decoy).unwrap().clone(); for action in imported(fixture(Some("Facade")), false, true).actions { - actual.actions.list.push(action).unwrap(); + actual.actions_mut().list.push(action).unwrap(); } actual.execute("actions.play", json!({"action":0})).unwrap(); direct.execute(COMMAND, json!({"planes":planes(),"layer":"Facade","target":"pixels"})).unwrap(); @@ -193,7 +194,7 @@ fn active_smart_object_playback_matches_the_native_filter() { s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); } for action in imported(fixture(None), false, true).actions { - actual.actions.list.push(action).unwrap(); + actual.actions_mut().list.push(action).unwrap(); } actual.execute("actions.play", json!({"action":0})).unwrap(); direct.execute("layer.smartObjects.perspectiveWarp", json!({"planes":planes()})).unwrap(); diff --git a/crates/engine/tests/it/atn_reference_forms.rs b/crates/engine/tests/it/atn_reference_forms.rs index 18885108fd..c605bebc15 100644 --- a/crates/engine/tests/it/atn_reference_forms.rs +++ b/crates/engine/tests/it/atn_reference_forms.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_engine::{ @@ -17,7 +18,7 @@ fn ordinal(name: &str) -> ReferenceItem { fn load(s: &mut Session, reference: ReferenceItem) { let descriptor = Descriptor::new("null").with("null", D::Reference(vec![reference])); - s.actions.list = ActionList::from_file(ActionsFile::new(vec![imported(AtnEvent::Code(*b"slct"), descriptor)], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![imported(AtnEvent::Code(*b"slct"), descriptor)], Vec::new())); } fn bytes(event: AtnEvent, descriptor: Descriptor) -> Vec { @@ -53,7 +54,7 @@ fn roundtrip(action: &Action, reference: &ReferenceItem, target: Option<&Referen } fn replay(s: &mut Session, action: &Action) { - s.actions.list = ActionList::from_file(ActionsFile::new(vec![action.clone()], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![action.clone()], Vec::new())); let result = s.execute("actions.play", json!({"action":"Select"})).unwrap(); assert_eq!(result["ran"], 1, "{result}"); assert!(result.get("failed").is_none(), "{result}"); @@ -433,7 +434,7 @@ fn unrepresentable_comp_indexes_are_rejected_before_recording() { } s.execute("actions.stop", json!({})).unwrap(); assert!(accepted.is_empty(), "unrepresentable indexes were accepted: {accepted:?}"); - assert!(s.actions.list.actions().last().unwrap().steps.is_empty()); + assert!(s.actions().list.actions().last().unwrap().steps.is_empty()); } /// Valid extreme indexes survive recording and export as ATN Index references. @@ -445,7 +446,7 @@ fn accepted_comp_boundary_indexes_record_and_export() { s.execute("layerComp.apply", json!({"comp":{"index":valid}})).unwrap(); } s.execute("actions.stop", json!({})).unwrap(); - let action = s.actions.list.actions().last().unwrap(); + let action = s.actions().list.actions().last().unwrap(); assert_eq!(action.steps.len(), 2); let (saved, skipped) = atn_cmds::export("References", &[action], &[], false).unwrap(); assert!(skipped.is_empty()); @@ -496,7 +497,7 @@ fn group_end_index_never_targets_the_selection() { let offset = Descriptor::new("Ofst").with("Hrzn", D::UnitFloat { unit: *b"#Pxl", value: 1.0 }).with("Vrtc", D::UnitFloat { unit: *b"#Pxl", value: 0.0 }); let action = imported(AtnEvent::Code(*b"move"), Descriptor::new("null").with("null", D::Reference(vec![index("Lyr ", 3)])).with("T ", D::Descriptor(offset))); - s.actions.list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(vec![action], Vec::new())); let result = s.execute("actions.play", json!({"action":"Select"})).unwrap(); assert!(result.get("failed").is_some(), "{result}"); assert_eq!(s.active().unwrap().history.past_len(), past); diff --git a/crates/engine/tests/it/atn_review_regressions.rs b/crates/engine/tests/it/atn_review_regressions.rs index 94c8c543bd..05675efd30 100644 --- a/crates/engine/tests/it/atn_review_regressions.rs +++ b/crates/engine/tests/it/atn_review_regressions.rs @@ -1,4 +1,5 @@ //! Public-API regressions for the dialog-event and Batch review findings. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_doc::LayerContent; @@ -150,7 +151,7 @@ fn custom_supported_representations_map_and_save_losslessly() { let mut native = session("rgb"); native.execute("filter.other.custom", action.steps[0].params.clone()).unwrap(); let mut played = session("rgb"); - played.actions.list.push(action.clone()).unwrap(); + played.actions_mut().list.push(action.clone()).unwrap(); played.execute("actions.play", json!({"action":action.name})).unwrap(); let commands: Vec<_> = played.journal.iter().filter(|(id, _)| id == "filter.other.custom").collect(); assert!(!commands.is_empty()); @@ -158,8 +159,8 @@ fn custom_supported_representations_map_and_save_losslessly() { let (id, last) = photocraft_engine::filters::last_filter(&played).unwrap(); assert_eq!(id, "filter.other.custom"); assert!(last.get("__atnCustom").is_none()); - assert!(played.actions.list.actions()[0].steps[0].params.get("__atnCustom").is_some()); - assert_eq!(exported(&played.actions.list.actions()[0]), d, "Save Actions still owns the original descriptor"); + assert!(played.actions().list.actions()[0].steps[0].params.get("__atnCustom").is_some()); + assert_eq!(exported(&played.actions().list.actions()[0]), d, "Save Actions still owns the original descriptor"); assert_eq!(photocraft_compose::flatten(&played.active().unwrap().doc).px, photocraft_compose::flatten(&native.active().unwrap().doc).px); action.steps[0].params["scale"] = json!(4); assert_eq!(exported(&action).get("Scl "), Some(&D::Integer(4)), "editing must not reuse stale original metadata"); @@ -237,7 +238,7 @@ fn named_batch_resolves_recorded_layer_targets() { source.execute("layer.new.layer", json!({"name":"Active"})).unwrap(); std::fs::write(&input, photocraft_format::save_to_bytes(&source.active().unwrap().doc, &Default::default()).unwrap()).unwrap(); let mut s = Session::new(); - s.actions + s.actions_mut() .list .push(Action::new("Hide", vec![ActionStep::new("layer.setProps", json!({"visible":false,"_actionLayer":{"name":"Target","ordinal":0}}))])) .unwrap(); @@ -647,10 +648,10 @@ fn imported_batch_references_follow_collision_renames_once_and_keep_other_sets() let mut s = Session::new(); let mut old = Action::new("Child", vec![ActionStep::new("select.deselect", json!({}))]); old.set = Some("Other".into()); - s.actions.list.push(old).unwrap(); + s.actions_mut().list.push(old).unwrap(); let loaded = s.execute("actions.load", json!({"data":photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap()),"replace":false})).unwrap(); let own_name = loaded["actions"][1].as_str().unwrap(); - let imported = &s.actions.list.actions()[1]; + let imported = &s.actions().list.actions()[1]; assert_eq!(imported.steps[0].params["action"], own_name); assert_eq!(imported.steps[1].params["action"], "Child"); assert_eq!(imported.steps[1].params["set"], "Other"); @@ -701,7 +702,7 @@ fn batch_unqualified_export_keeps_cross_set_resolution() { let mut child = Action::new("Child", vec![ActionStep::new("image.imageSize", json!({"width":3,"height":1,"resample":"nearest"}))]); child.set = Some("Other set".into()); let mut s = Session::new(); - s.actions.list.push(child).unwrap(); + s.actions_mut().list.push(child).unwrap(); let result = s.execute("file.automate.batch", batch).unwrap(); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); let doc = photocraft_io::import("out.png", &std::fs::read(result["files"][0].as_str().unwrap()).unwrap()).unwrap().document; @@ -723,10 +724,10 @@ fn batch_load_override_preserves_original_set_identity_and_foreign_references() if collision { let mut old = Action::new("Child", vec![ActionStep::new("image.imageSize", json!({"width":5,"height":1,"resample":"nearest"}))]); old.set = Some("Destination".into()); - s.actions.list.push(old).unwrap(); + s.actions_mut().list.push(old).unwrap(); } let loaded = s.execute("actions.load", json!({"data":photocraft_paint::tile::b64_encode(&bytes),"set":"Destination","replace":false})).unwrap(); - let parent = s.actions.list.actions().iter().find(|a| a.name == loaded["actions"][0].as_str().unwrap()).unwrap(); + let parent = s.actions().list.actions().iter().find(|a| a.name == loaded["actions"][0].as_str().unwrap()).unwrap(); let batch = parent.steps[0].params.clone(); assert_eq!(batch["set"], "Destination"); assert_eq!(batch["action"], if foreign { json!("Child") } else { loaded["actions"][1].clone() }); @@ -976,7 +977,7 @@ fn called_actions_packages_explicit_batch_children_and_replays_them() { assert_eq!(rewritten["kept"], 17); } let mut s = Session::new(); - s.actions.list = ActionList::from_file(ActionsFile::new(captured, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(captured, Vec::new())); let result = s.execute(&steps[0].0, steps[0].1.clone()).unwrap(); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); let doc = photocraft_io::import("saved.png", &std::fs::read(result["files"][0].as_str().unwrap()).unwrap()).unwrap().document; @@ -1008,7 +1009,7 @@ fn called_actions_packages_shared_descendants_at_the_shallowest_depth() { assert_eq!(captured.iter().map(|a| &a.name).collect::>(), list.iter().map(|a| &a.name).collect::>()); assert_eq!(captured[0].steps[0].params["action"], "Child"); let mut s = Session::new(); - s.actions.list = ActionList::from_file(ActionsFile::new(captured, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(captured, Vec::new())); let result = s.execute(&steps[0].0, steps[0].1.clone()).unwrap(); assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); diff --git a/crates/engine/tests/it/atn_ripple_amount.rs b/crates/engine/tests/it/atn_ripple_amount.rs index dc831a8bb4..deb2edcd3e 100644 --- a/crates/engine/tests/it/atn_ripple_amount.rs +++ b/crates/engine/tests/it/atn_ripple_amount.rs @@ -1,4 +1,5 @@ //! #7670: integer ATN Ripple amounts must never silently replace native fractions. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; use photocraft_engine::{Session, atn_cmds}; @@ -39,7 +40,7 @@ fn fractional_amounts_remain_native_and_are_refused_by_strict_export() { let mut direct = fixture(depth); direct.execute(RIPPLE, params).unwrap(); let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": "Fractional Ripple"})).unwrap(); assert_eq!(pixels(&direct), pixels(&native)); @@ -53,7 +54,7 @@ fn fractional_amounts_remain_native_and_are_refused_by_strict_export() { assert!(skipped.is_empty() && imported.unsupported.is_empty() && imported.warnings.is_empty()); let exported = imported.actions[0].steps[0].params["amount"].clone(); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Fractional Ripple"})).unwrap(); let changed = pixels(&replay) != pixels(&direct); if amount == 81.4 { @@ -82,7 +83,7 @@ fn integer_amounts_sizes_and_defaults_preserve_playback() { let mut direct = fixture(depth); direct.execute(RIPPLE, params.clone()).unwrap(); let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": "Integer Ripple"})).unwrap(); assert_eq!(pixels(&native), pixels(&direct)); @@ -99,7 +100,7 @@ fn integer_amounts_sizes_and_defaults_preserve_playback() { assert_eq!(imported.actions[0].steps.len(), 1); assert_eq!(imported.actions[0].steps[0].command, RIPPLE); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Integer Ripple"})).unwrap(); assert_eq!(pixels(&replay), pixels(&direct), "depth {depth}: {params}"); } diff --git a/crates/engine/tests/it/atn_selective_color.rs b/crates/engine/tests/it/atn_selective_color.rs index 0eb63125e5..6be0043d54 100644 --- a/crates/engine/tests/it/atn_selective_color.rs +++ b/crates/engine/tests/it/atn_selective_color.rs @@ -1,4 +1,5 @@ //! #7672: strict ATN export must preserve both accepted Selective Color parameter forms. +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; use photocraft_engine::{Session, atn_cmds}; use serde_json::{Value, json}; @@ -54,7 +55,7 @@ fn check_cases(id: &str, cases: &[Value], require_effect: bool) { } let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": action.name})).unwrap(); assert_eq!(pixels(&native), expected, "native replay: {id}, depth {depth}, {params}"); @@ -68,7 +69,7 @@ fn check_cases(id: &str, cases: &[Value], require_effect: bool) { assert_eq!(imported.actions[0].steps[0].command, id); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": action.name})).unwrap(); if pixels(&replay) != expected { failures.push(format!("{id}, depth {depth}, {params}")); diff --git a/crates/engine/tests/it/atn_shape_blur.rs b/crates/engine/tests/it/atn_shape_blur.rs index d9b25ea0cc..d67a4a8c02 100644 --- a/crates/engine/tests/it/atn_shape_blur.rs +++ b/crates/engine/tests/it/atn_shape_blur.rs @@ -1,3 +1,6 @@ +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_doc::LayerContent; @@ -94,7 +97,7 @@ fn smart_filter_params_resolve_custom_shapes_and_keep_portable_geometry() { assert_eq!(saved(&s), after); let mut reopened = Session::new(); - assert!(!reopened.presets.shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID))); + assert!(!reopened.presets().shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID))); reopened.add_document(photocraft_format::load_from_bytes(&after).unwrap(), None); reopened.execute("layer.smartFilter.setParams", json!({"index":0,"params":{"radius":6}})).unwrap(); assert_eq!(smart_params(&reopened)["shapePath"], path); @@ -127,7 +130,7 @@ fn smart_filter_selector_changes_replace_the_old_custom_geometry() { let stale = if replacement.get("shapeId").is_some() { "shapeName" } else { "shapeId" }; assert!(smart_params(&s).get(stale).is_none()); let mut expected = fixture(16); - expected.load_presets_json(s.presets.to_json(&s)); + expected.load_presets_json(s.presets().to_json(&s)); expected.execute("filter.convertForSmartFilters", json!({})).unwrap(); expected.execute("filter.blur.shapeBlur", json!({"radius":5,"shapeId":"replacement-triangle"})).unwrap(); assert_ne!(pixels(&s), old_pixels); @@ -213,7 +216,7 @@ fn custom_shape_uses_installed_id_despite_name_collision_and_undoes() { let mut s = fixture(depth); install_square(&mut s); let before = saved(&s); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); assert_eq!(s.execute("actions.play", json!({"action":"Shape"})).unwrap()["ran"], 1); assert_eq!(pixels(&s), expected, "{depth}-bit square custom kernel"); s.execute("edit.undo", json!({})).unwrap(); @@ -240,7 +243,7 @@ fn custom_shape_smart_filter_keeps_geometry_across_save_without_preset_library() .unwrap(); assert!(filter.params["shapePath"].is_object()); let mut reopened = Session::new(); - assert!(!reopened.presets.shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID))); + assert!(!reopened.presets().shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID))); reopened.add_document(doc, None); reopened.execute("layer.smartFilter.setVisible", json!({"index":0,"visible":false})).unwrap(); assert_ne!(pixels(&reopened), expected); @@ -257,7 +260,7 @@ fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() let p = json!({"data":photocraft_paint::tile::b64_encode(&bytes)}); s.execute("shape.presets.importCsh", p.clone()).unwrap(); s.execute("shape.presets.importCsh", p).unwrap(); - let matches: Vec<_> = s.presets.shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id.as_str())).collect(); + let matches: Vec<_> = s.presets().shapes.iter().flat_map(|g| &g.items).filter(|shape| shape.id.as_deref() == Some(id.as_str())).collect(); assert_eq!(matches.len(), 2, "both imports retain the source's opaque ID"); let path = photocraft_engine::vector_cmds::path_json(&matches[0].path); let mut expected = fixture(16); @@ -265,7 +268,7 @@ fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() let mut square = fixture(16); square.execute("filter.blur.shapeBlur", json!({"radius":5,"shape":"square"})).unwrap(); assert_ne!(pixels(&expected), pixels(&square), "the non-square imported triangle must differ from a square kernel"); - let prefs = s.presets.to_json(&s); + let prefs = s.presets().to_json(&s); let mut s = fixture(16); s.load_presets_json(prefs); let shape = @@ -276,7 +279,7 @@ fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() .with("keyOriginType", D::Integer(9)); let imported = atn_cmds::import(&encoded(d)).unwrap(); assert!(imported.unsupported.is_empty()); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let before = saved(&s); assert_eq!(s.execute("actions.play", json!({"action":"Shape"})).unwrap()["ran"], 1); assert_eq!(pixels(&s), pixels(&expected)); @@ -314,7 +317,7 @@ fn missing_or_invalid_custom_shapes_refuse_before_document_or_history_changes() assert_eq!(s.active().unwrap().history.past_len(), history); } let imported = atn_cmds::import(&encoded(descriptor())).unwrap(); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); // Playback reports a failed step in its successful response; native command errors are not outer errors. let result = s.execute("actions.play", json!({"action":"Shape"})).unwrap(); assert_eq!(result["ran"], 0); @@ -332,7 +335,7 @@ fn shape_ids_persist_and_old_preferences_without_ids_still_load() { let prefs = s.prefs_to_json(); let mut reopened = Session::new(); reopened.load_prefs_json(&prefs).unwrap(); - assert!(reopened.presets.shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID) && shape.name == "Renamed Square")); + assert!(reopened.presets().shapes.iter().flat_map(|g| &g.items).any(|shape| shape.id.as_deref() == Some(SHAPE_ID) && shape.name == "Renamed Square")); let before = reopened.prefs_to_json(); assert!(reopened.execute("shape.presets.new", json!({"id":SHAPE_ID,"path":"M 0 0 L 10 0 L 5 10 Z"})).is_err()); assert_eq!(reopened.prefs_to_json(), before); @@ -343,7 +346,7 @@ fn shape_ids_persist_and_old_preferences_without_ids_still_load() { } } reopened.load_prefs_json(&old.to_string()).unwrap(); - assert!(reopened.presets.shapes.iter().flat_map(|g| &g.items).all(|shape| shape.id.is_none())); + assert!(reopened.presets().shapes.iter().flat_map(|g| &g.items).all(|shape| shape.id.is_none())); } /// Outer descriptor metadata and its encoding stay whole when the native mapper cannot reproduce them. diff --git a/crates/engine/tests/it/atn_shear.rs b/crates/engine/tests/it/atn_shear.rs index 649c4496e4..276f7cdc11 100644 --- a/crates/engine/tests/it/atn_shear.rs +++ b/crates/engine/tests/it/atn_shear.rs @@ -1,4 +1,5 @@ //! Public load/save/playback witnesses for the measured Shear action mapping. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::{ @@ -178,7 +179,7 @@ fn shear_unrepresentable_steps_stay_kept_without_partial_playback() { let past = s.active().unwrap().history.past_len(); let name = loaded.actions[0].name.clone(); for action in loaded.actions { - s.actions.list.push(action).unwrap(); + s.actions_mut().list.push(action).unwrap(); } let report = s.execute("actions.play", json!({"action":name})).unwrap(); assert_eq!(report["ran"], 0); diff --git a/crates/engine/tests/it/atn_stack_modes.rs b/crates/engine/tests/it/atn_stack_modes.rs index 1085f83cba..dd4f6434ee 100644 --- a/crates/engine/tests/it/atn_stack_modes.rs +++ b/crates/engine/tests/it/atn_stack_modes.rs @@ -1,5 +1,6 @@ //! The measured Smart Object Stack Mode events retain their descriptor and native behavior. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, @@ -158,7 +159,7 @@ fn stack_recordings_play_native_modes_and_undo_at_each_depth() { let expected = s.active().unwrap().doc.clone(); s.execute("edit.undo", json!({})).unwrap(); let imported = load(source); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = s.execute("actions.play", json!({"action":"Mode","set":"Stacks"})).unwrap(); assert_eq!(result["ran"], 1, "{result}"); let actual = s.active().unwrap(); @@ -204,7 +205,7 @@ fn unsupported_stack_recordings_save_whole_and_refuse_playback() { s.execute("layer.smartObjects.stackMode.maximum", json!({})).unwrap(); let before = s.active().unwrap().doc.clone(); let history = s.active().unwrap().history.past_len(); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = s.execute("actions.play", json!({"action":"Mode","set":"Stacks"})).unwrap(); assert!(result.get("failed").is_some(), "{result}"); assert_eq!(s.active().unwrap().doc.layers, before.layers); diff --git a/crates/engine/tests/it/atn_stroke_width.rs b/crates/engine/tests/it/atn_stroke_width.rs index 3a2951374c..7f80f462b3 100644 --- a/crates/engine/tests/it/atn_stroke_width.rs +++ b/crates/engine/tests/it/atn_stroke_width.rs @@ -1,4 +1,5 @@ //! #7671: exported Stroke widths must have the same effect as command execution. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; use photocraft_engine::{Session, atn_cmds}; @@ -54,7 +55,7 @@ fn check_pixels(widths: &[(f64, u32)]) { } let mut native = fixture(depth); - native.actions.list.push(action.clone()).unwrap(); + native.actions_mut().list.push(action.clone()).unwrap(); native.execute("actions.play", json!({"action": "Stroke"})).unwrap(); assert_eq!(pixels(&native), expected); @@ -68,7 +69,7 @@ fn check_pixels(widths: &[(f64, u32)]) { assert_eq!(imported.actions[0].steps[0].command, "edit.stroke"); let imported_width = imported.actions[0].steps[0].params["width"].clone(); let mut replay = fixture(depth); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Stroke"})).unwrap(); if pixels(&replay) != expected { lost.push(format!("depth {depth}, {location}, width {width} -> {imported_width}, expected {effective}")); @@ -134,7 +135,7 @@ fn descriptor_width_matches_defaults_limits_and_other_stroke_options() { let mut direct = fixture(8); direct.execute("edit.stroke", params).unwrap(); let mut replay = fixture(8); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Stroke"})).unwrap(); assert_eq!(pixels(&replay), pixels(&direct)); } @@ -149,7 +150,7 @@ fn descriptor_width_matches_defaults_limits_and_other_stroke_options() { let mut direct = fixture(8); direct.execute("edit.stroke", Value::Null).unwrap(); let mut replay = fixture(8); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); replay.execute("actions.play", json!({"action": "Default"})).unwrap(); assert_eq!(pixels(&replay), pixels(&direct)); } diff --git a/crates/engine/tests/it/atn_type_path.rs b/crates/engine/tests/it/atn_type_path.rs index 2f7d1b4692..5530a31219 100644 --- a/crates/engine/tests/it/atn_type_path.rs +++ b/crates/engine/tests/it/atn_type_path.rs @@ -1,4 +1,5 @@ //! Recorded Type > Create Work Path preserves its descriptor and uses native glyph outlines. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, @@ -101,9 +102,9 @@ fn playback_matches_native_path_and_preserves_text_with_undo_redo() { d.items.reverse(); d.name = UnicodeString::new_nul("Recorded path"); } - recorded.actions.list = ActionList::from_file(ActionsFile::new(load(item(d)).actions, Vec::new())); + recorded.actions_mut().list = ActionList::from_file(ActionsFile::new(load(item(d)).actions, Vec::new())); if noncanonical { - assert!(recorded.actions.list.actions()[0].steps[0].params.get(SOURCE).is_some()); + assert!(recorded.actions().list.actions()[0].steps[0].params.get(SOURCE).is_some()); } let result = recorded.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 1); @@ -163,7 +164,7 @@ fn non_text_and_no_document_playback_fail_without_edits() { s.execute("file.new", json!({"width":8,"height":8})).unwrap(); } let before = s.active().map(|st| (st.doc.clone(), st.history.past_len())); - s.actions.list = ActionList::from_file(ActionsFile::new(load(item(descriptor())).actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(load(item(descriptor())).actions, Vec::new())); let result = s.execute("actions.play", json!({"action":0})).unwrap(); assert_eq!(result["ran"], 0); assert!(result.get("failed").is_some(), "{result}"); diff --git a/crates/engine/tests/it/atn_v12.rs b/crates/engine/tests/it/atn_v12.rs index 731215f3eb..60838a524d 100644 --- a/crates/engine/tests/it/atn_v12.rs +++ b/crates/engine/tests/it/atn_v12.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn; use photocraft_engine::{Session, actions_cmds::ActionStep, paint::tile::b64_encode}; use serde_json::json; @@ -17,6 +18,6 @@ fn legacy_v12_commands_import_like_v16() { let mut s = Session::new(); let result = s.execute("actions.load", json!({"data": b64_encode(input)})).unwrap(); assert_eq!(result["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, expected); + assert_eq!(s.actions().list.actions()[0].steps, expected); } } diff --git a/crates/engine/tests/it/content_aware_fill_atn.rs b/crates/engine/tests/it/content_aware_fill_atn.rs index 71c3d1193a..3135ca9c0d 100644 --- a/crates/engine/tests/it/content_aware_fill_atn.rs +++ b/crates/engine/tests/it/content_aware_fill_atn.rs @@ -1,5 +1,6 @@ //! #10694: Content-Aware Fill options survive ATN load, save and playback. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, @@ -107,7 +108,7 @@ fn typed_flags_survive_saved_descriptors_and_public_playback() { } let (mut replay, replay_id) = fixture(); assert_eq!(load(&mut replay, &recorded(event.clone(), d))["unsupported"], json!([])); - assert_eq!(replay.actions.list.actions()[0].steps, vec![ActionStep::new("edit.fill", params)], "CAF flags must import without loss"); + assert_eq!(replay.actions().list.actions()[0].steps, vec![ActionStep::new("edit.fill", params)], "CAF flags must import without loss"); let saved = save(&mut replay); let parsed = atn::parse(&saved).unwrap(); let saved_d = parsed.actions[0].items[0].descriptor.as_ref().unwrap(); @@ -117,8 +118,8 @@ fn typed_flags_survive_saved_descriptors_and_public_playback() { assert_eq!(saved_d.get(ROTATION), Some(&D::Boolean(values[3]))); let imported = atn_cmds::import(&saved).unwrap(); assert!(imported.unsupported.is_empty()); - assert_eq!(imported.actions[0].steps, replay.actions.list.actions()[0].steps); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + assert_eq!(imported.actions[0].steps, replay.actions().list.actions()[0].steps); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let played = replay.execute("actions.play", json!({"action": "Fill"})).unwrap(); assert_eq!(played["ran"], 1); assert!(played.get("failed").is_none(), "{played}"); @@ -134,10 +135,10 @@ fn typed_flags_survive_saved_descriptors_and_public_playback() { fn absent_and_null_native_flags_keep_defaults_and_export_no_rotation() { let mut s = Session::new(); assert_eq!(load(&mut s, &recorded(AtnEvent::Code(*b"Fl "), descriptor()))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].params, json!({"contents": "contentAware", "rotationAdaptation": false})); + assert_eq!(s.actions().list.actions()[0].steps[0].params, json!({"contents": "contentAware", "rotationAdaptation": false})); let saved = save(&mut s); let imported = atn_cmds::import(&saved).unwrap(); - assert_eq!(imported.actions[0].steps, s.actions.list.actions()[0].steps); + assert_eq!(imported.actions[0].steps, s.actions().list.actions()[0].steps); for null in [false, true] { let mut params = json!({"contents": "contentAware"}); if null { @@ -184,7 +185,7 @@ fn malformed_flags_remain_kept_steps() { let mut s = Session::new(); let loaded = load(&mut s, &source); assert_eq!(loaded["unsupported"].as_array().unwrap().len(), 1); - assert_eq!(s.actions.list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); let saved = atn::parse(&save(&mut s)).unwrap(); assert_eq!(saved.actions[0].items[0].descriptor, original.actions[0].items[0].descriptor); assert_eq!(saved.actions[0].items[0].event, original.actions[0].items[0].event); diff --git a/crates/engine/tests/it/convert_profile_atn.rs b/crates/engine/tests/it/convert_profile_atn.rs index 10a3f3407d..5ca4794070 100644 --- a/crates/engine/tests/it/convert_profile_atn.rs +++ b/crates/engine/tests/it/convert_profile_atn.rs @@ -1,5 +1,6 @@ //! Recorded-shaped Convert to Profile flags survive ATN load, save and native playback. +use photocraft_engine::actions_cmds::ActionsExt; use std::sync::Arc; use craft_cms::Builtin; @@ -73,7 +74,7 @@ fn absolute_and_unknown_intents_remain_distinct_with_conversion_flags() { assert_eq!(saved, &d); } else { assert_eq!(result["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps[0].params["intent"], json!("absolute")); + assert_eq!(s.actions().list.actions()[0].steps[0].params["intent"], json!("absolute")); assert_eq!(saved.get("Inte"), Some(&D::Enumerated { type_id: Id::new("Inte"), value: Id::new("AClr") })); let mut absolute = intent_fixture(); absolute.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "absolute", "bpc": false})).unwrap(); @@ -150,7 +151,7 @@ fn recorded_rgb_flags_survive_save_reimport_and_public_playback() { } let mut replay = fixture(); assert_eq!(load(&mut replay, &recorded(d))["unsupported"], json!([])); - assert_eq!(replay.actions.list.actions()[0].steps, vec![ActionStep::new("edit.convertToProfile", params)]); + assert_eq!(replay.actions().list.actions()[0].steps, vec![ActionStep::new("edit.convertToProfile", params)]); let saved = save(&mut replay); let parsed = atn::parse(&saved).unwrap(); let saved_d = parsed.actions[0].items[0].descriptor.as_ref().unwrap(); @@ -160,8 +161,8 @@ fn recorded_rgb_flags_survive_save_reimport_and_public_playback() { } let imported = atn_cmds::import(&saved).unwrap(); assert!(imported.unsupported.is_empty()); - assert_eq!(imported.actions[0].steps, replay.actions.list.actions()[0].steps); - replay.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + assert_eq!(imported.actions[0].steps, replay.actions().list.actions()[0].steps); + replay.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let played = replay.execute("actions.play", json!({"action": "Convert"})).unwrap(); assert_eq!(played["ran"], 1); assert!(played.get("failed").is_none(), "{played}"); @@ -182,12 +183,12 @@ fn recorded_rgb_flags_survive_save_reimport_and_public_playback() { fn defaults_are_explicit_false_and_assign_profile_is_unchanged() { let mut s = fixture(); assert_eq!(load(&mut s, &recorded(descriptor()))["unsupported"], json!([])); - let params = &s.actions.list.actions()[0].steps[0].params; + let params = &s.actions().list.actions()[0].steps[0].params; for (_, param) in FLAGS { assert_eq!(params[param], false); } let saved = save(&mut s); - s.actions.list = ActionList::from_file(ActionsFile::new(atn_cmds::import(&saved).unwrap().actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(atn_cmds::import(&saved).unwrap().actions, Vec::new())); let mut control = fixture(); control.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "relative", "bpc": false})).unwrap(); let played = s.execute("actions.play", json!({"action": "Convert"})).unwrap(); @@ -240,7 +241,7 @@ fn unsupported_values_are_preserved_and_invalid_native_values_refuse_export() { let original = atn::parse(&bytes).unwrap(); let mut s = Session::new(); assert_eq!(load(&mut s, &bytes)["unsupported"].as_array().unwrap().len(), 1); - assert_eq!(s.actions.list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); let saved = atn::parse(&save(&mut s)).unwrap(); assert_eq!(saved.actions[0].items[0].descriptor, original.actions[0].items[0].descriptor); assert_eq!(saved.actions[0].items[0].event, original.actions[0].items[0].event); @@ -278,7 +279,7 @@ fn reference_recorded_convert_to_profile_maps() { let mut s = fixture(); assert_eq!(load(&mut s, &recorded(d))["unsupported"], json!([])); assert_eq!( - s.actions.list.actions()[0].steps, + s.actions().list.actions()[0].steps, vec![ActionStep::new( "edit.convertToProfile", json!({"profile": "prophoto-compat", "intent": "absolute", "dither": true, "flatten": false, "rasterizePlaced": false}) diff --git a/crates/engine/tests/it/corpus_atn.rs b/crates/engine/tests/it/corpus_atn.rs index 0c3b297aab..ea53a70618 100644 --- a/crates/engine/tests/it/corpus_atn.rs +++ b/crates/engine/tests/it/corpus_atn.rs @@ -4,6 +4,7 @@ //! ceiling, so a mapping regression (or a new unmapped event in the corpus) shows up here. #![cfg(feature = "corpus")] +use photocraft_engine::actions_cmds::ActionsExt; use std::path::{Path, PathBuf}; use photocraft_engine::Session; @@ -133,7 +134,7 @@ fn atn_corpus_loads_saves_and_reloads() { steps += n_steps; unsupported += n_unsupported; println!("{name}: {} actions, {n_steps} steps, {n_unsupported} kept Photoshop steps {events:?}", loaded["actions"].as_array().map_or(0, Vec::len)); - let first: Vec<_> = s.actions.list.actions().iter().map(exported_action).collect(); + let first: Vec<_> = s.actions().list.actions().iter().map(exported_action).collect(); let saved = match s.execute("actions.save", json!({"set": loaded["set"]})) { Ok(v) => v, Err(e) => { @@ -144,12 +145,12 @@ fn atn_corpus_loads_saves_and_reloads() { let bytes = photocraft_engine::paint::tile::b64_decode(saved["data"].as_str().unwrap_or("")).unwrap_or_default(); let mut t = Session::new(); match t.execute("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&bytes)})) { - Ok(_) if t.actions.list.actions() == first.as_slice() => {} + Ok(_) if t.actions().list.actions() == first.as_slice() => {} Ok(_) => { // Name the first step that differs, so a mapping asymmetry is quick to find. let detail = first .iter() - .zip(t.actions.list.actions()) + .zip(t.actions().list.actions()) .flat_map(|(a, b)| a.steps.iter().zip(&b.steps).enumerate().map(move |(i, (x, y))| (a.name.as_str(), i, x, y))) .find(|(_, _, x, y)| x != y) .map(|(action, i, x, y)| format!("`{action}` step {}: {} {} → {} {}", i + 1, x.command, x.params, y.command, y.params)) diff --git a/crates/engine/tests/it/crop_delete_off_background.rs b/crates/engine/tests/it/crop_delete_off_background.rs index 323c3f2f20..20506f21e4 100644 --- a/crates/engine/tests/it/crop_delete_off_background.rs +++ b/crates/engine/tests/it/crop_delete_off_background.rs @@ -2,6 +2,7 @@ //! Photoshop does: it keeps the pixels past the canvas, and an extension is transparent on every //! layer. Delete on keeps the Background, and Image › Reveal All is unchanged (#10867). +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::{Action, ActionList, ActionStep, ActionsFile}; use photocraft_engine::{EngineError, Session, atn_cmds}; @@ -124,7 +125,7 @@ fn the_action_steps_turned_crop_unlocks_the_background() { assert_eq!((step.command.as_str(), &step.params["deleteCroppedPixels"]), ("image.crop", &json!(false))); let mut s = doc(); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let before = past(&s); s.execute("actions.play", json!({"action": "Crop"})).unwrap(); assert_eq!(past(&s), before + 1, "one undo step"); diff --git a/crates/engine/tests/it/csh_import.rs b/crates/engine/tests/it/csh_import.rs index 7791a70bae..bac55c51e4 100644 --- a/crates/engine/tests/it/csh_import.rs +++ b/crates/engine/tests/it/csh_import.rs @@ -1,6 +1,7 @@ //! Original geometric CSH fixture, assembled from the public container/path layout. //! No Adobe or third-party shape assets are embedded. +use photocraft_engine::presets::PresetsExt; use photocraft_engine::Session; use serde_json::json; @@ -15,7 +16,7 @@ fn csh_import_stores_the_display_form_of_a_localization_key() { let result = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": "Localized CSH"})).unwrap(); assert_eq!(result["group"], "Localized CSH"); assert_eq!(result["names"], json!(["Tiger"])); - assert_eq!(session.presets.shapes.iter().find(|g| g.name == "Localized CSH").unwrap().items[0].name, "Tiger"); + assert_eq!(session.presets().shapes.iter().find(|g| g.name == "Localized CSH").unwrap().items[0].name, "Tiger"); let again = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": "Localized CSH"})).unwrap(); assert_eq!(again["names"], json!(["Tiger 2"])); let blanked = session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&blank)})).unwrap(); @@ -47,16 +48,16 @@ fn csh_import_makes_an_original_shape_available_without_a_document() { #[test] fn csh_failed_import_preserves_existing_presets_and_revision() { let mut session = Session::new(); - let before = session.presets.to_json(&session); - let revision = session.presets.revision(); + let before = session.presets().to_json(&session); + let revision = session.presets().revision(); let bytes = triangle_csh(); for end in [0, 11, bytes.len() - 1] { assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes[..end])})).is_err()); - assert_eq!(session.presets.to_json(&session), before); - assert_eq!(session.presets.revision(), revision); + assert_eq!(session.presets().to_json(&session), before); + assert_eq!(session.presets().revision(), revision); } assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": 12})).is_err()); - assert_eq!(session.presets.to_json(&session), before); + assert_eq!(session.presets().to_json(&session), before); } #[test] @@ -69,11 +70,11 @@ fn csh_invalid_second_shape_does_not_partially_import_a_set() { set.pop(); let mut session = Session::new(); session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&triangle)})).unwrap(); - let before = session.presets.to_json(&session); - let revision = session.presets.revision(); + let before = session.presets().to_json(&session); + let revision = session.presets().revision(); assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&set)})).is_err()); - assert_eq!(session.presets.to_json(&session), before); - assert_eq!(session.presets.revision(), revision); + assert_eq!(session.presets().to_json(&session), before); + assert_eq!(session.presets().revision(), revision); } #[test] @@ -86,7 +87,7 @@ fn csh_multiple_shapes_with_matching_names_remain_individually_available() { let result = s.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&set), "group": "Pair"})).unwrap(); assert_eq!(result["count"], 2); assert_eq!(result["names"], json!(["Triangle", "Triangle 2"])); - let group = s.presets.shapes.iter().find(|g| g.name == "Pair").unwrap(); + let group = s.presets().shapes.iter().find(|g| g.name == "Pair").unwrap(); assert_eq!(group.items.len(), 2); assert_eq!(group.items[0].path, group.items[1].path); s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); @@ -105,10 +106,10 @@ fn csh_repeat_import_names_are_unique_and_survive_preferences_reload() { assert_eq!(second["count"], 1); assert_ne!(first["group"], second["group"]); assert_ne!(first["names"], second["names"]); - let persisted = session.presets.to_json(&session); + let persisted = session.presets().to_json(&session); let mut restored = Session::new(); restored.load_presets_json(persisted); - assert_eq!(restored.presets.shapes, session.presets.shapes); + assert_eq!(restored.presets().shapes, session.presets().shapes); } #[test] @@ -119,7 +120,7 @@ fn csh_same_winding_inner_subpath_stays_a_hole_after_place_and_reload() { let mut imported = Session::new(); let result = imported.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes)})).unwrap(); let mut s = Session::new(); - s.load_presets_json(imported.presets.to_json(&imported)); + s.load_presets_json(imported.presets().to_json(&imported)); s.execute("file.new", json!({"width": 96, "height": 96, "background": "transparent"})).unwrap(); s.execute("shape.presets.place", json!({"preset": result["names"][0], "rect": [8, 8, 80, 80], "keepAspect": false, "fill": "#ff0000"})).unwrap(); let image = photocraft_compose::flatten(&s.active().unwrap().doc); diff --git a/crates/engine/tests/it/gaussian_edge_profile.rs b/crates/engine/tests/it/gaussian_edge_profile.rs index aba5276e87..7beaaad874 100644 --- a/crates/engine/tests/it/gaussian_edge_profile.rs +++ b/crates/engine/tests/it/gaussian_edge_profile.rs @@ -19,6 +19,7 @@ //! depths and on both routes, and ratchet the distance to Photoshop's measured row so a future //! kernel change is a decision with a number attached to it instead of a silent drift. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use craft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; use photocraft_engine::actions_cmds::{ActionList, ActionsFile}; @@ -120,7 +121,7 @@ fn gaussian_recording_replays_the_direct_blur_pixels_and_radius() { let mut direct = edge_doc(depth); direct.execute("filter.blur.gaussianBlur", json!({"radius": 2.3})).unwrap(); let mut s = edge_doc(depth); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions.clone(), Vec::new())); assert_eq!(s.execute("actions.play", json!({"action": "Blur2_3"})).unwrap()["ran"], 1); assert_eq!( photocraft_compose::flatten(&s.active().unwrap().doc).px, diff --git a/crates/engine/tests/it/image_size_scale_styles_atn.rs b/crates/engine/tests/it/image_size_scale_styles_atn.rs index d84d52716c..3517f7fd97 100644 --- a/crates/engine/tests/it/image_size_scale_styles_atn.rs +++ b/crates/engine/tests/it/image_size_scale_styles_atn.rs @@ -1,5 +1,6 @@ //! #10694: Image Size style scaling survives ATN import, playback and saving. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, @@ -85,15 +86,15 @@ fn imported_style_scaling_survives_saved_bytes_and_playback() { let loaded = load(&mut s, &recorded(event, Some(descriptor))); assert_eq!(loaded["unsupported"], json!([])); let scale = option.unwrap_or(false); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("image.imageSize", json!({"percent": 50, "scaleStyles": scale}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("image.imageSize", json!({"percent": 50, "scaleStyles": scale}))]); let saved = save(&mut s); let parsed = atn::parse(&saved).unwrap(); // Only scaling needs the key: without it the step keeps style sizes. assert_eq!(parsed.actions[0].items[0].descriptor.as_ref().unwrap().get("scaleStyles"), scale.then_some(&D::Boolean(true))); let imported = atn_cmds::import(&saved).unwrap(); assert!(imported.unsupported.is_empty()); - assert_eq!(imported.actions[0].steps, s.actions.list.actions()[0].steps); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + assert_eq!(imported.actions[0].steps, s.actions().list.actions()[0].steps); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = s.execute("actions.play", json!({"action": "Half"})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{result}"); @@ -121,7 +122,7 @@ fn native_default_is_written_explicitly_and_keeps_its_behavior() { assert_size_and_style(&direct, direct_id, scale); let (mut replay, replay_id) = fixture(); assert_eq!(load(&mut replay, &bytes)["unsupported"], json!([])); - assert_eq!(replay.actions.list.actions()[0].steps[0].params["scaleStyles"], json!(scale)); + assert_eq!(replay.actions().list.actions()[0].steps[0].params["scaleStyles"], json!(scale)); let result = replay.execute("actions.play", json!({"action": "Half"})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{result}"); @@ -147,7 +148,7 @@ fn malformed_or_empty_steps_are_kept_without_becoming_resizes() { let original = atn::parse(&source).unwrap(); let mut s = Session::new(); let loaded = load(&mut s, &source); - let ActionStep { command: step, params } = &s.actions.list.actions()[0].steps[0]; + let ActionStep { command: step, params } = &s.actions().list.actions()[0].steps[0]; if original.actions[0].items[0].descriptor.is_none() { assert_eq!(loaded["unsupported"], json!([])); assert_eq!(step, atn_cmds::MENU_ITEM); diff --git a/crates/engine/tests/it/paste_style_options.rs b/crates/engine/tests/it/paste_style_options.rs index 1527db4f7a..c221bc920d 100644 --- a/crates/engine/tests/it/paste_style_options.rs +++ b/crates/engine/tests/it/paste_style_options.rs @@ -1,5 +1,6 @@ //! Paste Layer Style applies group eligibility consistently and preserves the ATN flag. +use photocraft_engine::actions_cmds::ActionsExt; use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, @@ -203,13 +204,13 @@ fn atn_group_flag_survives_saved_descriptor_and_public_playback() { let child_before = layer(&scene.s, scene.child).clone(); let bytes = recorded(Descriptor::new("null").with(KEY, D::Boolean(allow))); assert_eq!(load(&mut scene.s, &bytes)["unsupported"], json!([])); - assert_eq!(scene.s.actions.list.actions()[0].steps, vec![ActionStep::new(CMD, json!({"allowGroups": allow}))]); + assert_eq!(scene.s.actions().list.actions()[0].steps, vec![ActionStep::new(CMD, json!({"allowGroups": allow}))]); let saved = save(&mut scene.s); let parsed = atn::parse(&saved).unwrap(); assert_eq!(parsed.actions[0].items[0].descriptor.as_ref().unwrap().get(KEY), Some(&D::Boolean(allow))); let imported = atn_cmds::import(&saved).unwrap(); - assert_eq!(imported.actions[0].steps, scene.s.actions.list.actions()[0].steps); - scene.s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + assert_eq!(imported.actions[0].steps, scene.s.actions().list.actions()[0].steps); + scene.s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = scene.s.execute("actions.play", json!({"action": "Paste"})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{result}"); @@ -228,7 +229,7 @@ fn atn_group_flag_survives_saved_descriptor_and_public_playback() { fn atn_defaults_are_explicit_and_unsupported_fields_remain_whole_steps() { let mut scene = fixture(); assert_eq!(load(&mut scene.s, &recorded(Descriptor::new("null")))["unsupported"], json!([])); - assert_eq!(scene.s.actions.list.actions()[0].steps[0].params, json!({"allowGroups": true})); + assert_eq!(scene.s.actions().list.actions()[0].steps[0].params, json!({"allowGroups": true})); for value in [None, Some(Value::Null)] { let mut params = json!({}); if let Some(value) = value { @@ -249,7 +250,7 @@ fn atn_defaults_are_explicit_and_unsupported_fields_remain_whole_steps() { let original = atn::parse(&bytes).unwrap(); let mut s = Session::new(); assert_eq!(load(&mut s, &bytes)["unsupported"].as_array().unwrap().len(), 1); - assert_eq!(s.actions.list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); let saved = atn::parse(&save(&mut s)).unwrap(); assert_eq!(saved.actions[0].items[0].descriptor, original.actions[0].items[0].descriptor); } diff --git a/crates/engine/tests/it/vector_paste_options.rs b/crates/engine/tests/it/vector_paste_options.rs index e98d8116e9..6a6ab05add 100644 --- a/crates/engine/tests/it/vector_paste_options.rs +++ b/crates/engine/tests/it/vector_paste_options.rs @@ -1,5 +1,6 @@ //! Explicit Paste modes preserve source kind instead of silently using the ordinary raster route. +use photocraft_engine::actions_cmds::ActionsExt; use photocraft_engine::Session; use serde_json::json; @@ -286,15 +287,15 @@ fn atn_classes_roundtrip_and_play_real_modes() { assert_eq!(load(&mut s, &recorded(descriptor(class_id)))["unsupported"], json!([])); // `As Pxel` is what an ordinary Paste records: it keeps the ordinary route. let params = if mode == "pixels" { json!({}) } else { json!({"as":mode}) }; - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("edit.paste", params)]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("edit.paste", params)]); let saved = save(&mut s); let file = atn::parse(&saved).unwrap(); if mode != "pixels" { assert_eq!(file.actions[0].items[0].descriptor.as_ref().unwrap().get("As "), descriptor(class_id).get("As ")); } let imported = atn_cmds::import(&saved).unwrap(); - assert_eq!(imported.actions[0].steps, s.actions.list.actions()[0].steps); - s.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + assert_eq!(imported.actions[0].steps, s.actions().list.actions()[0].steps); + s.actions_mut().list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); let result = s.execute("actions.play", json!({"action":"Paste"})).unwrap(); assert_eq!(result["ran"], 1); assert!(result.get("failed").is_none(), "{result}"); @@ -316,7 +317,7 @@ fn atn_classes_roundtrip_and_play_real_modes() { fn atn_unknown_forms_are_kept_and_legacy_omission_stays_legacy() { let mut s = scene(8); assert_eq!(load(&mut s, &recorded(Descriptor::new("null")))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("edit.paste", json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("edit.paste", json!({}))]); for d in [ descriptor("unknownClass"), Descriptor::new("null").with("As ", D::Text(UnicodeString::new_nul("Path"))), @@ -328,7 +329,7 @@ fn atn_unknown_forms_are_kept_and_legacy_omission_stays_legacy() { let file = atn::parse(&original).unwrap(); let mut s = Session::new(); assert_eq!(load(&mut s, &original)["unsupported"].as_array().unwrap().len(), 1); - assert_eq!(s.actions.list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); + assert_eq!(s.actions().list.actions()[0].steps[0].command, atn_cmds::PHOTOSHOP_STEP); assert_eq!(atn::parse(&save(&mut s)).unwrap().actions[0].items[0].descriptor, file.actions[0].items[0].descriptor); } for p in [ @@ -358,7 +359,7 @@ fn recorded_pixels_paste_keeps_the_ordinary_route() { s.execute("edit.paste", json!({"as":"shape"})).unwrap(); s.execute("edit.copy", json!({})).unwrap(); assert_eq!(load(&mut s, &recorded(recorded_pixels_paste(false)))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("edit.paste", json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("edit.paste", json!({}))]); let layers = s.active().unwrap().doc.layers.len(); let result = s.execute("actions.play", json!({"action":"Paste"})).unwrap(); assert_eq!(result["ran"], 1); @@ -372,5 +373,5 @@ fn recorded_pixels_paste_keeps_the_ordinary_route() { fn recorded_pixels_paste_in_place_maps() { let mut s = Session::new(); assert_eq!(load(&mut s, &recorded(recorded_pixels_paste(true)))["unsupported"], json!([])); - assert_eq!(s.actions.list.actions()[0].steps, vec![ActionStep::new("edit.pasteSpecial.pasteInPlace", json!({}))]); + assert_eq!(s.actions().list.actions()[0].steps, vec![ActionStep::new("edit.pasteSpecial.pasteInPlace", json!({}))]); } diff --git a/crates/engine/tests/it/working_rgb_profile.rs b/crates/engine/tests/it/working_rgb_profile.rs index ea30b78ea9..ec3cee0df8 100644 --- a/crates/engine/tests/it/working_rgb_profile.rs +++ b/crates/engine/tests/it/working_rgb_profile.rs @@ -1,5 +1,7 @@ //! Working RGB must support reading and editing for the configured intent. +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::color_cmds::ColorExt; use craft_cms::{ Builtin, Curve, Intent, Profile, ProfileClass, pipeline::Stage, @@ -59,12 +61,12 @@ fn reject_one_way_setting(source: bool, destination: bool, missing_direction: &s assert_eq!(file.profile.device_to_pcs(intent).is_ok(), source); assert_eq!(file.profile.pcs_to_device(intent).is_ok(), destination); let mut s = Session::new(); - let before = s.color.settings.clone(); + let before = s.color().settings.clone(); let error = s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": intent.id(), "bpc": false})).unwrap_err(); assert!(error.to_string().contains(missing_direction), "{error}"); - assert_eq!(s.color.settings, before, "reject the full settings update before any mutation"); + assert_eq!(s.color().settings, before, "reject the full settings update before any mutation"); assert!(s.execute("prefs.set", json!({"path": "colorSettings.workingRgb", "value": file.spec()})).is_err()); - assert_eq!(s.color.settings, before, "individual preference setter also rejects atomically"); + assert_eq!(s.color().settings, before, "individual preference setter also rejects atomically"); } } @@ -81,13 +83,13 @@ fn a_destination_only_rgb_working_space_is_rejected_atomically() { fn legacy_session(file: &ProfileFile, intent: Intent) -> Session { let mut s = Session::new(); s.load_prefs_json(&json!({"colorSettings": {"workingRgb": file.spec(), "intent": intent.id()}}).to_string()).unwrap(); - assert_eq!(s.color.settings.working_rgb, file.spec(), "legacy preferences still load"); + assert_eq!(s.color().settings.working_rgb, file.spec(), "legacy preferences still load"); s } fn display_and_copy(s: &mut Session, depth: SampleType) { let target = s.active().unwrap().doc.clone(); - let display = s.color.display_transform(&target).expect("the destination document must also be a readable display source"); + let display = s.color().display_transform(&target).expect("the destination document must also be a readable display source"); let mut displayed = [0.0; 3]; display.eval(&[0.35, 0.65, 0.45], &mut displayed).unwrap(); assert!(displayed.iter().all(|v| v.is_finite())); @@ -115,7 +117,7 @@ fn legacy_untagged_workflow(source: bool, destination: bool) { assert!(doc.icc_profile.is_none()); s.open_document(doc, None); display_and_copy(&mut s, depth); - assert_eq!(s.color.working(ColorMode::Rgb).content_hash(), Builtin::Srgb.profile().content_hash()); + assert_eq!(s.color().working(ColorMode::Rgb).content_hash(), Builtin::Srgb.profile().content_hash()); assert!(s.documents()[0].doc.icc_profile.is_none(), "the default working fallback keeps untagged documents untagged"); } } @@ -162,15 +164,15 @@ fn valid_input_matrix_and_lut_working_profiles_use_the_configured_intent() { for intent in Intent::ALL { let supported = !colorimetric_only || matches!(intent, Intent::RelativeColorimetric | Intent::AbsoluteColorimetric); let mut s = Session::new(); - let before = s.color.settings.clone(); + let before = s.color().settings.clone(); let result = s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": intent.id()})); assert_eq!(result.is_ok(), supported, "{intent:?}/colorimetric_only={colorimetric_only}"); if !supported { - assert_eq!(s.color.settings, before); + assert_eq!(s.color().settings, before); } let s = legacy_session(&file, intent); let expected = if supported { &file.profile } else { Builtin::Srgb.profile() }; - assert_eq!(s.color.working(ColorMode::Rgb).content_hash(), expected.content_hash()); + assert_eq!(s.color().working(ColorMode::Rgb).content_hash(), expected.content_hash()); } } } @@ -214,8 +216,8 @@ fn valid_cross_field_profile_and_intent_changes_validate_the_final_batch() { for (command, params) in cases { let mut s = colorimetric_session(&file); s.execute(command, params.clone()).unwrap_or_else(|e| panic!("final valid batch must succeed: {command}/{params}: {e}")); - assert_eq!(s.color.settings.working_rgb, "display-p3"); - assert_eq!(s.color.settings.intent, "perceptual"); + assert_eq!(s.color().settings.working_rgb, "display-p3"); + assert_eq!(s.color().settings.intent, "perceptual"); } } @@ -256,8 +258,8 @@ fn incompatible_single_intent_reset_preserves_the_original_colour_settings() { fn unrelated_preference_batches_still_work_with_legacy_invalid_colour_settings() { let invalid = ProfileFile::new(directional_profile(true, false)); let mut s = legacy_session(&invalid, Intent::RelativeColorimetric); - let before = s.color.settings.clone(); + let before = s.color().settings.clone(); s.execute("prefs.set", json!({"values": {"cursors.painting": "precise", "performance.historyStates": 17}})).unwrap(); - assert_eq!(s.color.settings, before); + assert_eq!(s.color().settings, before); assert_eq!(s.execute("prefs.get", json!({"path": "performance.historyStates"})).unwrap(), json!(17)); } diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 6dbfc750e4..91435bea1a 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -2,6 +2,7 @@ //! (Rule 9 in AGENTS.md.) Panics are counted by a hook and reported with the command; a hang is //! ended by nextest's slow-timeout and the last `panic_hunt:` line on stderr names it. Opt-in (slow): //! `cargo test -p photocraft-engine --test panic_hunt -- --ignored`. +use photocraft_engine::print_cmds::PrintExt; use photocraft_engine::{Session, command_specs}; use serde_json::{Value, json}; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -14,7 +15,7 @@ fn fresh() -> Session { photocraft_engine::print_cmds::disable_printing(); let mut s = Session::new(); // `file.printers` and `file.print.printers` list no printers and do not ask the spooler. - s.printer_source = Some(std::sync::Arc::new(Vec::new)); + *s.printer_source_mut() = Some(std::sync::Arc::new(Vec::new)); s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); s.execute("select.rect", json!({"x": 1, "y": 1, "width": 6, "height": 5})).unwrap(); diff --git a/crates/ui-egui/examples/camera_raw_bench.rs b/crates/ui-egui/examples/camera_raw_bench.rs index 743610d734..3b5ad38d7b 100644 --- a/crates/ui-egui/examples/camera_raw_bench.rs +++ b/crates/ui-egui/examples/camera_raw_bench.rs @@ -1,4 +1,5 @@ //! Real Camera Raw proxy-update timing on a 36 MP document (CPU preparation, not GPU presentation). +use photocraft_engine::color_cmds::ColorExt; use photocraft_ui_egui::{PhotocraftApp, camera_raw_ui}; use serde_json::{Value, json}; diff --git a/crates/ui-egui/examples/flat_open_bench.rs b/crates/ui-egui/examples/flat_open_bench.rs index 9e05fbdfed..3d87eeb304 100644 --- a/crates/ui-egui/examples/flat_open_bench.rs +++ b/crates/ui-egui/examples/flat_open_bench.rs @@ -17,7 +17,7 @@ //! //! Rows per case, in ms over `--reps` repetitions: //! - `import`: `import_for_open_with`, the real File › Open path (decode, orientation, tiles) -//! - `admission`: `Session::open_document` of that document +//! - `admission`: `ColorExt::open_document` of that document //! - `decode`: the codec alone, orientation kept as stored //! - `orient`: `Image::oriented` with the file's EXIF orientation (a no-op for an upright file) //! - `tiles`: `image_to_document` on the decoded image (layout conversion, tile construction, prune) @@ -34,6 +34,7 @@ //! A case run directly with `--case` generates a missing fixture in its own process, which //! raises its peak: run the bench once without `--case` first. +use photocraft_engine::color_cmds::ColorExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::time::Instant; diff --git a/crates/ui-egui/examples/interactive_bench.rs b/crates/ui-egui/examples/interactive_bench.rs index 090aad88b4..110f8496fb 100644 --- a/crates/ui-egui/examples/interactive_bench.rs +++ b/crates/ui-egui/examples/interactive_bench.rs @@ -18,6 +18,7 @@ //! clipped target keeps the CPU proxy (its preview group would rebuild effect shape maps on the //! UI thread), so only its CPU reference rows run and the reason is printed. +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use eframe::wgpu; diff --git a/crates/ui-egui/examples/large_file_bench.rs b/crates/ui-egui/examples/large_file_bench.rs index ce59771cf6..817d973e33 100644 --- a/crates/ui-egui/examples/large_file_bench.rs +++ b/crates/ui-egui/examples/large_file_bench.rs @@ -14,6 +14,7 @@ //! to this binary) and kept for the next run; `--clean` removes them afterwards. Each row also //! records the peak resident memory of its opens. Needs about 30 GB of memory for the PSB. +use photocraft_engine::color_cmds::ColorExt; use std::path::PathBuf; use std::time::{Duration, Instant}; diff --git a/crates/ui-egui/examples/large_image_bench.rs b/crates/ui-egui/examples/large_image_bench.rs index 5f03d81126..83186014a2 100644 --- a/crates/ui-egui/examples/large_image_bench.rs +++ b/crates/ui-egui/examples/large_image_bench.rs @@ -16,6 +16,7 @@ //! `--depth 16` or `--depth 32` converts the document to that bit depth after opening (the //! conversion is part of "open"), e.g. a 36 MP 16-bit refresh: `--size 7360x4912 --depth 16 --op refresh`. +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use eframe::egui_wgpu::RenderState; diff --git a/crates/ui-egui/examples/lasso_bench.rs b/crates/ui-egui/examples/lasso_bench.rs index 875cc4f963..5d7ae5133d 100644 --- a/crates/ui-egui/examples/lasso_bench.rs +++ b/crates/ui-egui/examples/lasso_bench.rs @@ -13,6 +13,7 @@ //! each frame on the GPU (with a readback, about 7 ms here), otherwise only the app's logic runs. //! `PHOTOCRAFT_GPU_SYNC=1` makes a canvas refresh wait for the GPU. +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use egui::{Event, Modifiers, PointerButton, Pos2}; diff --git a/crates/ui-egui/examples/layout_bench.rs b/crates/ui-egui/examples/layout_bench.rs index 24ddc3f27e..a7f9a6f8cb 100644 --- a/crates/ui-egui/examples/layout_bench.rs +++ b/crates/ui-egui/examples/layout_bench.rs @@ -22,6 +22,7 @@ #[path = "../tests/support/layout_doc.rs"] mod layout_doc; +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use egui::{Event, Key, Modifiers, PointerButton, Pos2}; diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 85e0f1b34f..fb5a9fded3 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -18,6 +18,7 @@ //! what the refreshes did (`refresh_kinds`: `Refresh::kind` counts, also "rect" / "full" without //! an adapter; `fallbacks`: `CpuReason::kind` of any refresh the wgpu compositor didn't draw). +use photocraft_engine::color_cmds::ColorExt; use std::time::Instant; use eframe::egui_wgpu::RenderState; diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index 317a590737..d1911f39df 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -1,6 +1,7 @@ //! ⌥-click through the real canvas: the Brush's temporary Eyedropper (#1659) and the Clone //! Stamp's source point and painting (#1658), the Zoom tool's Zoom Out (#3137). +use photocraft_engine::presets::PresetsExt; use egui::{Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; use serde_json::json; @@ -115,7 +116,7 @@ fn alt_click_routes_by_tool_held_or_latched() { h.state_mut().ui.tool = Tool::CloneStamp; latch_alt(&mut h, latched); click(&mut h, 150.0, 50.0, m); - assert!(h.state().session.presets.clone.active().source.is_some(), "Clone Stamp {how}: the source is set"); + assert!(h.state().session.presets().clone.active().source.is_some(), "Clone Stamp {how}: the source is set"); // Zoom: zooms out (scrubby on and off for the latched key), and zooms in again without ⌥. for scrubby in [true, false] { diff --git a/crates/ui-egui/src/app/clipboard_tests.rs b/crates/ui-egui/src/app/clipboard_tests.rs index 3c45f62d16..fa0ce3c5b8 100644 --- a/crates/ui-egui/src/app/clipboard_tests.rs +++ b/crates/ui-egui/src/app/clipboard_tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use std::sync::{Arc, Mutex}; @@ -174,7 +175,7 @@ fn action_vector_paste_reads_the_current_svg_source() { let mut app = PhotocraftApp::new(Session::new(), services); app.run("file.new", json!({"width": 24, "height": 20})).unwrap(); app.session - .actions + .actions_mut() .list .push(photocraft_engine::actions_cmds::Action::new("SVG", vec![photocraft_engine::actions_cmds::ActionStep::new("edit.paste", json!({"as": "shape"}))])) .unwrap(); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4716314e04..add39c2a0e 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use craft::behavior::PixelSize; use craft::ui::patterns::form_dialogs::DocumentOptions; @@ -129,7 +130,7 @@ impl PhotocraftApp { let warnings = file_open::with_missing_fonts_of(&doc, warnings); // A developed raw has no embedded profile to ask about. let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let question = self.session.color.open_question(&doc).filter(|_| !developed); + let question = self.session.color().open_question(&doc).filter(|_| !developed); let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings); open_prompt::arrive( self, diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 7ba7ed0242..1adbb3c532 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -9,6 +9,7 @@ //! The `craft` facade features PhotoCraft enables for this: `text`, `text-font-picker`, //! `font-manager`, `menu`, `timeline` and `print`, plus `dialogs` on native targets. +use photocraft_engine::actions_cmds::ActionsExt; use std::collections::{BTreeMap, BTreeSet}; use std::sync::{Arc, Mutex, PoisonError}; @@ -676,7 +677,7 @@ impl PhotocraftApp { pub(crate) fn framework_before_input(&mut self, ctx: &egui::Context) { // The catalog's rows change only with the action names; the bindings with the rows and the // shortcut preferences. - let list = &self.session.actions.list; + let list = &self.session.actions().list; let actions_rev = list.revision(); if self.framework.catalog_rows_rev != Some(actions_rev) { let same = self.framework.catalog_rows_rev.is_some() diff --git a/crates/ui-egui/src/app/framework/catalog_tests.rs b/crates/ui-egui/src/app/framework/catalog_tests.rs index 7599ab9c1d..e1ead1868f 100644 --- a/crates/ui-egui/src/app/framework/catalog_tests.rs +++ b/crates/ui-egui/src/app/framework/catalog_tests.rs @@ -1,5 +1,6 @@ //! Count trials: the command catalog and the keymap overrides are built only when what they read changes. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::actions::ActionStep; use serde_json::json; @@ -54,14 +55,14 @@ fn the_catalog_is_built_only_when_its_inputs_change() { assert!(app.framework.overrides.get("filter.blur.gaussian").is_some_and(|keys| !keys.is_empty()), "the overrides carry the new key"); assert_eq!(app.framework.keymap_inputs().1, generation, "the catalog keeps its generation"); - app.session.actions.list.new_action("Trial", None).unwrap(); + app.session.actions_mut().list.new_action("Trial", None).unwrap(); frames(&mut app, 2); assert_eq!(builds(&app), (2, 3), "a new action builds the rows and the overrides once"); assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog takes a new generation"); assert!(app.framework.catalog_rows.iter().any(|row| row.label == "Trial"), "the action has its row"); // Edits that keep every action's name leave the rows. - let list = &mut app.session.actions.list; + let list = &mut app.session.actions_mut().list; let at = list.actions().iter().position(|action| action.name == "Trial").unwrap(); list.insert_step(at, 0, ActionStep::new("layer.new", json!({}))).unwrap(); list.toggle_step(at, 0).unwrap(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ad09929d65..f7c9cb0ee5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -260,6 +260,7 @@ mod art_history_shift_click_tests; #[cfg(test)] mod rotation_preview_isolation_tests { + use photocraft_engine::color_cmds::ColorExt; use craft::ui::dialog::DialogId; use photocraft_engine::channel_cmds::ChannelTarget; @@ -484,8 +485,8 @@ mod rotation_preview_isolation_tests { #[test] fn profile_dialogs_preview_through_the_profile_they_choose() { let mut session = photocraft_engine::Session::new(); - session.color.settings.monitor_profile = "srgb".into(); - session.color.settings.working_rgb = "display-p3".into(); + session.color_mut().settings.monitor_profile = "srgb".into(); + session.color_mut().settings.working_rgb = "display-p3".into(); session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); session.execute("edit.assignProfile", json!({"profile": "srgb"})).unwrap(); session diff --git a/crates/ui-egui/src/canvas/background_redraw.rs b/crates/ui-egui/src/canvas/background_redraw.rs index 45a2d5a70c..44b59ccb35 100644 --- a/crates/ui-egui/src/canvas/background_redraw.rs +++ b/crates/ui-egui/src/canvas/background_redraw.rs @@ -15,6 +15,7 @@ //! going back to a state drawn a moment ago (⌥-click on an eye and again, an undo and its redo) //! uploads those blocks instead of compositing every layer again. +use photocraft_engine::color_cmds::ColorExt; use std::collections::VecDeque; #[cfg(test)] use std::sync::atomic::AtomicU64; @@ -232,7 +233,7 @@ impl KeptComposites { /// application setting, not part of the document. Read from the session's settings, which the /// engine keeps in step with the process-wide value compose reads (`psblend::set_text_gamma`). fn text_gamma(app: &PhotocraftApp) -> u32 { - app.session.color.settings.blend_text_gamma.to_bits() + app.session.color().settings.blend_text_gamma.to_bits() } /// Bytes kept composites of document `doc` may hold: what Memory Usage leaves beside its pixels diff --git a/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs b/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs index 43139138b9..1a06e7fe29 100644 --- a/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs +++ b/crates/ui-egui/src/canvas/background_redraw/gpu_tests.rs @@ -1,5 +1,6 @@ //! Background full CPU redraws (#4024) on a device: the GPU tests skip when there is no adapter. +use photocraft_engine::color_cmds::ColorExt; use super::*; use serde_json::json; @@ -215,7 +216,7 @@ fn a_state_drawn_before_the_text_gamma_changed_is_composited_again() { settle(&mut g); g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide"); settle(&mut g); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = 1.0; g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": true})).expect("show"); g.harness.step(); assert!(g.harness.state().redraws.contains_key(&doc), "served from blocks of the old gamma: {}", g.harness.state().perf.last_refresh); @@ -231,7 +232,7 @@ fn a_redraw_across_a_text_gamma_change_is_not_kept() { let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); let held = start_held_redraw(&mut g, doc); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = 1.0; drop(held); settle(&mut g); assert!(g.harness.state().kept.entries.is_empty(), "a composite of two gammas was kept"); @@ -243,11 +244,11 @@ fn a_redraw_across_a_text_gamma_change_and_back_is_not_kept() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let gamma = g.harness.state().session.color.settings.blend_text_gamma; + let gamma = g.harness.state().session.color().settings.blend_text_gamma; let held = start_held_redraw(&mut g, doc); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = 1.0; g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = gamma; assert!(g.harness.state().redraws.contains_key(&doc), "the redraw finished before the change back"); drop(held); settle(&mut g); @@ -261,13 +262,13 @@ fn a_hidden_documents_redraw_across_a_text_gamma_change_and_back_is_not_kept() { let _gpu = photocraft_testkit::gpu_lock(); let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072); - let gamma = g.harness.state().session.color.settings.blend_text_gamma; + let gamma = g.harness.state().session.color().settings.blend_text_gamma; let held = start_held_redraw(&mut g, doc); g.harness.state_mut().run("file.new", json!({"width": 64, "height": 64})).expect("another document"); g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = 1.0; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = 1.0; g.harness.step(); - g.harness.state_mut().session.color.settings.blend_text_gamma = gamma; + g.harness.state_mut().session.color_mut().settings.blend_text_gamma = gamma; g.harness.step(); assert!(g.harness.state().redraws.contains_key(&doc), "the hidden document's redraw stopped"); let i = g.harness.state().session.documents().iter().position(|st| st.doc.id == doc).expect("document"); diff --git a/crates/ui-egui/src/canvas/channel_view.rs b/crates/ui-egui/src/canvas/channel_view.rs index 6399ece211..83742e332c 100644 --- a/crates/ui-egui/src/canvas/channel_view.rs +++ b/crates/ui-egui/src/canvas/channel_view.rs @@ -12,6 +12,7 @@ //! grayscale values instead. The canvas draws it as a raster source (`raster_source::ChannelOverlay`), //! which redraws only the damage of each change. +use photocraft_engine::color_cmds::ColorExt; use egui::Color32; use photocraft_color::PixelFormat; use photocraft_doc::{AlphaChannel, ColorMode, Document}; @@ -81,7 +82,7 @@ pub struct Screen { impl Screen { /// How the canvas shows `doc` on `display` (`None`: the main window's). pub fn of(app: &PhotocraftApp, doc: &Document, display: Option) -> Screen { - let color = &app.session.color; + let color = app.session.color(); let display = display.or(color.main_display); let Ok(d) = color.canvas_display_for(doc, display) else { return Screen::default() }; let proof = color.proof_ref(doc.id).is_some_and(|p| p.enabled); @@ -91,7 +92,7 @@ impl Screen { /// A key that changes with [`Screen::of`]. pub fn key(app: &PhotocraftApp, doc: &Document, display: Option) -> u64 { - let color = &app.session.color; + let color = app.session.color(); color.display_signature_for(doc, display.or(color.main_display)) } diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs index 3085aefb30..e9ec6cabb4 100644 --- a/crates/ui-egui/src/canvas/display.rs +++ b/crates/ui-egui/src/canvas/display.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use super::strokes::live_stroke; use super::{Document, PhotocraftApp}; use photocraft_doc::LayerContent; @@ -64,7 +65,7 @@ pub(crate) fn canvas_display( doc: &Document, display: Option, ) -> (Option>, u64) { - match app.session.color.canvas_display_for(doc, display.or(app.session.color.main_display)) { + match app.session.color().canvas_display_for(doc, display.or(app.session.color().main_display)) { Ok(d) => { let k = d.key ^ ink_preview_key(doc); (Some(d), k) @@ -254,7 +255,7 @@ pub(super) fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Do let Some(gpu) = app.gpu.clone() else { return 0 }; let output = display.unwrap_or(0); // Rebuild only when anything feeding the LUT changes. - let sig = app.session.color.display_signature_for(doc, display); + let sig = app.session.color().display_signature_for(doc, display); if let Some((s, mode)) = gpu.display_lut_signature(key, output) && s == sig { @@ -262,13 +263,13 @@ pub(super) fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Do } // Keep the curve/matrix/curve stages separate: interpolating a finished display // transform on a 33³ lattice crushes shadows when the monitor curve is steep near zero. - if let Ok(Some(shaper)) = app.session.color.gpu_canvas_matrix_shaper_for(doc, display) { + if let Ok(Some(shaper)) = app.session.color().gpu_canvas_matrix_shaper_for(doc, display) { gpu.set_display_matrix_shaper(key, output, &shaper); gpu.cache_display_lut_signature(key, output, sig, 3); return 3; } - let gamut = app.session.color.proof(doc.id).gamut_warning; - let mode = match app.session.color.gpu_canvas_lut_for(doc, DISPLAY_LUT, display) { + let gamut = app.session.color().proof(doc.id).gamut_warning; + let mode = match app.session.color().gpu_canvas_lut_for(doc, DISPLAY_LUT, display) { Ok(Some(bytes)) => { gpu.set_display_lut(key, output, DISPLAY_LUT as u32, Some(&bytes)); if gamut { 2 } else { 1 } @@ -290,5 +291,5 @@ pub(super) fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Do /// View › 32-bit Preview Options for the GPU canvas shader: (exposure, gamma) when active. pub(super) fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 2]> { - app.session.color.hdr_preview(doc).map(|h| [h.exposure, h.gamma]) + app.session.color().hdr_preview(doc).map(|h| [h.exposure, h.gamma]) } diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 648385077d..09a1112f43 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use craft::imaging::ui::live_preview::{PreviewSession, settings_hash}; use craft::ui::canvas::PixelRect; use craft::ui::dialog::StackDialog as _; @@ -146,7 +147,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e if !fresh && !app.filter_preview_worker.busy() { let doc = app.session.documents().get(idx)?.doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let color = app.session.color.settings.clone(); + let color = app.session.color().settings.clone(); let task = request.clone(); let fade = fade_job(app, &task); if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| { @@ -207,7 +208,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e None, request.target, &documents, - &app.session.color.settings, + &app.session.color().settings, Some(request.tool_colors), ), } diff --git a/crates/ui-egui/src/canvas/filter_preview/tests.rs b/crates/ui-egui/src/canvas/filter_preview/tests.rs index 481fcd8e59..a279aef07f 100644 --- a/crates/ui-egui/src/canvas/filter_preview/tests.rs +++ b/crates/ui-egui/src/canvas/filter_preview/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use super::*; use craft::ui::dialog::DialogId; use serde_json::{Map, Value, json}; @@ -311,7 +312,7 @@ fn indexed_matte_preview_matches_commit_and_refreshes_tool_colors_inline_and_on_ }); let preview = app.filter_preview.as_ref().unwrap().result.as_ref().unwrap(); let mut applied = photocraft_engine::Session::new(); - applied.color.settings = app.session.color.settings.clone(); + applied.color_mut().settings = app.session.color().settings.clone(); applied.tools.foreground = colors.0; applied.tools.background = colors.1; applied.add_document((*source).clone(), None); @@ -391,7 +392,7 @@ fn cross_scale_indexed_matte_preview_rejects_old_tool_colors_from_cached_and_wor let old_worker = old.clone(); let doc = app.session.documents()[0].doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let color = app.session.color.settings.clone(); + let color = app.session.color().settings.clone(); let (release_old, wait_old) = std::sync::mpsc::channel(); app.filter_preview_worker .start(old_worker.clone(), ctx.clone(), move |_| { diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index cd58e26268..2e7252df12 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -8,6 +8,7 @@ //! [`secondary_takes`] says what a secondary press does for the paint tool; [`context_popup`] is the //! one router that says which popup a press the tool refused opens, for every canvas tool. +use photocraft_engine::preset_store::PresetStoreExt; use craft::keymap::Mods; use photocraft_engine::BrushSettings; use photocraft_engine::prefs::RightClickPaint; diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 7c721293ac..eba49821fb 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use std::sync::Arc; use craft::behavior::PixelSize; @@ -140,12 +141,12 @@ fn clone_dab_coverage( /// display's colour management; a second window on another monitor shows it through the main one's. pub(crate) fn clone_source(app: &mut PhotocraftApp, at: [f64; 2]) -> Option { use photocraft_engine::presets::clone_source::overlay_blend; - let overlay = app.session.presets.clone.overlay.clone(); + let overlay = app.session.presets().clone.overlay.clone(); let tool = app.ui.tool; if !matches!(tool, Tool::CloneStamp | Tool::Healing) || !overlay.show || (overlay.auto_hide && super::paint_tool::stroking(app).is_some()) { return None; } - let slot = app.session.presets.clone.active().clone(); + let slot = app.session.presets().clone.active().clone(); let map = crate::preset_panels::clone_mapping_at(app, Some(at))?; let radius = f64::from(app.session.tools.brush.size) / 2.0; if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { diff --git a/crates/ui-egui/src/canvas/tabs_tests.rs b/crates/ui-egui/src/canvas/tabs_tests.rs index a1cf638516..54454eb71e 100644 --- a/crates/ui-egui/src/canvas/tabs_tests.rs +++ b/crates/ui-egui/src/canvas/tabs_tests.rs @@ -1,6 +1,7 @@ //! The document tab strip in the whole app: tabs follow their documents through Save As, Ctrl+Tab cycles them in //! document order, and the tab text names the target (real tree). +use photocraft_engine::actions_cmds::ActionsExt; use egui::accesskit::Role; use egui::vec2; use egui_kittest::Harness; @@ -112,7 +113,7 @@ fn ctrl_tab_records_a_relative_document_switch() { h.key_press_modifiers(ctrl(), egui::Key::Tab); h.run_steps(2); h.state_mut().run("actions.stop", json!({})).unwrap(); - let steps = &h.state().session.actions.list.action(0).expect("the recorded action").steps; + let steps = &h.state().session.actions().list.action(0).expect("the recorded action").steps; assert_eq!(steps, &[ActionStep::new("document.activate", json!({"offset": -1}))]); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9f91d3279a..7ffdb0bcf0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1,3 +1,5 @@ +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; use super::document_display::{CanvasHost, active_view}; use super::*; use craft::behavior::canvas::ZoomLadder; @@ -41,7 +43,7 @@ fn app_on_two_displays() -> Box { app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); app.run("edit.fill", json!({"color": "#cc8040"})).unwrap(); let icc = |id: &str| Some(resolve_profile(id, None, None).unwrap().to_bytes()); - app.session.color.set_displays(Ok(vec![ + app.session.color_mut().set_displays(Ok(vec![ Display { id: 1, name: "A".into(), frame: [0.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("srgb") }, Display { id: 4, name: "B".into(), frame: [100.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("display-p3") }, ])); @@ -175,8 +177,8 @@ fn clone_overlay_is_circular_and_respects_visibility() { assert_eq!(image(32 + 8, 32 + 8).a(), 0, "the brush square's corner, outside the circle, is clipped"); assert_eq!(image(32 + 12, 32).a(), 0, "past the hard tip's rim"); assert_eq!(app.session.active().unwrap().revision, revision); - assert!(app.session.presets.clone.active().anchor.is_none()); - app.session.presets.clone.overlay.show = false; + assert!(app.session.presets().clone.active().anchor.is_none()); + app.session.presets_mut().clone.overlay.show = false; assert!(clone_source_image(&mut app).is_none(), "a hidden Clone Source shows no image"); } @@ -218,7 +220,7 @@ fn clone_overlay_opacity_and_flow_match_a_stamp_on_another_layer() { app.ui.tool = Tool::CloneStamp; app.ui.tool_options.clone_sample = "all".into(); app.session.tools.brush.size = 20.0; - app.session.presets.clone.overlay.clipped = clipped; + app.session.presets_mut().clone.overlay.clipped = clipped; for (opacity, flow) in [(1.0, 1.0), (0.5, 1.0), (1.0, 0.25), (0.5, 0.4)] { // A full-strength overlay is shown first, so the change comes after a shown one. clone_overlay_centre_alpha(&mut app); @@ -244,7 +246,7 @@ fn clone_overlay_opacity_and_flow_match_a_stamp_on_another_layer() { fn clone_overlay_separate_opacity_setting_still_multiplies_the_brush_opacity() { let mut app = clone_overlay_app(20.0); app.session.tools.brush.opacity = 0.5; - app.session.presets.clone.overlay.opacity = 40.0; + app.session.presets_mut().clone.overlay.opacity = 40.0; let alpha = clone_overlay_centre_alpha(&mut app); assert!((alpha - 0.2).abs() < 0.01, "50% brush opacity times 40% overlay opacity: {alpha}"); } @@ -360,7 +362,7 @@ fn clone_cursor_from_an_inactive_document_cannot_replace_the_active_offset_refer app.ui.document_windows.arrangement = Some(Arrangement::TwoUpVertical); super::testing::frame(&mut app); let document = app.session.active().unwrap().doc.id; - let slots = app.session.presets.clone.clone(); + let slots = app.session.presets().clone.clone(); let revision = app.session.active().unwrap().revision; super::testing::move_to(&mut app, [40.0, 30.0], egui::Modifiers::NONE); assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [40.0, 30.0]))); @@ -380,7 +382,7 @@ fn clone_cursor_from_an_inactive_document_cannot_replace_the_active_offset_refer assert_eq!(crate::preset_panels::clone_offset_edit(&app, [-20.0, -10.0]).unwrap()["anchor"], json!([40.0, 30.0])); super::testing::move_to(&mut app, [44.0, 34.0], egui::Modifiers::NONE); assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [44.0, 34.0])), "the active canvas still updates normally"); - assert_eq!(app.session.presets.clone, slots, "hover does not establish a source anchor"); + assert_eq!(app.session.presets().clone, slots, "hover does not establish a source anchor"); assert_eq!(app.session.active().unwrap().revision, revision, "hover does not paint"); } } diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index b3442742e7..2f6ca90908 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -3,6 +3,7 @@ //! selected) and its commands. How the panel draws and edits a colour is `ColorPanel`'s, covered //! in craft-color. +use photocraft_engine::presets::PresetsExt; use egui::{Modifiers, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -178,7 +179,7 @@ fn copy_commands_and_add_to_swatches() { app.ui.color_panel.panel.background = false; app.ui.color_panel.panel.mode = ColorPanelMode::ColorWheel; - let count = |app: &PhotocraftApp| app.session.presets.swatches.iter().map(|group| group.entries.len()).sum::(); + let count = |app: &PhotocraftApp| app.session.presets().swatches.iter().map(|group| group.entries.len()).sum::(); let before = count(&app); let mut h = color_tab_of(AppTheme::pro(), app); h.get_by_label("Add to Swatches").click(); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 32914e4874..cb6a220072 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use crate::canvas_tool_menu::MenuKind; use craft::automation::actions::{Action, ActionList, ActionStep}; @@ -113,7 +114,7 @@ fn perf_output_includes_slow_frames() { } // A nested run (`actions.play` → its view steps through `App::run`) is inside the outer // call's time: the frame counts the outer command once, not the steps again. - app.session.actions.list.push(action("Zoom", vec![("view.zoomIn", json!({})), ("view.zoomOut", json!({}))])).unwrap(); + app.session.actions_mut().list.push(action("Zoom", vec![("view.zoomIn", json!({})), ("view.zoomOut", json!({}))])).unwrap(); let played = app.run("actions.play", json!({"action": "Zoom"})).unwrap(); assert_eq!(played["ran"], 2, "{played}"); let outer_ms = app.perf.command_ms; @@ -1747,8 +1748,8 @@ fn control_refuses_linked_smart_objects_in_commands_and_actions_but_local_editin let r = call(&mut app, &ctx, "engine.execute", json!({"command": command, "params": {"layer": smart.0}})); assert_eq!(r["ok"], false, "{r}"); assert!(r["error"].as_str().unwrap().contains("ambient smart-object path denied"), "{r}"); - app.session.actions.list = ActionList::new(); - app.session.actions.list.push(action("Linked contents", vec![(command, json!({"layer": smart.0}))])).unwrap(); + app.session.actions_mut().list = ActionList::new(); + app.session.actions_mut().list.push(action("Linked contents", vec![(command, json!({"layer": smart.0}))])).unwrap(); let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Linked contents"}})); assert_eq!(r["ok"], true, "{r}"); assert_eq!(r["result"]["ran"], 0, "{r}"); @@ -1774,7 +1775,7 @@ fn control_refuses_linked_smart_objects_in_commands_and_actions_but_local_editin fn actions_play_checks_each_step_over_control() { let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.session.actions.list.push(action("Open", vec![("file.open", json!({"path": "/etc/passwd"})), ("layer.new.layer", json!({}))])).unwrap(); + app.session.actions_mut().list.push(action("Open", vec![("file.open", json!({"path": "/etc/passwd"})), ("layer.new.layer", json!({}))])).unwrap(); let ctx = app.ctx().clone(); let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Open"}})); assert_eq!(r["ok"], true, "{r}"); @@ -1789,7 +1790,7 @@ fn actions_play_checks_each_step_over_control() { fn actions_play_checks_each_step_for_synthetic_input() { let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.session.actions.list.push(action("Open", vec![("file.open", json!({"path": "/etc/passwd"})), ("layer.new.layer", json!({}))])).unwrap(); + app.session.actions_mut().list.push(action("Open", vec![("file.open", json!({"path": "/etc/passwd"})), ("layer.new.layer", json!({}))])).unwrap(); app.automation_input = true; let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); assert_eq!(r["ran"], 0, "{r}"); @@ -1798,7 +1799,7 @@ fn actions_play_checks_each_step_for_synthetic_input() { // A local play (no automation input) still runs recorded steps. app.automation_input = false; - app.session.actions.list.delete_step(0, 0).unwrap(); + app.session.actions_mut().list.delete_step(0, 0).unwrap(); app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); assert_eq!(r["ran"], 1, "{r}"); diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index 5b04a7b7b1..ba765906f0 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -10,6 +10,7 @@ //! The function reads no input and drains no queue: a second pass in one frame shows the value as the first left it and //! reports only its own events and asks. +use photocraft_engine::presets::PresetsExt; use std::sync::Arc; use craft::behavior::{EditEvent, EditEvents, Mixed}; @@ -434,7 +435,7 @@ pub fn gradient_presets(app: &PhotocraftApp) -> Vec { StopColor::Rgb(rgb) => *rgb, }; app.session - .presets + .presets() .gradients .iter() .map(|group| { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs index 3e4ea6e649..7817d00738 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use craft::behavior::PixelSize; @@ -201,7 +202,7 @@ fn open_session( Coverage::None => None, }; let source = photocraft_engine::color_cmds::composite_profile(&st.doc); - let display = app.session.color.canvas_display(&st.doc).map_err(|e| e.to_string())?; + let display = app.session.color().canvas_display(&st.doc).map_err(|e| e.to_string())?; let lab_transform = craft::cms::cached(&source, craft::cms::Builtin::LabD50.profile(), Default::default()).map_err(|e| e.to_string())?; let scope_transform = craft::cms::cached(&source, craft::cms::Builtin::Srgb.profile(), Default::default()).map_err(|e| e.to_string())?; let float = surf.format().sample == photocraft_color::SampleType::F32; diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs index 7a702be396..8c0ff2c990 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs @@ -3,6 +3,7 @@ //! shown, Open develops every one and Cancel closes every one. The framework's `RawFilmstrip` //! draws the tiles; this module holds the raws and their thumbnails. +use photocraft_engine::color_cmds::ColorExt; use super::open::{Target, commit_open_raw, open_raw_with, return_on_failure}; use super::sidecar::read_sidecar; use super::{CameraRaw, PhotocraftApp, RawOpen, Rect, Value, hosted, image, json, workspace_demosaic}; @@ -54,7 +55,7 @@ fn thumbnail(app: &PhotocraftApp, index: usize) -> Option { } } let px: Vec<[f32; 4]> = acc.iter().map(|a| if a[4] > 0.0 { [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]] } else { [0.0; 4] }).collect(); - let display = app.session.color.canvas_display(doc).ok()?; + let display = app.session.color().canvas_display(doc).ok()?; Some(image(&px, tw, th, &display)) } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs index ded5ce0f39..c234f5a4d7 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs @@ -1,5 +1,6 @@ //! Re-develop completion must follow the replacement document across intervening tab changes. +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index cc062d4c52..a01d7c2c68 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use super::convert::{RawStart, apply_raw_conversions, open_pixels, open_raw_pixels, output_sharpening, raw_conversions}; use super::sidecar::{read_sidecar, write_sidecar}; use super::{CameraRaw, LayerId, PhotocraftApp, Rect, Value, json}; diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index eefb909743..d5aacaa301 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -8,6 +8,7 @@ //! [`answer_for`]; a window the app holds itself opens one with [`open_for_window`] and pulls the //! answer with [`answer_for_window`]. +use photocraft_engine::color_cmds::ColorExt; use craft::cms::convert::CmykConverter; use craft::color_ui::ui::{ColorPickerDialog, ColorPickerResult, PickedColor}; use craft::theme::{ModelValues, Srgba}; @@ -164,7 +165,7 @@ pub(crate) fn same_inks(a: [f32; 4], b: [f32; 4]) -> bool { /// The CMYK converter of the document colour settings; the built-in coated one when the profile is unusable. fn converter(app: &PhotocraftApp) -> CmykConverter { - CmykConverter::new(app.session.color.working(photocraft_doc::ColorMode::Cmyk)).ok().unwrap_or_else(|| CmykConverter::coated().clone()) + CmykConverter::new(app.session.color().working(photocraft_doc::ColorMode::Cmyk)).ok().unwrap_or_else(|| CmykConverter::coated().clone()) } /// Opens `dialog` for `target` with the app's picker features, under `parent` when it has one. diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index 2b568a0955..a308d0a051 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -9,6 +9,7 @@ //! full resolution (one history step). Reduced previews approximate fine detail and effects. //! Cancel never touches the document, so the previous selection stays as it was. +use photocraft_engine::color_cmds::ColorExt; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -197,7 +198,7 @@ fn query_key(app: &PhotocraftApp, params: &Value) -> u64 { // This runs several times per frame, including mere pointer motion. Debug-formatting a // ProofView serializes the whole ICC profile/LUT; proof() also clones the default profile. // Borrow the state and use the profile's memoized content hash instead. - let proof = app.session.active().and_then(|st| app.session.color.proof_ref(st.doc.id)); + let proof = app.session.active().and_then(|st| app.session.color().proof_ref(st.doc.id)); proof.is_some().hash(&mut key); if let Some(proof) = proof { let setup = &proof.setup; @@ -255,7 +256,7 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> return Ok(mask); } if params.get("select").and_then(Value::as_str) == Some("outOfGamut") { - let pv = app.session.color.proof(proxy.id); + let pv = app.session.color().proof(proxy.id); let (m, _) = photocraft_engine::color_cmds::gamut_mask(proxy, &pv.setup, pv.gamut_threshold).map_err(|e| e.to_string())?; let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false); let mut mask: Vec = m.iter().map(|v| f32::from(*v) / 255.0).map(|v| if invert { 1.0 - v } else { v }).collect(); @@ -307,7 +308,7 @@ fn report(app: &mut PhotocraftApp, error: Option) { fn thumbnail(app: &PhotocraftApp, proxy: &Document) -> Result, String> { let (w, h) = (proxy.size.width as usize, proxy.size.height as usize); let buf = photocraft_compose::thumbnail_buffer(proxy, proxy.size.width.max(proxy.size.height)); - let thumb = app.session.color.canvas_display(proxy).map_err(|e| e.to_string())?.to_rgba8(&buf); + let thumb = app.session.color().canvas_display(proxy).map_err(|e| e.to_string())?.to_rgba8(&buf); let size = [thumb.width as usize, thumb.height as usize]; if size != [w, h] || thumb.pixels.len() != w * h * 4 { return Err(format!("the image thumbnail is {}×{}, expected {w}×{h}", thumb.width, thumb.height)); diff --git a/crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs index 3d5a9046fb..6048f3d15d 100644 --- a/crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs +++ b/crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs @@ -1,5 +1,6 @@ //! JPEG Options on Save As and Save a Copy (FILE-215-19): the quality and format it asks for, the //! scripted `quality` / `jpegFormat` that skip it, and recording and playback. +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use crate::jpeg_options_ui::{self, REMEMBER_KEY, Remembered}; use craft::automation::actions::ActionStep; @@ -73,7 +74,7 @@ pub(super) fn set_field(h: &mut Prompted, field: &str, value: Value) { /// The steps of the first recorded action. pub(super) fn steps(h: &Prompted) -> &Vec { - &h.state().session.actions.list.action(0).unwrap().steps + &h.state().session.actions().list.action(0).unwrap().steps } /// Save As to a JPEG asks first, starting at the Export preferences' quality (85 → 10, Maximum) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 21b5a651c2..bd9a2be4c9 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -2,6 +2,8 @@ //! with a preview and an estimated file size. The estimate encodes a small proxy and scales by //! pixel count, so the dialog stays instant on 36 MP documents. +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; use std::path::PathBuf; use std::sync::Arc; #[cfg(not(target_arch = "wasm32"))] @@ -244,7 +246,7 @@ const RESAMPLE_CHOICES: [Resample; 7] = [ /// settings read with [`options_of`]. fn preset_library(app: &PhotocraftApp) -> PresetLibrary { let mut library = PresetLibrary::new(); - for preset in &app.session.presets.export_presets { + for preset in &app.session.presets().export_presets { if let Ok(Value::Object(settings)) = serde_json::to_value(&preset.settings) { // A name the library refuses (a duplicate ignoring case) is one the engine would not have kept. let _ = library.add(&GroupPath::root(), &preset.name, options_of(&settings)); @@ -484,7 +486,7 @@ fn effective_source_profile(app: &PhotocraftApp, doc: &Document) -> Arc .as_ref() .and_then(|bytes| photocraft_engine::color_cmds::profile_from_bytes(bytes).ok()) .filter(|profile| profile.color_space == photocraft_engine::color_cmds::mode_space(doc.mode)) - .unwrap_or_else(|| app.session.color.working(doc.mode)) + .unwrap_or_else(|| app.session.color().working(doc.mode)) } fn s(f: &Map, k: &str) -> String { @@ -909,7 +911,7 @@ fn layer_documents(app: &PhotocraftApp, layers: &[LayerId]) -> Vec { /// whose own profile decides. Tagged documents skip the profile lookup on every frame. fn working_profile_hash(app: &PhotocraftApp) -> Option { let doc = &app.session.active()?.doc; - doc.icc_profile.is_none().then(|| app.session.color.working(doc.mode).content_hash().to_string()) + doc.icc_profile.is_none().then(|| app.session.color().working(doc.mode).content_hash().to_string()) } /// One preset edit of the dialog, stored through the engine's commands. `created` holds the values diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index ccbc1244db..b2a66a5186 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -12,6 +12,7 @@ fn ico_export_is_available_and_rejects_oversize_output() { assert_eq!((resized.size.width, resized.size.height), (150, 100)); } +use photocraft_engine::color_cmds::ColorExt; use super::*; use craft::ui::runtime::memory::set_saved_value; diff --git a/crates/ui-egui/src/dialogs/file_forms/tests.rs b/crates/ui-egui/src/dialogs/file_forms/tests.rs index 6a2b71a390..b974dbd03c 100644 --- a/crates/ui-egui/src/dialogs/file_forms/tests.rs +++ b/crates/ui-egui/src/dialogs/file_forms/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::actions::{Action, ActionStep}; use craft::automation::ui::actions::ActionSelection; use craft::ui::dialog::DialogId; @@ -28,7 +29,7 @@ fn create_droplet_saves_the_selected_actions_set_and_steps() { for (set_name, name, step) in [("A", "Retouch", "image.adjustments.invert"), ("B", "Turn", "image.imageRotation.90cw")] { let mut action = Action::new(name, vec![ActionStep::new(step, json!({}))]); action.set = Some(set_name.into()); - app.session.actions.list.push(action).unwrap(); + app.session.actions_mut().list.push(action).unwrap(); } app.ui.actions.panel.selected = Some(ActionSelection::Action(1)); let id = open_create_droplet(&mut app).unwrap(); @@ -56,7 +57,7 @@ fn create_droplet_uses_the_action_selected_in_the_form() { app.run("file.new", json!({"width": 2, "height": 1})).unwrap(); app.run("file.saveACopy", json!({"path": input})).unwrap(); for (name, step) in [("Invert", "image.adjustments.invert"), ("Rotate", "image.imageRotation.90cw")] { - app.session.actions.list.push(Action::new(name, vec![ActionStep::new(step, json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new(name, vec![ActionStep::new(step, json!({}))])).unwrap(); } app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); let id = open_create_droplet(&mut app).unwrap(); diff --git a/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs b/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs index fefd1bb085..3e50075bd8 100644 --- a/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs @@ -1,5 +1,6 @@ //! #3820: edit custom paper through the real Print dialog, preview it, and print safely to PDF. //! The dialog host is crate-private, so these are unit tests of the app. +use photocraft_engine::print_cmds::PrintExt; use craft::print::ui::HostedPrint; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; @@ -31,7 +32,7 @@ fn app() -> (Box, DialogId) { fn app_remembering(paper: Option) -> (Box, DialogId) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); // Print lists this printer and does not ask the spooler. - app.session.printer_source = Some(std::sync::Arc::new(|| { + *app.session.printer_source_mut() = Some(std::sync::Arc::new(|| { vec![craft::print::Printer { name: "Test native printer".into(), default: true, two_sided: None, description: String::new() }] })); app.run("file.new", json!({"width": 120, "height": 80, "name": "Custom paper"})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index a00d9402ba..54eec857e1 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::print_cmds::PrintExt; use craft::print::ui::HostedPrint; use craft::ui::dialog::{DialogId, StackDialog as _}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedSaveForWeb, Resample, SAVE_PATH_KEY, WebFormat, WebSlices}; @@ -7,7 +8,7 @@ use std::sync::Arc; pub(super) fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.printer_source = + *app.session.printer_source_mut() = Some(Arc::new(|| vec![craft::print::Printer { name: "Test printer".into(), default: true, two_sided: None, description: String::new() }])); app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap(); app @@ -86,14 +87,14 @@ fn check_saved_settings_with_cached_printers(cached: &'static [&'static str]) { let ctx = app.ctx().clone(); let available = Arc::new(AtomicBool::new(false)); let listed = Arc::clone(&available); - app.session.printer_source = Some(Arc::new(move || { + *app.session.printer_source_mut() = Some(Arc::new(move || { if listed.load(Ordering::SeqCst) { vec![listed_printer("Saved printer")] } else { cached.iter().map(|name| listed_printer(name)).collect() } })); app.session.prefs.edit(|p| { p.dialogs.insert(photocraft_engine::print_cmds::REMEMBERED.into(), json!({"printer": "Saved printer", "printerSettings": "0011"})); }); let mut lister = photocraft_engine::Session::new(); - lister.printer_source = app.session.printer_source.clone(); + *lister.printer_source_mut() = app.session.printer_source().cloned(); let (held_tx, held) = std::sync::mpsc::channel(); let (release, released_rx) = std::sync::mpsc::channel::<()>(); let holder = std::thread::spawn(move || { @@ -131,7 +132,7 @@ fn check_saved_settings_with_cached_printers(cached: &'static [&'static str]) { fn an_empty_fresh_printer_list_drops_the_saved_driver_settings() { let mut app = app(); let ctx = app.ctx().clone(); - app.session.printer_source = Some(Arc::new(Vec::new)); + *app.session.printer_source_mut() = Some(Arc::new(Vec::new)); app.session.prefs.edit(|p| { p.dialogs.insert(photocraft_engine::print_cmds::REMEMBERED.into(), json!({"printer": "Saved printer", "printerSettings": "0011"})); }); @@ -181,7 +182,7 @@ fn print_dialog_retries_an_uncached_printer_list_after_the_spooler_is_released() let ctx = app.ctx().clone(); let asked = Arc::new(AtomicUsize::new(0)); let counted = Arc::clone(&asked); - app.session.printer_source = Some(Arc::new(move || { + *app.session.printer_source_mut() = Some(Arc::new(move || { counted.fetch_add(1, Ordering::SeqCst); vec![craft::print::Printer { name: "Retry printer".into(), default: true, two_sided: None, description: String::new() }] })); diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index df82081d16..aadd81de28 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -8,6 +8,7 @@ //! The preview runs the *same engine command* on the downsampled proxy document (pixel-sized //! parameters scaled by the proxy factor), so what you preview is what you get. +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use craft::behavior::NumberCodec; @@ -460,7 +461,7 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map proof_setup_defaults(app, &mut map); } if command == "edit.colorSettings" - && let Ok(Value::Object(current)) = serde_json::to_value(&app.session.color.settings) + && let Ok(Value::Object(current)) = serde_json::to_value(&app.session.color().settings) { map.extend(current.into_iter().filter(|(key, _)| params.iter().any(|p| p.key == *key))); } @@ -877,7 +878,7 @@ fn assign_profile_defaults(app: &PhotocraftApp, fields: &mut Map) let Some(st) = app.session.active() else { return }; let Some(spec) = photocraft_engine::commands::find("edit.assignProfile") else { return }; let space = photocraft_engine::color_cmds::mode_space(st.doc.mode); - let fits = |name: &str| name == "none" || app.session.color.resolve(name, Some(&st.doc), None).is_ok_and(|p| p.color_space == space); + let fits = |name: &str| name == "none" || app.session.color().resolve(name, Some(&st.doc), None).is_ok_and(|p| p.color_space == space); let builtin: Vec = Param::parse_list(spec.params) .into_iter() .filter(|p| p.key == "profile") @@ -944,7 +945,7 @@ fn global_light_defaults(app: &PhotocraftApp, fields: &mut Map) { /// Proof Setup reflects the active document's current proofing condition, never remembered values. fn proof_setup_defaults(app: &PhotocraftApp, fields: &mut Map) { let Some(st) = app.session.active() else { return }; - let pv = app.session.color.proof(st.doc.id); + let pv = app.session.color().proof(st.doc.id); fields.insert("profile".into(), json!(pv.setup.name)); fields.insert("intent".into(), json!(pv.setup.intent.id())); fields.insert("bpc".into(), json!(pv.setup.bpc)); @@ -1207,7 +1208,7 @@ pub(crate) fn preview_document_for_target( scale_preview_params(command, &mut p, run_k); } let mut s = photocraft_engine::Session::new(); - s.color.settings = color.clone(); + s.color_mut().settings = color.clone(); if let Some((foreground, background)) = tool_colors { s.tools.foreground = foreground; s.tools.background = background; diff --git a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs index 7788682bf0..cda4b8792c 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs @@ -9,6 +9,7 @@ //! `lutSize`, `lutError`) and Lens Blur's `channel:N` sources and Match Color's textual //! `source`; the family's `command_params` (dialogs-w24) maps them back and leaves the private ones out. +use photocraft_engine::color_cmds::ColorExt; use std::path::PathBuf; use std::sync::Arc; @@ -136,8 +137,8 @@ fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32 ColorSpace::Rgb | ColorSpace::Gray => photocraft_engine::color_cmds::document_profile(doc), _ => photocraft_engine::color_cmds::composite_profile(doc), }; - let source = app.session.color.working(ColorMode::Rgb); - let options = TransformOptions { intent: app.session.color.settings.intent(), bpc: app.session.color.settings.bpc, ..Default::default() }; + let source = app.session.color().working(ColorMode::Rgb); + let options = TransformOptions { intent: app.session.color().settings.intent(), bpc: app.session.color().settings.bpc, ..Default::default() }; let transform = craft::cms::transform::cached(&source, &destination, options).map_err(|e| e.to_string())?; let mut output = [0.0; 16]; transform.eval(&color[..3], &mut output).map_err(|e| e.to_string())?; diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 4284dec547..faf7037fbc 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamKind}; use egui_kittest::Harness; @@ -112,7 +113,7 @@ fn indexed_matte_tool_seeds_use_document_encoded_rgb() { use craft::cms::Transform; let mut session = photocraft_engine::Session::new(); - session.color.settings.working_rgb = "display-p3".into(); + session.color_mut().settings.working_rgb = "display-p3".into(); session.execute("file.new", json!({"width": 2, "height": 2, "background": "transparent"})).unwrap(); session.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); let mut app = PhotocraftApp::new(session, crate::Services::default()); @@ -121,9 +122,9 @@ fn indexed_matte_tool_seeds_use_document_encoded_rgb() { let colors = rows::indexed_matte_defaults(&app); let doc = app.session.active().unwrap().doc.clone(); - let source = app.session.color.working(photocraft_doc::ColorMode::Rgb); + let source = app.session.color().working(photocraft_doc::ColorMode::Rgb); let destination = photocraft_engine::color_cmds::document_profile(&doc); - let transform = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc).unwrap(); + let transform = Transform::new(&source, &destination, app.session.color().settings.intent(), app.session.color().settings.bpc).unwrap(); for (value, input) in [("foreground", [0.2, 0.4, 0.8]), ("background", [0.8, 0.4, 0.2])] { let mut output = [0.0; 16]; transform.eval(&input, &mut output).unwrap(); @@ -338,12 +339,12 @@ fn proof_setup_dialog_reflects_active_document_proof_condition() { let d_fresh = open(&mut app, "view.proofSetup").unwrap(); assert_eq!(fields_of(&app, d_fresh).text("profile"), Some("working-cmyk")); ok(&mut app, d_fresh); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "working-cmyk"); + assert_eq!(app.session.color().proof(doc1_id).setup.name, "working-cmyk"); // 1. A preset sets sRGB and turns Proof Colors on. crate::menus::invoke(&mut app, &ctx, "view.proofSetup.internetStandardRgb", Value::Null).unwrap(); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); - assert!(app.session.color.proof(doc1_id).enabled); + assert_eq!(app.session.color().proof(doc1_id).setup.name, "srgb"); + assert!(app.session.color().proof(doc1_id).enabled); // 2. The dialog starts with the document's condition; an unchanged OK keeps it and Proof Colors on. let d_id = open(&mut app, "view.proofSetup").unwrap(); @@ -353,7 +354,7 @@ fn proof_setup_dialog_reflects_active_document_proof_condition() { assert_eq!(f.bool("bpc"), Some(true)); assert_eq!(f.bool("simulatePaper"), Some(false)); ok(&mut app, d_id); - let pv = app.session.color.proof(doc1_id); + let pv = app.session.color().proof(doc1_id); assert_eq!(pv.setup.name, "srgb"); assert!(pv.enabled); @@ -368,7 +369,7 @@ fn proof_setup_dialog_reflects_active_document_proof_condition() { // 4. Cancel keeps the document. set(&mut app, d_id, "profile", json!("display-p3")); cancel(&mut app, d_id); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); + assert_eq!(app.session.color().proof(doc1_id).setup.name, "srgb"); // 5. Each document opens the dialog at its own condition. app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); @@ -389,8 +390,8 @@ fn proof_setup_dialog_reflects_active_document_proof_condition() { // 6. An edit in the dialog updates the active document only. set(&mut app, d_id1, "profile", json!("adobe-rgb-compat")); ok(&mut app, d_id1); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "adobe-rgb-compat"); - assert_eq!(app.session.color.proof(doc2_id).setup.name, "display-p3"); + assert_eq!(app.session.color().proof(doc1_id).setup.name, "adobe-rgb-compat"); + assert_eq!(app.session.color().proof(doc2_id).setup.name, "display-p3"); } /// The Color Lookup dialog's own fields run the command: `fileName` used to be filled with `0` diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 5b956a5347..e5d03ad067 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -7,6 +7,7 @@ //! draft as `StyleValue::Other` so everything the dialog doesn't model (gradient strokes, imported //! contours, PSD data) survives an apply. +use photocraft_engine::presets::PresetsExt; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; @@ -482,7 +483,7 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option { let layer_id = st.active_layer?; let layer = st.doc.layer(layer_id)?.clone(); let (light, mode, doc) = (st.doc.global_light.angle, st.doc.mode, st.doc.id); - let user: Map = app.session.presets.layer_defaults.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); + let user: Map = app.session.presets().layer_defaults.iter().map(|(k, v)| (k.clone(), v.clone())).collect(); let keys = blend_keys(); let specs = specs(&keys, &user, light); let mut draft = LayerStyleDraft::new(draft_of(&layer, light, mode)); @@ -595,7 +596,7 @@ fn pattern_rows(patterns: &[(String, String)], _: &Env) -> Vec fn gradient_presets(app: &PhotocraftApp) -> Vec<(String, GradientStops)> { let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); app.session - .presets + .presets() .gradients .iter() .flat_map(|g| g.items.iter()) @@ -616,7 +617,7 @@ struct StylePresets { /// The Styles page's presets. fn style_presets(app: &mut PhotocraftApp) -> PresetSource<'static, String> { - let groups = app.session.presets.styles.iter().map(|group| (group.name.clone(), group.items.iter().map(|st| st.name.clone()).collect())).collect(); + let groups = app.session.presets().styles.iter().map(|group| (group.name.clone(), group.items.iter().map(|st| st.name.clone()).collect())).collect(); let inputs = StylePresets { groups, library: StyleLibrary::held(app) }; PresetSource::new(inputs, PresetFns::new(style_rows).thumb(style_thumb)) } diff --git a/crates/ui-egui/src/dialogs/layer_style/contour.rs b/crates/ui-egui/src/dialogs/layer_style/contour.rs index 70bfe13762..e59b3cfbbd 100644 --- a/crates/ui-egui/src/dialogs/layer_style/contour.rs +++ b/crates/ui-egui/src/dialogs/layer_style/contour.rs @@ -1,6 +1,7 @@ //! Layer Style contours: the engine's contour parameters as the framework's `Contour`, the user's //! contour library, and the Contour Editor opened as a child of the Layer Style dialog. +use photocraft_engine::presets::PresetsExt; use craft::imaging::layer_style::{Contour, ContourPoint}; use craft::imaging::ui::layer_style::{ContourAction, ContourEditorDialog, ContourRequest, HostedLayerStyle}; use craft::ui::dialog::{DialogId, DialogResult}; @@ -55,7 +56,7 @@ pub(super) fn to_param(c: &Contour) -> Value { /// The user's contour library. pub(super) fn user_contours(app: &PhotocraftApp) -> Vec { - app.session.presets.contours.iter().map(from_doc).collect() + app.session.presets().contours.iter().map(from_doc).collect() } /// The engine's interpolation of a contour's points (levels `0..=255` on both axes) as one output @@ -145,7 +146,7 @@ pub(super) fn library_action(app: &mut PhotocraftApp, action: ContourAction) { Ok(json!({"path": path})) }) }), - ContourAction::Delete(i) => match app.session.presets.contours.get(i).map(name_of) { + ContourAction::Delete(i) => match app.session.presets().contours.get(i).map(name_of) { Some(name) => app.run("layer.layerStyle.contours.delete", json!({"name": name})), None => Err("no such contour".into()), }, diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 3ee114f20c..40629cbe2d 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use egui::vec2; use egui_kittest::{Harness, kittest::Queryable}; use photocraft_doc::effects::{BevelTechnique, FxPaint, GlowSource}; @@ -681,7 +682,7 @@ fn new_style_saves_pending_state_and_a_swatch_apply_restores_it() { h.run_steps(3); // The preset is saved at once under the default name "Style". assert_eq!(h.state().framework.dialogs.stack().top(), Some(id), "New Style… opens no other dialog"); - let preset = h.state().session.presets.styles.iter().flat_map(|g| g.items.iter()).find(|st| st.name == "Style").expect("the preset is created"); + let preset = h.state().session.presets().styles.iter().flat_map(|g| g.items.iter()).find(|st| st.name == "Style").expect("the preset is created"); assert_eq!(preset.effects.len(), 1, "only the enabled instance is saved"); assert_eq!(preset.opacity, Some(0.4), "the pending opacity is saved"); diff --git a/crates/ui-egui/src/dialogs/new_doc_ui.rs b/crates/ui-egui/src/dialogs/new_doc_ui.rs index 13bc86b4a0..dccabf54eb 100644 --- a/crates/ui-egui/src/dialogs/new_doc_ui.rs +++ b/crates/ui-egui/src/dialogs/new_doc_ui.rs @@ -2,6 +2,8 @@ //! last created settings, carries the colour picker, the saved presets and the recent list between the dialog and the //! engine, and runs `file.new` with what Create answers. +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; use craft::behavior::PixelSize; use craft::theme::Srgba; use craft::ui::contract::{Bind, SaveKey}; @@ -64,7 +66,7 @@ pub(crate) fn open(app: &mut PhotocraftApp) -> DialogId { dialog }) .saved(saved_library(app)) - .recent(app.session.presets.recent_documents.iter().map(to_options).collect()); + .recent(app.session.presets().recent_documents.iter().map(to_options).collect()); app.framework.dialogs.open(dialog) } @@ -153,7 +155,7 @@ fn listed_pixel_aspect(app: &PhotocraftApp, id: &str) -> String { /// The engine's saved document presets as the dialog's library, in the engine's order. fn saved_library(app: &PhotocraftApp) -> PresetLibrary { let mut library = PresetLibrary::new(); - for preset in &app.session.presets.documents { + for preset in &app.session.presets().documents { let mut options = to_options(&preset.settings); options.name.clone_from(&preset.name); if library.add(&GroupPath::root(), &preset.name, options).is_err() { @@ -174,7 +176,7 @@ pub(crate) fn profiles(app: &PhotocraftApp) -> Vec { let space = photocraft_engine::color_cmds::mode_space(*mode); let mut others: Vec = craft::cms::Builtin::ALL.iter().filter(|b| b.profile().color_space == space).map(|b| b.id().to_string()).collect(); others.extend(installed.iter().filter(|i| i.is_destination() && i.color_space == space).map(|i| i.path.clone())); - ColorProfiles::new(*dialog_mode, app.session.color.working(*mode).description.clone(), others) + ColorProfiles::new(*dialog_mode, app.session.color().working(*mode).description.clone(), others) }) .collect() } diff --git a/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs b/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs index b8fefc374f..6410df2fe7 100644 --- a/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs @@ -1,3 +1,6 @@ +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; use super::*; use crate::new_doc_remember_tests::{app, fields, harness, open, press_create}; use egui_kittest::kittest::Queryable; @@ -17,7 +20,7 @@ fn color_profile_menu_lists_the_profiles_of_the_modes_space() { let lists = profiles(&app); let of = |mode: DialogMode| lists.iter().find(|p| p.mode == mode).unwrap_or_else(|| panic!("{mode:?} has a list")); let rgb = of(DialogMode::Rgb); - assert_eq!(rgb.working, app.session.color.working(photocraft_color::ColorMode::Rgb).description); + assert_eq!(rgb.working, app.session.color().working(photocraft_color::ColorMode::Rgb).description); assert!(rgb.others.contains(&Builtin::AdobeRgbCompat.id().to_string())); assert!(!rgb.others.contains(&Builtin::CoatedCmyk.id().to_string())); let cmyk = of(DialogMode::Cmyk); @@ -141,7 +144,7 @@ fn save_restart_select_create_and_delete_through_the_dialog() { h.run_steps(1); h.get_by_label("Save Preset").click(); h.run_steps(3); - let stored = h.state().session.presets.documents.clone(); + let stored = h.state().session.presets().documents.clone(); assert_eq!(stored.iter().map(|p| p.name.as_str()).collect::>(), ["Wide"]); let size = (stored[0].settings.width, stored[0].settings.height); assert_eq!(size, (1920, 1080), "the dialog's settings are stored"); @@ -170,7 +173,7 @@ fn save_restart_select_create_and_delete_through_the_dialog() { assert_eq!(fields(h.state(), id)["tab"], "saved", "a saved preset opens the Saved tab"); h.get_by_label("Delete").click(); h.run_steps(3); - assert!(h.state().session.presets.documents.is_empty()); + assert!(h.state().session.presets().documents.is_empty()); } /// Opens New Document, applies `edit` to the settings it shows and presses Create. @@ -195,7 +198,7 @@ fn create_makes_a_bitmap_document() { let doc = &h.state().session.active().expect("a document was created").doc; assert_eq!((doc.size.width, doc.size.height), (32, 24)); assert_eq!(doc.mode, ColorMode::Bitmap, "not a silent RGB document"); - let recent = &h.state().session.presets.recent_documents; + let recent = &h.state().session.presets().recent_documents; assert_eq!((recent[0].mode.as_str(), recent[0].depth, recent[0].background.as_str()), ("bitmap", 1, "black")); assert_eq!(to_options(&recent[0]).color_mode, DialogMode::Bitmap, "the Recent card opens on Bitmap again"); } diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index cd71437c87..1bb022d47d 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -5,6 +5,7 @@ //! cancelling a profile question retains its existing behaviour of cancelling the whole queue. //! Files that finish reading while a prompt is up wait their turn. +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use craft::color_ui::ui::{ProfileAction, ProfileMismatchDialog, ProfileMode, ProfileQuestion}; @@ -364,7 +365,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result) -> Result usize { match cmd { "brush.presets.importAbr" => app.session.tools.presets.iter().filter(|x| !x.builtin && x.group == group).count(), - "gradient.presets.importGrd" => app.session.presets.gradients.iter().filter(|g| g.name == group).map(|g| g.items.len()).sum(), + "gradient.presets.importGrd" => app.session.presets().gradients.iter().filter(|g| g.name == group).map(|g| g.items.len()).sum(), _ => 0, } } diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs index 0c5d3d5b48..d3bfda6c30 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs @@ -1,4 +1,5 @@ //! The documented dialog API answers the import question: the default, Replace and Cancel. +use photocraft_engine::presets::PresetsExt; use craft::ui::dialog::DialogId; use super::*; @@ -33,12 +34,12 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu fn group(app: &PhotocraftApp, kind: Kind, name: &str) -> Value { match kind { Kind::Brushes => json!(app.session.tools.presets.iter().filter(|p| p.group == name).collect::>()), - Kind::Gradients => json!(app.session.presets.gradients.iter().filter(|g| g.name == name).collect::>()), + Kind::Gradients => json!(app.session.presets().gradients.iter().filter(|g| g.name == name).collect::>()), } } fn library(app: &PhotocraftApp) -> Value { - json!({"brushes": app.session.tools.presets.as_ref(), "gradients": app.session.presets.gradients, "selectedBrush": *app.session.tools.brush}) + json!({"brushes": app.session.tools.presets.as_ref(), "gradients": app.session.presets().gradients, "selectedBrush": *app.session.tools.brush}) } impl Fixture { @@ -78,7 +79,7 @@ impl Fixture { } Kind::Gradients => { assert_eq!(original[0]["items"].as_array().unwrap().len(), 2); - app.session.presets.gradients.iter_mut().find(|g| g.name == stem).unwrap().items[0].name = "Edited gradient".into(); + app.session.presets_mut().gradients.iter_mut().find(|g| g.name == stem).unwrap().items[0].name = "Edited gradient".into(); } } let edited = group(&app, kind, stem); diff --git a/crates/ui-egui/src/dialogs/screen_picker.rs b/crates/ui-egui/src/dialogs/screen_picker.rs index dbb986a9a7..2c72929f1e 100644 --- a/crates/ui-egui/src/dialogs/screen_picker.rs +++ b/crates/ui-egui/src/dialogs/screen_picker.rs @@ -2,6 +2,7 @@ //! Color Picker dialog and from colour popovers, runs through these functions. The capture, the //! capture windows, the loupe and the pixel mapping are the framework's //! (`craft::color_ui::ui::{ScreenPick, ScreenColorPicker}`). +use photocraft_engine::color_cmds::ColorExt; use crate::PhotocraftApp; use craft::color_ui::ui::{ScreenColorPicker, ScreenPickGesture, ScreenPickerWords}; use craft::theme::Srgba; @@ -57,7 +58,7 @@ pub fn cancel(app: &mut PhotocraftApp) { pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // A frame sampled during a held drag converts from the monitor's profile to sRGB; only a running pick needs it. if app.screen_pick.busy() { - app.screen_pick.set_monitor(&app.session.color.monitor()); + app.screen_pick.set_monitor(&app.session.color().monitor()); } ScreenColorPicker::new(&mut app.screen_pick, "PhotoCraft").show(ui); // The status is taken here rather than in `tick`: the words come from the Env, which needs a diff --git a/crates/ui-egui/src/dock/tests.rs b/crates/ui-egui/src/dock/tests.rs index 5b092580a1..4f4ce95dfa 100644 --- a/crates/ui-egui/src/dock/tests.rs +++ b/crates/ui-egui/src/dock/tests.rs @@ -1,6 +1,7 @@ //! Saving and restoring the workspace: what the preferences keep, what a save leaves to the host, and what //! a workspace switch restores. +use photocraft_engine::prefs::SavedPrefsExt; use craft::behavior::dock::{Action, Workspace}; use craft::color_ui::ui::ColorPanelMode; use serde_json::json; diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 87cb8677a3..722fa013a0 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use crate::{Services, menus}; use std::cell::{Cell, RefCell}; @@ -313,7 +314,7 @@ fn plain_save_of_a_flat_jpeg_asks_jpeg_options_and_records_a_plain_save() { confirm_options(&mut app); app.run("actions.stop", json!({})).unwrap(); assert_eq!(*written.borrow(), ["/pics/photo.jpg"]); - assert_eq!(app.session.actions.list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({}))]); + assert_eq!(app.session.actions().list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({}))]); } /// A plain Save confirmed in the dialog keeps a changed JPEG Options answer in its recorded step, @@ -341,7 +342,7 @@ fn plain_save_of_a_flat_jpeg_records_and_replays_a_changed_quality() { set_option(&mut app, "format", json!("progressive")); confirm_options(&mut app); app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({"quality": 3, "jpegFormat": "progressive"}))]); + assert_eq!(app.session.actions().list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({"quality": 3, "jpegFormat": "progressive"}))]); // Played on another flat JPEG: written over itself at quality 3, with no dialog or prompt. let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "other.jpg", &Default::default()).unwrap().bytes; let index = app.session.add_document(photocraft_io::import("other.jpg", &bytes).unwrap().document, Some("/pics/other.jpg".into())); @@ -1338,7 +1339,7 @@ fn flat_jpeg_saves_are_recorded_and_replay_over_the_open_file() { set_option(&mut app, "quality", json!(5)); confirm_options(&mut app); app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({"quality": 5}))]); + assert_eq!(app.session.actions().list.action(0).unwrap().steps, [ActionStep::new("file.save", json!({"quality": 5}))]); add_flat_jpeg(&mut app, "/pics/other.jpg"); written.borrow_mut().clear(); let played = app.run("actions.play", json!({"action": 0})).unwrap(); diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 4c40874686..d810f1da85 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use crate::{Services, menus}; use craft::host::{Picked, ScriptedFiles}; @@ -1444,7 +1445,7 @@ fn save_a_copy_is_recorded_and_replayed_as_a_copy() { app.run("actions.stop", json!({})).unwrap(); // PLAN: assumed panels-w29's `ActionStep` is `craft::automation::actions::ActionStep` let saved = craft::automation::actions::ActionStep::new("file.saveACopy", json!({"path": "/pics/copy.png"})); - assert_eq!(app.session.actions.list.actions()[0].steps.last(), Some(&saved)); + assert_eq!(app.session.actions().list.actions()[0].steps.last(), Some(&saved)); assert_eq!(crate::actions::label_of("file.saveACopy"), "Save a Copy"); written.borrow_mut().clear(); let played = app.run("actions.play", json!({"action": 0})).unwrap(); @@ -1493,7 +1494,7 @@ fn export_as_is_recorded_and_replayed() { control(&mut app, "ui.dialog.confirm", json!({"dialog": id})); app.run("actions.stop", json!({})).unwrap(); assert_eq!(*exported.borrow(), [("/pics/out.jpg".to_string(), 20, 10, Some(70))]); - let craft::automation::actions::ActionStep { command: step_id, params: step } = app.session.actions.list.actions()[0].steps.last().cloned().unwrap(); + let craft::automation::actions::ActionStep { command: step_id, params: step } = app.session.actions().list.actions()[0].steps.last().cloned().unwrap(); assert_eq!(step_id, "file.export.exportAs"); // The scale is the dialog's percentage, a number whatever its JSON form (`50` or `50.0`). assert_eq!((&step["path"], &step["format"], &step["quality"]), (&json!("/pics/out.jpg"), &json!("jpg"), &json!(70))); diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rs index f2197819f2..b98e393301 100644 --- a/crates/ui-egui/src/gpu_status.rs +++ b/crates/ui-egui/src/gpu_status.rs @@ -5,6 +5,7 @@ //! "started" hook once the first frames have rendered (the crash-safe startup marker), and //! provides the Help › System Info text (including the monitor profile in use). +use photocraft_engine::color_cmds::ColorExt; use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt}; use serde_json::json; @@ -208,8 +209,8 @@ pub fn system_info_json(app: &PhotocraftApp) -> serde_json::Value { "os": std::env::consts::OS, "arch": std::env::consts::ARCH, "gpu": app.perf.gpu_info, - "monitor": app.session.color.monitor_status(), - "displays": app.session.color.display_statuses(), + "monitor": app.session.color().monitor_status(), + "displays": app.session.color().display_statuses(), "lines": system_info(app), }) } diff --git a/crates/ui-egui/src/healing_indexed_alert_tests.rs b/crates/ui-egui/src/healing_indexed_alert_tests.rs index eb5ac8deb3..d40195a2e5 100644 --- a/crates/ui-egui/src/healing_indexed_alert_tests.rs +++ b/crates/ui-egui/src/healing_indexed_alert_tests.rs @@ -2,6 +2,7 @@ //! reference application's alert with OK and change neither the clone source, the pixels nor the //! History. RGB documents keep healing, and the Clone Stamp (not measured) keeps setting its source. +use photocraft_engine::presets::PresetsExt; use egui::Modifiers; use serde_json::json; @@ -27,7 +28,7 @@ type State = (Option<[f64; 2]>, Option<[f64; 2]>, Vec, usize); fn state(app: &PhotocraftApp) -> State { let st = app.session.active().unwrap(); let pixels = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()); - (app.ui.clone_source, app.session.presets.clone.active().source, pixels, st.history.past_len()) + (app.ui.clone_source, app.session.presets().clone.active().source, pixels, st.history.past_len()) } /// The alert is up once; OK closes it and leaves `before` as it was. diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index dc64309867..d153f69af5 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -471,6 +471,7 @@ fn open_recent_gate(app: &PhotocraftApp, path: &str) -> Result<(), String> { #[cfg(test)] mod tests { + use photocraft_engine::color_cmds::ColorExt; use super::*; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index d40c580558..8dc1a1dcae 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -1,5 +1,6 @@ //! Behavioural checks for switching languages in a running shell. +use photocraft_engine::prefs::SavedPrefsExt; use super::*; use crate::prefs_ui::{apply_window, open_preferences, set_draft, window_open}; use crate::{PhotocraftApp, Services}; diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index 1d0c5189b7..76ba9b36b8 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -10,6 +10,7 @@ //! shortcut whose command is disabled in the current state reports why on the status bar instead //! of doing nothing silently, as the greyed menu item shows. +use photocraft_engine::actions_cmds::ActionsExt; use std::collections::HashMap; use rustc_hash::FxHashMap; @@ -320,7 +321,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { push_row(&mut rows, &mut index, def); } // Recorded actions run on their own key (the user's assignment is an override). - for action in app.session.actions.list.actions() { + for action in app.session.actions().list.actions() { let id = crate::actions::shortcut_id(&action.name); push_row(&mut rows, &mut index, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()])); } @@ -726,7 +727,7 @@ fn dispatch_as(app: &mut PhotocraftApp, ctx: &egui::Context, command: &CommandRe let action = id.strip_prefix(crate::actions::SHORTCUT_PREFIX); let command_id = if action.is_some() { "actions.play" } else { id }; // A key saved for an action that was since deleted or renamed names no action. - let missing = action.is_some_and(|name| !app.session.actions.list.actions().iter().any(|a| a.name == name)); + let missing = action.is_some_and(|name| !app.session.actions().list.actions().iter().any(|a| a.name == name)); let outcome = if missing || !crate::menus::is_enabled(app, command_id) { let why = if missing { "The Action no longer exists".into() } else { disabled_reason(app, command_id) }; let template = "{label} is not available: {reason}"; diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index cd720d3002..de48359342 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -3,6 +3,7 @@ //! document. Every shortcut's command is fired into the dispatcher directly; one shortcut of each kind //! of key and route is pressed from the places focus usually is (#15678). +use photocraft_engine::actions_cmds::ActionsExt; use std::collections::HashSet; use craft::keymap::Chord; @@ -115,7 +116,7 @@ fn active_name(h: &Harness<'_, Box>) -> String { /// Adds the action `name` with `steps` to the action list. fn add_action(h: &mut Harness<'_, Box>, name: &str, steps: &[(&str, serde_json::Value)]) { let steps = steps.iter().map(|(command, params)| photocraft_engine::actions_cmds::ActionStep::new(*command, params.clone())).collect(); - h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new(name, steps)).unwrap(); + h.state_mut().session.actions_mut().list.push(photocraft_engine::actions_cmds::Action::new(name, steps)).unwrap(); } fn logged(h: &Harness<'_, Box>) -> Vec { @@ -740,7 +741,7 @@ fn fit_shortcut_records_and_f6_fits_the_resized_canvas() { press(&mut h, "Cmd+0"); h.state_mut().run("actions.stop", json!({})).unwrap(); assert_eq!( - h.state().session.actions.list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(), + h.state().session.actions().list.actions()[0].steps.iter().map(|s| s.command.as_str()).collect::>(), ["image.canvasSize", "view.fitOnScreen"] ); let item = crate::menus::menu_rows(h.state()).into_iter().find(|i| i.command.id == "view.fitOnScreen").unwrap(); @@ -767,7 +768,7 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() { press(&mut h, "F6"); assert_eq!(active_name(&h), "Nested overlay"); h.state_mut().run("actions.stop", json!({})).unwrap(); - let recorded: Vec<_> = h.state().session.actions.list.actions()[1].steps.iter().map(|s| (s.command.clone(), s.params.clone())).collect(); + let recorded: Vec<_> = h.state().session.actions().list.actions()[1].steps.iter().map(|s| (s.command.clone(), s.params.clone())).collect(); assert_eq!(recorded, [("actions.play".to_string(), json!({"action": "LivePrint 2R"}))]); } diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index cc9e525d10..0a235c97c5 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -2,6 +2,7 @@ //! rendering frames while a slow job runs, shows the status-bar progress and the blocking progress //! overlay, and Esc / Cancel leave the document unchanged. +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; diff --git a/crates/ui-egui/src/last_brush.rs b/crates/ui-egui/src/last_brush.rs index 45c101a7ae..b061a52df5 100644 --- a/crates/ui-egui/src/last_brush.rs +++ b/crates/ui-egui/src/last_brush.rs @@ -15,7 +15,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { } /// Restore the remembered brush at launch; stored tips load when the preset store attaches -/// (`Session::attach_preset_store`). +/// (`PresetStoreExt::attach_preset_store`). pub fn restore(app: &mut PhotocraftApp) { photocraft_engine::brush_cmds::restore_brush(&mut app.session); } diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index a9310693cb..9864d1aa71 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -2,6 +2,7 @@ //! pixels float and drop with the history steps Photoshop names, a moved selection snaps to guides and the document //! (not to its own start), the arrows nudge the outline, and the lock refusal of the Move tool and ⌘-drags. +use photocraft_engine::smartselect_cmds::SmartSelectExt; use crate::app::framework::BuildApp as _; use egui::{Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; @@ -95,7 +96,7 @@ fn object_selection_keeps_the_mode_from_the_mouse_press() { let doc = st.doc.clone(); let target = st.active_layer; let region = photocraft_engine::smartselect_cmds::find_object(&doc, target, false, 220.0, 150.0).expect("the red disc is detectable"); - h.state_mut().session.object_finder.insert(&doc, target, std::sync::Arc::new(region)); + h.state_mut().session.object_finder_mut().insert(&doc, target, std::sync::Arc::new(region)); if at_press.alt { h.state_mut().run("select.all", json!({})).unwrap(); } else { diff --git a/crates/ui-egui/src/menu_floor_trials.rs b/crates/ui-egui/src/menu_floor_trials.rs index fa053354c9..2c08def1dd 100644 --- a/crates/ui-egui/src/menu_floor_trials.rs +++ b/crates/ui-egui/src/menu_floor_trials.rs @@ -3,6 +3,7 @@ //! the menu model is built only when a fact it shows changed, never for a tool option or a button release, and the //! held model always equals a fresh build. +use photocraft_engine::presets::PresetsExt; use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_key_bytes}; use egui::{Event, Pos2, vec2}; use egui_kittest::Harness; @@ -23,7 +24,7 @@ fn harness(documents: usize, recent: usize, swatches: usize) -> H { for _ in 0..documents { s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); } - s.presets.edit(|presets| { + s.presets_mut().edit(|presets| { if let Some(group) = presets.swatches.first_mut() && let Some(entry) = group.entries.first().cloned() { diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 4456145246..766ea42003 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -4,6 +4,9 @@ //! Nothing here grows with the documents, presets, recent files or layers, so an idle frame keys the same few bytes //! whatever the model's size. +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; +use photocraft_engine::actions_cmds::ActionsExt; use std::sync::Arc; use craft::ui::contract::{MemoProps, Revision, Tracked}; @@ -209,7 +212,7 @@ impl<'a> RuleFacts<'a> { jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), - proofs: s.color.proofs_revision(), + proofs: s.color().proofs_revision(), image_assets: &s.file_menu.image_assets, slices_locked: s.file_menu.slices_locked, }, @@ -217,12 +220,12 @@ impl<'a> RuleFacts<'a> { clipboard: s.clipboard.revision(), style_clipboard: s.style_clipboard.revision(), path_clipboards: (s.path_fill_clipboard.is_some(), s.path_stroke_clipboard.is_some()), - presets: s.presets.revision(), + presets: s.presets().revision(), no_patterns: s.patterns.items.is_empty(), type_defaults: s.type_defaults.is_some(), measurement_log: s.analysis.log.is_empty(), mask_targeted: s.tools.mask_targeted, - actions: (s.actions.list.revision(), s.recording.target, s.recording.playing), + actions: (s.actions().list.revision(), s.recording.target, s.recording.playing), undo_label: crate::actions::library::edit_undo_label(app), plugins: photocraft_plugins::registry::revision(), }, diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 7831ae9382..44ea44dc8c 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use craft::menu::{LANGUAGE_COMMAND, THEME_COMMAND}; use super::invoke::{panel_alias, proof_preset, workspace_id}; @@ -165,7 +166,7 @@ pub(super) fn checked(app: &PhotocraftApp, id: &str) -> Option { } if id == "view.proofColors" || id == "view.gamutWarning" { let Some(d) = app.session.active() else { return Some(false) }; - let pv = app.session.color.proof(d.doc.id); + let pv = app.session.color().proof(d.doc.id); return Some(if id == "view.proofColors" { pv.enabled } else { pv.gamut_warning }); } if let Some(rest) = id.strip_prefix("window.workspace.") { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 4cff58749b..773eda0cf8 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use super::items::row; use super::*; use craft::menu::{THEME_COMMAND, ThemeChoice}; @@ -69,7 +70,7 @@ fn proofed(app: &mut PhotocraftApp) { invoke(app, &ctx, "view.proofSetup.workingCmyk", Value::Null).unwrap(); invoke(app, &ctx, "view.gamutWarning", json!({"on": true})).unwrap(); let doc = app.session.active().unwrap().doc.clone(); - let lut = app.session.color.canvas_lut(&doc, 9).unwrap().unwrap(); + let lut = app.session.color().canvas_lut(&doc, 9).unwrap().unwrap(); // Pure sRGB green is outside coated CMYK; mid grey is inside. let at = |r: usize, g: usize, b: usize| lut[(r + g * 9 + b * 81) * 4 + 3]; assert_eq!((at(0, 8, 0), at(4, 4, 4)), (255, 0)); diff --git a/crates/ui-egui/src/menus/view_cmds/fit_image_sticky_tests.rs b/crates/ui-egui/src/menus/view_cmds/fit_image_sticky_tests.rs index 8a61699089..bdbcbfc19c 100644 --- a/crates/ui-egui/src/menus/view_cmds/fit_image_sticky_tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/fit_image_sticky_tests.rs @@ -1,6 +1,7 @@ //! #13853: Fit Image opens with the width, height and Don't Enlarge it last ran with (OK, or a //! run without the dialog), not the document's size; Cancel stores nothing. +use photocraft_engine::prefs::SavedPrefsExt; use craft::ui::dialog::DialogId; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index ef4261412a..1bcdea35fc 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::dialogs::params_for; use super::*; use crate::menus::{invoke as menu, is_live, menu_rows, row}; @@ -428,7 +429,7 @@ fn batch_menu_starts_on_the_selected_actions_set_and_runs_its_action() { for (set, name, step) in [("A", "Retouch", "image.adjustments.invert"), ("B", "Turn", "image.imageRotation.90cw")] { let mut action = Action::new(name, vec![ActionStep::new(step, json!({}))]); action.set = Some(set.into()); - app.session.actions.list.push(action).unwrap(); + app.session.actions_mut().list.push(action).unwrap(); } app.ui.actions.panel.selected = Some(ActionSelection::Action(1)); let id = open_form(&mut app, &ctx, "file.automate.batch"); @@ -455,7 +456,7 @@ fn batch_menu_runs_the_action_chosen_in_the_form() { app.run("file.new", json!({"width": 2, "height": 1})).unwrap(); app.run("file.saveACopy", json!({"path": source.join("source.png").to_string_lossy()})).unwrap(); for (name, step) in [("Invert", "image.adjustments.invert"), ("RotateRGB", "image.imageRotation.90cw")] { - app.session.actions.list.push(Action::new(name, vec![ActionStep::new(step, json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new(name, vec![ActionStep::new(step, json!({}))])).unwrap(); } app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); let id = open_form(&mut app, &ctx, "file.automate.batch"); @@ -479,8 +480,8 @@ fn batch_menu_runs_the_action_chosen_in_the_form() { let id = open_form(&mut app, &ctx, "file.automate.batch"); set(&mut app, &ctx, id, "action", json!("RotateRGB")); set(&mut app, &ctx, id, "output", json!(cancelled.to_string_lossy())); - let rotate = app.session.actions.list.actions().iter().position(|action| action.name == "RotateRGB").unwrap(); - app.session.actions.list.delete_action(rotate).unwrap(); + let rotate = app.session.actions().list.actions().iter().position(|action| action.name == "RotateRGB").unwrap(); + app.session.actions_mut().list.delete_action(rotate).unwrap(); // The run's refusal reaches the user through the status bar and a notice, as a failed filter's does. confirm(&mut app, &ctx, id).unwrap(); assert!(app.ui.status_error && app.ui.status.contains("no action named"), "{}", app.ui.status); @@ -605,7 +606,7 @@ fn batch_dialogs_include_all_subfolders() { std::fs::create_dir_all(dir.join("in/sub")).unwrap(); let input = dir.join("in").to_string_lossy().into_owned(); app.run("file.saveACopy", json!({"path": dir.join("in/sub/a.png").to_string_lossy()})).unwrap(); - app.session.actions.list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap(); for (command, out) in [("file.automate.batch", "batch"), ("file.scripts.imageProcessor", "processed")] { let d = open_form(&mut app, &ctx, command); let shown = fields(&app, d); @@ -684,7 +685,7 @@ fn a_batch_that_fails_on_its_files_says_which_and_why() { app.run("file.saveACopy", json!({"path": dir.join("in").join(name).to_string_lossy()})).unwrap(); } // A step for a layer that only the recording document has. - app.session.actions.list.push(Action::new("Stale", vec![ActionStep::new("layer.setProps", json!({"layer": 424_242, "opacity": 50}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("Stale", vec![ActionStep::new("layer.setProps", json!({"layer": 424_242, "opacity": 50}))])).unwrap(); let d = open_form(&mut app, &ctx, "file.automate.batch"); set(&mut app, &ctx, d, "input", json!(dir.join("in").to_string_lossy())); set(&mut app, &ctx, d, "output", json!(dir.join("out").to_string_lossy())); diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index 80ae255718..164d91a5e7 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -5,6 +5,7 @@ //! of it; what a workspace captures beside its layout (shortcuts, menus, toolbar) is in //! `Preferences::workspace_extras` by workspace id. [`ShellUi`] is the serialisable shell state of `UiState`. +use photocraft_engine::color_cmds::ColorExt; use craft::behavior::dock::{NamedWorkspace, WorkspaceChrome, WorkspaceError, WorkspaceKeeps, WorkspaceSet}; use craft::keymap::{CommandRef, Mods}; use craft::ui::contract::{Bind, CommandSet as _}; @@ -380,7 +381,7 @@ fn open_extras(app: &mut PhotocraftApp) -> Result { fn open_preview32(app: &mut PhotocraftApp) -> Option> { let d = app.session.active()?; - let h = app.session.color.hdr.get(&d.doc.id).copied().unwrap_or_default(); + let h = app.session.color().hdr.get(&d.doc.id).copied().unwrap_or_default(); let method = if h.highlight_compression { "highlightCompression" } else { "exposureGamma" }; let fields = DialogFields::from_pairs([ ("method", FieldValue::Text(method.into())), @@ -624,7 +625,7 @@ mod tests { } crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); let d = app.session.active().unwrap().doc.id; - assert_eq!((app.session.color.hdr[&d].exposure, app.session.color.hdr[&d].gamma), (1.5, 1.5)); + assert_eq!((app.session.color().hdr[&d].exposure, app.session.color().hdr[&d].gamma), (1.5, 1.5)); // Highlight Compression disables the two ranges. menu(&mut app, PREVIEW32, &json!({})).expect("handled").unwrap(); diff --git a/crates/ui-egui/src/monitor_status.rs b/crates/ui-egui/src/monitor_status.rs index 1d988ee1c3..b035d0d89a 100644 --- a/crates/ui-egui/src/monitor_status.rs +++ b/crates/ui-egui/src/monitor_status.rs @@ -14,6 +14,7 @@ //! and a profile reassigned while PhotoCraft stays in front with no window moving practically //! doesn't happen; it is picked up at the next return to the front or Color Settings. +use photocraft_engine::color_cmds::ColorExt; use std::sync::mpsc::Receiver; use std::sync::{Arc, Mutex}; @@ -73,8 +74,8 @@ fn refresh_note(app: &PhotocraftApp) { /// A reading started before the shell existed (the desktop app starts one at launch and waits /// for it briefly so the first frames already use the right profile): applied when it arrives. pub fn pending(app: &mut PhotocraftApp, rx: Receiver) { - if app.session.color.displays.is_empty() { - app.session.color.monitor_detection = MonitorDetection::Pending; + if app.session.color().displays.is_empty() { + app.session.color_mut().monitor_detection = MonitorDetection::Pending; } app.monitors.pending = Some(rx); } @@ -115,8 +116,8 @@ fn poll_with_output_name(app: &mut PhotocraftApp, ctx: &egui::Context, output_na } } let main = view_display(app, ctx); - if main != app.session.color.main_display { - app.session.color.main_display = main; + if main != app.session.color().main_display { + app.session.color_mut().main_display = main; ctx.request_repaint(); } let focused = ctx.input(|i| i.focused) || std::mem::take(&mut app.monitors.window_focused); @@ -171,7 +172,7 @@ pub fn read_now(app: &mut PhotocraftApp) { /// The Color Settings dialog's line: the monitor profile in use for the main window, as it is /// now. pub fn note(app: &PhotocraftApp) -> String { - let st = app.session.color.monitor_status(); + let st = app.session.color().monitor_status(); let template = if st.display.is_some() { "Monitor profile in use on {display}: {profile}" } else { "Monitor profile in use: {profile}" }; let profile = profile_summary(&st); let mut note = crate::i18n::fmt(tl!(template), &[("display", st.display.as_deref().unwrap_or_default()), ("profile", &profile)]); @@ -196,7 +197,7 @@ fn profile_summary(st: &photocraft_engine::display_color::MonitorStatus) -> Stri /// When the last re-read failed and an earlier reading is shown: why. fn retained(app: &PhotocraftApp) -> Option { - match &app.session.color.monitor_detection { + match &app.session.color().monitor_detection { MonitorDetection::Retained { reason } => Some({ let template = "previous reading kept; the last re-read failed: {reason}"; crate::i18n::fmt(tl!(template), &[("reason", reason)]) @@ -218,10 +219,10 @@ fn start(app: &mut PhotocraftApp, now: f64) { /// management). Manual monitor profiles don't depend on the reading. A failed re-read keeps the /// previous reading and says so in the status. pub fn apply(app: &mut PhotocraftApp, r: Detection) { - if let Some(e) = app.session.color.set_displays(r) { + if let Some(e) = app.session.color_mut().set_displays(r) { log::warn!("re-reading the display profiles failed: {e}; keeping the previous ones"); } - let c = &app.session.color; + let c = app.session.color(); let fallbacks: Vec<(u32, String, String)> = if c.displays.is_empty() { let st = c.monitor_status(); match (st.source, st.reason, &st.detection) { @@ -277,7 +278,7 @@ fn display_for_view(app: &PhotocraftApp, ctx: &egui::Context) -> Option { if let Some(display) = root_output_display(app, ctx) { return display; } - display_at(&app.session.color.displays, window_frame(ctx)?) + display_at(&app.session.color().displays, window_frame(ctx)?) } #[cfg(target_os = "linux")] @@ -294,7 +295,7 @@ fn root_output_display(app: &PhotocraftApp, ctx: &egui::Context) -> Option bool { /// The window is on no display we know, or on one whose size differs from what was read. fn displays_changed(app: &PhotocraftApp, ctx: &egui::Context) -> bool { - let c = &app.session.color; + let c = app.session.color(); if c.displays.is_empty() || !matches!(c.monitor_detection, MonitorDetection::Found | MonitorDetection::Retained { .. }) { return false; } @@ -338,7 +339,7 @@ fn displays_changed(app: &PhotocraftApp, ctx: &egui::Context) -> bool { /// Help › System Info's lines: the monitor profile of each display. pub fn summary_lines(app: &PhotocraftApp) -> Vec { - let c = &app.session.color; + let c = app.session.color(); if c.displays.is_empty() { return vec![{ let template = "Monitor profile: {profile}"; @@ -438,13 +439,13 @@ mod tests { frame(&mut app, &ctx, 0.1, [100.0, 100.0], [1728.0, 1117.0], true); assert!(app.monitors.pending.is_none()); // On the built-in display (no profile here): sRGB, reported once. - assert_eq!(app.session.color.main_display, Some(1)); + assert_eq!(app.session.color().main_display, Some(1)); assert_eq!(app.ui.notices.len(), 1); assert!(app.ui.notices[0].lines[0].contains("Built-in Retina Display has no ICC profile")); // Moved to the external display: its profile, without a restart. frame(&mut app, &ctx, 0.2, [2000.0, -500.0], [3008.0, 1692.0], true); - assert_eq!(app.session.color.main_display, Some(4)); - assert_eq!(app.session.color.monitor().description, "Display P3"); + assert_eq!(app.session.color().main_display, Some(4)); + assert_eq!(app.session.color().monitor().description, "Display P3"); let lines = summary_lines(&app); assert_eq!(lines[1], "Monitor profile on ROG PG32UQX (main window): Apple_Display (auto)", "{lines:?}"); assert!(lines[0].starts_with("Monitor profile on Built-in Retina Display: sRGB"), "{lines:?}"); @@ -477,7 +478,7 @@ mod tests { fn displays_are_read_again_when_they_may_have_changed() { let mut app = app(); let ctx = app.ctx().clone(); - app.session.color.set_displays(Ok(displays(p3()))); + app.session.color_mut().set_displays(Ok(displays(p3()))); let reads = reader(&mut app, displays(p3())); let count = || reads.load(std::sync::atomic::Ordering::SeqCst); frame(&mut app, &ctx, 100.0, [100.0, 100.0], [1728.0, 1117.0], true); @@ -513,7 +514,7 @@ mod tests { // that applies its result; the reader doesn't wake the UI. let mut app = app(); let ctx = app.ctx().clone(); - app.session.color.set_displays(Ok(displays(None))); + app.session.color_mut().set_displays(Ok(displays(None))); let (count, readers) = manual_reader(&mut app); frame(&mut app, &ctx, 0.0, [100.0, 100.0], [1728.0, 1117.0], false); let wait = frame(&mut app, &ctx, 1.0, [100.0, 100.0], [1728.0, 1117.0], true); @@ -521,7 +522,7 @@ mod tests { assert!(wait <= std::time::Duration::from_millis(250), "next frame scheduled: {wait:?}"); readers.recv().unwrap().send(Ok(displays(p3()))).unwrap(); frame(&mut app, &ctx, 1.25, [100.0, 100.0], [1728.0, 1117.0], true); - assert_eq!(app.session.color.monitor().description, "Display P3"); + assert_eq!(app.session.color().monitor().description, "Display P3"); } /// One frame of a document window at `pos` with `focused` (its part of the shell is @@ -543,7 +544,7 @@ mod tests { let mut app = app(); // The main window is the app's own context; the document window is another window's. let (main, doc) = (app.ctx().clone(), egui::Context::default()); - app.session.color.set_displays(Ok(displays(p3()))); + app.session.color_mut().set_displays(Ok(displays(p3()))); let reads = reader(&mut app, displays(p3())); frame(&mut app, &main, 100.0, [100.0, 100.0], [1728.0, 1117.0], true); // A new egui context asks for a few frames of its own first. @@ -563,7 +564,7 @@ mod tests { let mut app = app(); // The main window is the app's own context; the document window is another window's. let (main, doc) = (app.ctx().clone(), egui::Context::default()); - app.session.color.set_displays(Ok(displays(p3()))); + app.session.color_mut().set_displays(Ok(displays(p3()))); let reads = reader(&mut app, displays(p3())); let count = || reads.load(std::sync::atomic::Ordering::SeqCst); // Working in the document window: PhotoCraft is in front, no reading. @@ -596,8 +597,8 @@ mod tests { // r1 finding 4: the dialog's line follows a reading that arrives while it is open. let mut app = app(); let ctx = app.ctx().clone(); - app.session.color.set_displays(Ok(displays(None))); - app.session.color.main_display = Some(1); + app.session.color_mut().set_displays(Ok(displays(None))); + app.session.color_mut().main_display = Some(1); crate::prefs_ui::invoke(&mut app, &ctx, "edit.colorSettings", &serde_json::json!({})).unwrap().unwrap(); assert!(!app.framework.dialogs.is_empty(), "Color Settings is open"); let cell = note_cell(&app); @@ -605,7 +606,7 @@ mod tests { assert!(shown().contains("on Built-in Retina Display: sRGB") && shown().contains("fallback"), "{}", shown()); // A reading that arrives while the dialog is open changes the line the dialog draws. apply(&mut app, Ok(displays(p3()))); - app.session.color.main_display = Some(4); + app.session.color_mut().main_display = Some(4); read_now(&mut app); assert!(!app.framework.dialogs.is_empty(), "the dialog stays open"); assert_eq!(shown(), "Monitor profile in use on ROG PG32UQX: Apple_Display (auto)"); @@ -634,7 +635,7 @@ mod tests { apply(&mut app, Ok(displays(p3()))); assert!(app.ui.notices.is_empty()); apply(&mut app, Err("osascript failed".into())); - assert_eq!(app.session.color.displays.len(), 2); + assert_eq!(app.session.color().displays.len(), 2); assert!(app.ui.notices.is_empty()); app.run("edit.colorSettings", serde_json::json!({"monitorProfile": "srgb"})).unwrap(); apply(&mut app, Ok(displays(Some(Arc::new(vec![0u8; 200]))))); @@ -646,7 +647,7 @@ mod tests { #[test] fn root_window_uses_winit_monitor_name_to_select_its_profile() { let mut app = app(); - app.session.color.set_displays(Ok(vec![ + app.session.color_mut().set_displays(Ok(vec![ Display { id: 1, name: "DP-1".into(), frame: [0.0, 0.0, 1920.0, 1080.0], profile_name: None, icc: None }, Display { id: 2, name: "HDMI-1".into(), frame: [1920.0, 0.0, 1920.0, 1080.0], profile_name: None, icc: None }, ])); diff --git a/crates/ui-egui/src/new_doc_remember_tests.rs b/crates/ui-egui/src/new_doc_remember_tests.rs index e26fda2a91..54e9068dd2 100644 --- a/crates/ui-egui/src/new_doc_remember_tests.rs +++ b/crates/ui-egui/src/new_doc_remember_tests.rs @@ -2,6 +2,8 @@ //! clipboard image's size still taking priority. Also the hosted dialog's test harness, which the //! New Document tests share. +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::presets::PresetsExt; use craft::behavior::PixelSize; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{BackgroundContents, BitDepth, ColorMode, DocumentOptions}; @@ -123,7 +125,7 @@ fn a_corrupt_remembered_value_is_ignored() { let kept = craft::ui::runtime::memory::saved_value::>(h.state().ctx(), &crate::new_doc_ui::LAST_CREATED); assert_eq!(kept.as_ref().map(|o| o.size), Some(PixelSize::new(800, 600))); let documents = h.state().session.documents().len(); - let recent = h.state().session.presets.recent_documents.clone(); + let recent = h.state().session.presets().recent_documents.clone(); // A Create the engine refuses (an unknown profile) stores nothing and adds no recent entry. create(&mut h, |o| { o.size = PixelSize::new(321, 123); @@ -131,7 +133,7 @@ fn a_corrupt_remembered_value_is_ignored() { }); assert_eq!(h.state().session.documents().len(), documents, "no document was made"); assert_eq!(craft::ui::runtime::memory::saved_value::>(h.state().ctx(), &crate::new_doc_ui::LAST_CREATED), kept, "unchanged"); - assert_eq!(h.state().session.presets.recent_documents, recent); + assert_eq!(h.state().session.presets().recent_documents, recent); } /// #3131: File › New › Recent lists the documents created with the dialog, newest first, and @@ -155,14 +157,14 @@ fn created_documents_fill_the_recent_category() { o.background = BackgroundContents::White; o.unit = UnitKind::Pixels; }); - let recent = h.state().session.presets.recent_documents.clone(); + let recent = h.state().session.presets().recent_documents.clone(); assert_eq!(recent.iter().map(|r| (r.width, r.unit.as_str())).collect::>(), [(1920, "px"), (640, "in")]); // The settings are kept with the preferences. let mut restarted = photocraft_engine::Session::new(); restarted.load_prefs_json(&h.state().session.prefs_to_json()).unwrap(); - assert_eq!(restarted.presets.recent_documents, recent); + assert_eq!(restarted.presets().recent_documents, recent); // The list the dialog opens with (its bound `recent`) holds every setting of each entry. - let listed: Vec = restarted.presets.recent_documents.iter().map(crate::new_doc_ui::to_options).collect(); + let listed: Vec = restarted.presets().recent_documents.iter().map(crate::new_doc_ui::to_options).collect(); assert_eq!( (listed[1].size, listed[1].unit, listed[1].color_mode, listed[1].depth), (PixelSize::new(640, 480), UnitKind::Inches, ColorMode::Cmyk, BitDepth::Sixteen) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 777bbca655..d07bdb80ed 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -6,6 +6,7 @@ //! keeps the panel's state, maps its events to engine commands ([`apply_actions_events`]) and holds //! the selection rules Batch, Droplet and Play share. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::{ ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, ActionsSettings, DIALOG_COLUMN, INCLUDE_COLUMN, }; @@ -58,7 +59,7 @@ mod stop_tests; mod tests; /// The Actions panel's state: the framework panel's selection, expansion and settings. The action -/// list itself is [`photocraft_engine::Session::actions`]. Only Button Mode and the collapsed sets +/// list itself is [`ActionsExt::actions`](photocraft_engine::actions_cmds::ActionsExt::actions). Only Button Mode and the collapsed sets /// are saved (see [`saved`]). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(from = "saved::Saved", into = "saved::Saved")] @@ -111,7 +112,7 @@ pub(crate) fn label_of(id: &str) -> String { /// The action a selected row belongs to: the action itself or the action of a selected step. fn selected_action_index(app: &PhotocraftApp) -> Option { match app.ui.actions.panel.selected.as_ref()? { - ActionSelection::Action(i) | ActionSelection::Step(i, _) => Some(*i).filter(|i| *i < app.session.actions.list.actions().len()), + ActionSelection::Action(i) | ActionSelection::Step(i, _) => Some(*i).filter(|i| *i < app.session.actions().list.actions().len()), _ => None, } } @@ -119,7 +120,7 @@ fn selected_action_index(app: &PhotocraftApp) -> Option { /// The selected action, else the first action of the selected set (Batch and Create Droplet start /// on the panel's selection), else the first one. pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> { - let list = &app.session.actions.list; + let list = &app.session.actions().list; selected_action_index(app) .and_then(|i| list.action(i)) .or_else(|| selected_set_actions(app).first().and_then(|i| list.action(*i))) @@ -131,7 +132,7 @@ pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> { /// one name in two sets, so the dialog sends the set too and the command picks that set's action. pub fn action_form_choices(app: &PhotocraftApp) -> (Vec, Vec) { let (mut names, mut sets) = (Vec::new(), Vec::new()); - for action in app.session.actions.list.actions() { + for action in app.session.actions().list.actions() { if !names.contains(&action.name) { names.push(action.name.clone()); } @@ -145,14 +146,14 @@ pub fn action_form_choices(app: &PhotocraftApp) -> (Vec, Vec) { /// The selected set folder, if it still exists. pub(crate) fn selected_set(app: &PhotocraftApp) -> Option<&str> { match app.ui.actions.panel.selected.as_ref()? { - ActionSelection::Set(name) if app.session.actions.list.sets().contains(&name.as_str()) => Some(name), + ActionSelection::Set(name) if app.session.actions().list.sets().contains(&name.as_str()) => Some(name), _ => None, } } /// The actions of `set`, in list order (empty for an empty or unknown set). fn set_actions(app: &PhotocraftApp, set: &str) -> Vec { - let list = &app.session.actions.list; + let list = &app.session.actions().list; (0..list.actions().len()).filter(|i| list.set_of(*i) == Some(set)).collect() } @@ -175,7 +176,7 @@ pub(crate) fn playback_targets(app: &PhotocraftApp) -> Vec { /// Index of the playback target. Photoshop's Play button uses the first action when /// the panel has actions but none of its rows is selected. fn playback_selection(app: &PhotocraftApp) -> Option { - if app.session.actions.list.actions().is_empty() { None } else { Some(selected_action_index(app).unwrap_or(0)) } + if app.session.actions().list.actions().is_empty() { None } else { Some(selected_action_index(app).unwrap_or(0)) } } /// Steps in the `[[id, params], …]` shape batch and droplets already accept, without the @@ -230,7 +231,7 @@ pub(crate) fn library_changed(app: &mut PhotocraftApp) { /// The set New Action records into: the selected action's, else the selected set folder's. pub(crate) fn new_action_set(app: &PhotocraftApp) -> Option { match selected_action_index(app) { - Some(i) => app.session.actions.list.set_of(i).map(str::to_owned), + Some(i) => app.session.actions().list.set_of(i).map(str::to_owned), None => selected_set(app).map(str::to_owned), } } @@ -247,7 +248,7 @@ pub(crate) fn begin_recording(app: &mut PhotocraftApp, into: Option) { }; let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; - let Some(action) = app.session.actions.list.action(i) else { return }; + let Some(action) = app.session.actions().list.action(i) else { return }; let (name, set) = (action.name.clone(), action.set.clone()); let panel = &mut app.ui.actions.panel; panel.selected = Some(ActionSelection::Action(i)); @@ -261,11 +262,11 @@ pub(crate) fn begin_recording(app: &mut PhotocraftApp, into: Option) { /// Duplicate one action or step and select the copy. A copied action is open when its source is; /// the action of a copied step opens. fn duplicate_row(app: &mut PhotocraftApp, action: usize, step: Option) -> Result { - let source_open = app.session.actions.list.action(action).is_some_and(|a| app.ui.actions.panel.expanded.contains(&a.name)); + let source_open = app.session.actions().list.action(action).is_some_and(|a| app.ui.actions.panel.expanded.contains(&a.name)); let result = app.run("actions.duplicate", json!({"action": action, "step": step}))?; let index = result["index"].as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("the copy has no action index")?; let copied_step = result.get("step").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - let name = app.session.actions.list.action(index).map(|a| a.name.clone()); + let name = app.session.actions().list.action(index).map(|a| a.name.clone()); let panel = &mut app.ui.actions.panel; panel.selected = Some(match copied_step { Some(s) => ActionSelection::Step(index, s), @@ -301,7 +302,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let rename = app.ui.actions.rename.take(); let paced = playback::pending(app); let host = PhotoActions::new(&app.session, paced); - let mut widget = ActionsPanel::new(&mut app.ui.actions.panel, &app.session.actions.list).host(&host); + let mut widget = ActionsPanel::new(&mut app.ui.actions.panel, &app.session.actions().list).host(&host); if let Some(action) = rename { widget = widget.start_rename(action); } @@ -339,8 +340,8 @@ fn play_and_report(app: &mut PhotocraftApp, targets: &[usize], from: usize) { /// The action and the step position after the selected row, for inserting a step. fn insert_target(app: &PhotocraftApp) -> Result<(usize, Option), String> { match app.ui.actions.panel.selected.as_ref() { - Some(ActionSelection::Action(i)) if *i < app.session.actions.list.actions().len() => Ok((*i, None)), - Some(ActionSelection::Step(i, s)) if *i < app.session.actions.list.actions().len() => Ok((*i, Some(s.saturating_add(1)))), + Some(ActionSelection::Action(i)) if *i < app.session.actions().list.actions().len() => Ok((*i, None)), + Some(ActionSelection::Step(i, s)) if *i < app.session.actions().list.actions().len() => Ok((*i, Some(s.saturating_add(1)))), _ => Err(tl!("Select an action first.").to_string()), } } @@ -394,7 +395,7 @@ fn apply_event(app: &mut PhotocraftApp, event: ActionsEvent) -> Result<(), Strin app.run("actions.setColor", json!({"action": action, "color": color.name()}))?; } ActionsEvent::AssignShortcut { action, choice, .. } => { - let name = app.session.actions.list.action(action).map(|a| a.name.clone()).ok_or("no such action")?; + let name = app.session.actions().list.action(action).map(|a| a.name.clone()).ok_or("no such action")?; let key = choice.map_or_else(String::new, |c| photocraft_engine::atn_cmds::function_key_name(u16::from(c.key), c.shift, c.command)); assign_shortcut(app, &name, &key)?; } @@ -427,7 +428,7 @@ fn reorder(app: &mut PhotocraftApp, row: ActionSelection, place: ActionPlace) -> match (row, place) { (ActionSelection::Action(action), ActionPlace::Action { index, set, .. }) => { app.run("actions.move", json!({"action": action, "to": index}))?; - let current = app.session.actions.list.set_of(index).map(str::to_owned); + let current = app.session.actions().list.set_of(index).map(str::to_owned); if current != set { app.run("actions.assignSet", json!({"action": index, "set": set}))?; } diff --git a/crates/ui-egui/src/panels/actions/dialogs.rs b/crates/ui-egui/src/panels/actions/dialogs.rs index bf963413b7..d834c57bcd 100644 --- a/crates/ui-egui/src/panels/actions/dialogs.rs +++ b/crates/ui-egui/src/panels/actions/dialogs.rs @@ -1,5 +1,6 @@ //! New Set…, Insert Stop… and the Stop message: the Actions panel's own dialogs. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::ActionSelection; use craft::ui::contract::Bind; use craft::ui::dialog::{DialogId, DialogResult, PromptAnswer, PromptChoice, StandardPrompt}; @@ -58,14 +59,14 @@ fn selected_action(app: &PhotocraftApp) -> Option<(usize, Option)> { ActionSelection::Step(action, step) => (*action, Some(*step)), _ => return None, }; - app.session.actions.list.action(action).map(|_| (action, step)) + app.session.actions().list.action(action).map(|_| (action, step)) } /// Insert Stop…: a message step after the selected step, or at the end of the selected action (pending steps of a /// recording count). The action and the place are captured here; the dialog shows neither. pub(super) fn insert_stop_dialog(app: &mut PhotocraftApp) -> Result { let (action, step) = selected_action(app).ok_or_else(|| tl!("Select an action first").to_string())?; - let len = app.session.actions.list.step_count(action) + actions_cmds::pending_steps(&app.session, action).count(); + let len = app.session.actions().list.step_count(action) + actions_cmds::pending_steps(&app.session, action).count(); let at = step.map_or(len, |step| (step + 1).min(len)); let id = params::open_param(app, INSERT_STOP, DialogFields::new(), json!({"action": action, "at": at}), |fields: &mut DialogFields| { let rows = vec![ @@ -96,7 +97,7 @@ fn run_insert_stop(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamR Ok(inserted) => { let Some(step) = inserted["step"].as_u64().and_then(|step| usize::try_from(step).ok()) else { return }; app.ui.actions.panel.selected = Some(ActionSelection::Step(action, step)); - if let Some(held) = app.session.actions.list.action(action) { + if let Some(held) = app.session.actions().list.action(action) { app.ui.actions.panel.expanded.insert(held.name.clone()); } } diff --git a/crates/ui-egui/src/panels/actions/drag_drop_tests.rs b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs index e8c850a783..4a9470d636 100644 --- a/crates/ui-egui/src/panels/actions/drag_drop_tests.rs +++ b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs @@ -1,22 +1,23 @@ //! #12373: an Actions panel row dropped on the trash is deleted, on Create new action duplicated. //! The panel reports the drop as `Delete` or `Duplicate`; these tests run those events. +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::automation::actions::ActionStep; fn names(app: &PhotocraftApp) -> Vec { - app.session.actions.list.actions().iter().map(|a| a.name.clone()).collect() + app.session.actions().list.actions().iter().map(|a| a.name.clone()).collect() } fn steps(app: &PhotocraftApp, action: usize) -> Vec { - app.session.actions.list.action(action).unwrap().steps.iter().map(|s| s.command.clone()).collect() + app.session.actions().list.action(action).unwrap().steps.iter().map(|s| s.command.clone()).collect() } fn app() -> Box { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let first = ["view.zoomOut", "view.fitOnScreen", "view.actualPixels"].map(|id| ActionStep::new(id, json!({}))).to_vec(); - app.session.actions.list.push(Action { name: "First".into(), steps: first, ..Default::default() }).unwrap(); + app.session.actions_mut().list.push(Action { name: "First".into(), steps: first, ..Default::default() }).unwrap(); let second = Action { name: "Second".into(), steps: vec![ActionStep::new("view.zoomIn", json!({}))], ..Default::default() }; - app.session.actions.list.push(second).unwrap(); + app.session.actions_mut().list.push(second).unwrap(); app } diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index a10935559e..e21f53ec38 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -1,5 +1,6 @@ //! Load Actions… and Save Actions…: the `.atn` file dialogs of the Actions panel. +use photocraft_engine::actions_cmds::ActionsExt; use serde_json::{Value, json}; use craft::host::{PickRequest, Picked}; @@ -42,7 +43,7 @@ pub(super) fn load_source(app: &mut PhotocraftApp, name: &str, params: Value) -> }; // Show what arrived: select the first loaded action, expanded. let first = r["actions"][0].as_str().and_then(|first| { - let list = &app.session.actions.list; + let list = &app.session.actions().list; list.actions().iter().position(|a| a.name == first).map(|i| (i, first.to_string())) }); if let Some((i, first)) = first { diff --git a/crates/ui-egui/src/panels/actions/files_tests.rs b/crates/ui-egui/src/panels/actions/files_tests.rs index a13bcdd763..6705f0583d 100644 --- a/crates/ui-egui/src/panels/actions/files_tests.rs +++ b/crates/ui-egui/src/panels/actions/files_tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use std::sync::Arc; use craft::host::{PickKind, Picked, ScriptedFiles}; @@ -29,7 +30,7 @@ fn settle(app: &mut PhotocraftApp) { } fn names(app: &PhotocraftApp) -> Vec<&str> { - app.session.actions.list.actions().iter().map(|a| a.name.as_str()).collect() + app.session.actions().list.actions().iter().map(|a| a.name.as_str()).collect() } /// The file names the Save requests of `files` suggested. @@ -139,7 +140,7 @@ fn bulk_load_keeps_cancel_empty_and_single_file_behavior() { for answer in [Picked::Cancelled, Picked::Paths(Vec::new()), Picked::Contents(Vec::new())] { let fake = Arc::new(ScriptedFiles::answering([answer])); let mut app = super::runner_tests::disk_app(fake); - app.session.actions.list.new_action("Existing", None).unwrap(); + app.session.actions_mut().list.new_action("Existing", None).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); app.ui.status = "Unchanged".into(); files::load_dialog(&mut app).unwrap(); @@ -152,7 +153,7 @@ fn bulk_load_keeps_cancel_empty_and_single_file_behavior() { let mut app = super::runner_tests::disk_app(fake); files::load_dialog(&mut app).unwrap(); settle(&mut app); - assert_eq!(app.session.actions.list.actions()[0].name, "One"); + assert_eq!(app.session.actions().list.actions()[0].name, "One"); assert!(app.ui.status.contains("single.atn")); assert!(!app.ui.status_error); } @@ -184,7 +185,7 @@ fn save_actions_with_a_set_selected_saves_that_set() { let mut app = super::runner_tests::disk_app(fake.clone()); app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); for (name, set) in [("Sharpen", "Retouch"), ("Resize", "Web")] { - app.session.actions.list.new_action(name, Some(set.into())).unwrap(); + app.session.actions_mut().list.new_action(name, Some(set.into())).unwrap(); } app.ui.actions.panel.selected = Some(ActionSelection::Set("Web".into())); files::save_dialog(&mut app, None).unwrap(); @@ -199,7 +200,7 @@ fn save_actions_with_a_set_selected_saves_that_set() { fn save_actions_suggests_a_file_name_without_path_characters() { let set = "Web/Print\\Mail: v2"; let (mut app, files) = empty_set_app(set); - app.session.actions.list.new_action("Loose", None).unwrap(); + app.session.actions_mut().list.new_action("Loose", None).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Set(set.into())); files::save_dialog(&mut app, None).unwrap(); settle(&mut app); @@ -243,5 +244,5 @@ fn bulk_load_summary_counts_unsupported_steps_of_surviving_sets() { assert!(!app.ui.status_error, "{status}"); // Both sets stay loaded: the unsupported step is counted for one that is in the panel. assert_eq!(names(&app), ["A", "B"]); - assert!(app.session.actions.list.actions()[0].steps.iter().any(|step| step.command == "actions.photoshopStep")); + assert!(app.session.actions().list.actions()[0].steps.iter().any(|step| step.command == "actions.photoshopStep")); } diff --git a/crates/ui-egui/src/panels/actions/library.rs b/crates/ui-egui/src/panels/actions/library.rs index 5caff25cdb..3f93cc602a 100644 --- a/crates/ui-egui/src/panels/actions/library.rs +++ b/crates/ui-egui/src/panels/actions/library.rs @@ -6,6 +6,7 @@ //! OK runs only while the list is at the revision it was asked at, and the command must pass both //! the authorization it was asked under and the current one. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::{ActionsWords, LibraryPrompt}; use craft::host::{PickRequest, Picked}; use craft::ui::dialog::{PromptAnswer, PromptChoice}; @@ -36,7 +37,7 @@ struct Asked { impl Asked { fn now(app: &PhotocraftApp) -> Self { let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }); - Asked { revision: app.session.actions.list.revision(), gate, automated: app.automation_input || gate.is_some() } + Asked { revision: app.session.actions().list.revision(), gate, automated: app.automation_input || gate.is_some() } } /// The asking authorization and the current one both allow `command` with `params`. @@ -110,7 +111,7 @@ pub(super) fn replace(app: &mut PhotocraftApp) -> Result { } app.ask_file(request, move |app, picked| { idle(app, REPLACE)?; - if app.session.actions.list.revision() != asked.revision { + if app.session.actions().list.revision() != asked.revision { return Err(tl!("The actions changed. Request Replace Actions again.").into()); } let (name, bytes, path) = match picked { @@ -167,7 +168,7 @@ pub(crate) fn answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut fn confirm(app: &mut PhotocraftApp, held: Held, append: bool) -> Result { let command = command(&held.prompt); idle(app, command)?; - if app.session.actions.list.revision() != held.asked.revision { + if app.session.actions().list.revision() != held.asked.revision { return Err(tl!("The Actions library changed. Choose the command again.").into()); } let params = match (&held.prompt, held.data) { diff --git a/crates/ui-egui/src/panels/actions/library_tests.rs b/crates/ui-egui/src/panels/actions/library_tests.rs index 618f874ea9..c4853337ab 100644 --- a/crates/ui-egui/src/panels/actions/library_tests.rs +++ b/crates/ui-egui/src/panels/actions/library_tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use std::cell::Cell; use std::rc::Rc; use std::sync::Arc; @@ -16,7 +17,7 @@ fn new_app() -> Box { } fn sets(app: &PhotocraftApp) -> Vec<&str> { - app.session.actions.list.sets() + app.session.actions().list.sets() } /// The panel menu's `event`, then the question it opened. @@ -90,7 +91,7 @@ fn replace_holds_the_read_file_until_ok() { assert_eq!(sets(&app), ["Original"]); crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); assert_eq!(sets(&app), ["Replacement"]); - assert_eq!(app.session.actions.list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["Invert"]); + assert_eq!(app.session.actions().list.actions().iter().map(|a| a.name.as_str()).collect::>(), ["Invert"]); } /// The chosen path and the bytes read need the automation policy, and the bytes need it again on OK. diff --git a/crates/ui-egui/src/panels/actions/menu.rs b/crates/ui-egui/src/panels/actions/menu.rs index f22bb2e749..bca66d3091 100644 --- a/crates/ui-egui/src/panels/actions/menu.rs +++ b/crates/ui-egui/src/panels/actions/menu.rs @@ -1,5 +1,6 @@ //! The Actions panel's menu: the rows the app offers, their states and the commands they fire. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandRef, CommandSet as _, CommandState}; @@ -31,7 +32,7 @@ pub(crate) fn panel_rows(app: &PhotocraftApp) -> Vec { /// menu does not show. pub(crate) fn states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { let facts = facts(app); - let (panel, list) = (&app.ui.actions.panel, &app.session.actions.list); + let (panel, list) = (&app.ui.actions.panel, &app.session.actions().list); // Load Actions… is the one library row the framework leaves always on. The app's own // `actions.load` refuses while a recording or a paced playback holds the library (a load would // replace the set the recording writes into), and the reference application greys the row @@ -67,7 +68,7 @@ struct StatesFacts<'a> { pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { let menu = facts(app); let facts = StatesFacts { - list: app.session.actions.list.revision(), + list: app.session.actions().list.revision(), recording: menu.recording, path_selected: menu.path_selected, waiting: menu.waiting, @@ -86,7 +87,7 @@ pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: return true; } let facts = facts(app); - if let Some(ActionsMenuAction::Event(event)) = command.run(&mut app.ui.actions.panel, &app.session.actions.list, facts) { + if let Some(ActionsMenuAction::Event(event)) = command.run(&mut app.ui.actions.panel, &app.session.actions().list, facts) { super::apply_actions_events(app, vec![event]); } true diff --git a/crates/ui-egui/src/panels/actions/menu_item.rs b/crates/ui-egui/src/panels/actions/menu_item.rs index 97ed9f4027..38a7262912 100644 --- a/crates/ui-egui/src/panels/actions/menu_item.rs +++ b/crates/ui-egui/src/panels/actions/menu_item.rs @@ -1,4 +1,5 @@ //! Choose an existing mapped menu event without borrowing current command settings. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::ActionSelection; use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; @@ -35,7 +36,7 @@ pub(super) fn open(app: &mut PhotocraftApp, action: usize, at: Option) -> return Err(tl!("Confirm or cancel the pending menu item first.").to_string()); } app.held_insert_menu = None; - if app.session.actions.list.action(action).is_none() { + if app.session.actions().list.action(action).is_none() { return Err(tl!("Select an action first.").to_string()); } let target = json!({"action": action, "at": at}); @@ -50,7 +51,7 @@ pub(super) fn open(app: &mut PhotocraftApp, action: usize, at: Option) -> let rows = vec![Param::new("id", tl!("Command"), ParamKind::choice(options.clone(), Some("image.imageSize".into()))).searchable()]; ParamDialog::command(KEY, tl!("Insert Menu Item"), rows).values(Bind::bound(fields)) }); - app.held_insert_menu = Some(Held { dialog, revision: app.session.actions.list.revision(), target, gate, automated }); + app.held_insert_menu = Some(Held { dialog, revision: app.session.actions().list.revision(), target, gate, automated }); Ok(json!({"dialog": dialog.value()})) } @@ -63,7 +64,7 @@ fn vet(app: &PhotocraftApp, result: &ParamResult) -> Result { .as_ref() .filter(|held| held.dialog == result.id && result.key == KEY) .ok_or_else(|| tl!("No menu item belongs to this chooser.").to_string())?; - if held.revision != app.session.actions.list.revision() { + if held.revision != app.session.actions().list.revision() { return Err(tl!("The action or insertion command changed. Request Insert Menu Item again.").to_string()); } let mut params = held.target.clone(); diff --git a/crates/ui-egui/src/panels/actions/menu_tests.rs b/crates/ui-egui/src/panels/actions/menu_tests.rs index 10cf440bb4..a9b9cc3844 100644 --- a/crates/ui-egui/src/panels/actions/menu_tests.rs +++ b/crates/ui-egui/src/panels/actions/menu_tests.rs @@ -1,4 +1,5 @@ //! The panel menu's rows and states, and the New Set… and Insert Stop… dialogs they open. +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::automation::ui::actions::{ActionSelection, ActionsPanelCommands as C}; use craft::ui::dialog::DialogId; @@ -84,7 +85,7 @@ fn the_panel_menu_offers_the_hosts_rows_with_the_apps_state() { assert!(enabled(&app, C::Save)); // Insert Path: on only when the selected path is a saved path. - app.session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); app.ui.selected_path = Some("Curve".into()); assert!(!enabled(&app, C::InsertPath), "no path of that name"); @@ -116,7 +117,7 @@ fn the_panel_menu_offers_the_hosts_rows_with_the_apps_state() { // Play with a selected set plays the set through the one event mapping. let mut member = Action::new("Member", vec![ActionStep::new("layer.new.layer", json!({"name": "FromSet"}))]); member.set = Some("Group".into()); - app.session.actions.list.push(member).unwrap(); + app.session.actions_mut().list.push(member).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Set("Group".into())); app.run("actions.setPlayback", json!({"performance": "accelerated"})).unwrap(); fire(&mut app, C::Play); @@ -130,7 +131,7 @@ fn the_panel_menu_offers_the_hosts_rows_with_the_apps_state() { #[test] fn load_actions_row_greys_while_a_recording_or_playback_holds_the_library() { let mut app = app(); - app.session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); // Idle: every library row is on. assert!(enabled(&app, C::Load), "no recording and no playback: the row is on"); assert!(enabled(&app, C::Save), "an action to save"); @@ -167,14 +168,14 @@ fn new_set_names_the_first_free_set_and_new_action_records_into_it() { assert!(!app.dialog_open()); fire(&mut app, C::NewAction); app.run("actions.stop", json!({})).unwrap(); - let recorded = app.session.actions.list.actions().last().expect("New Action made an action"); + let recorded = app.session.actions().list.actions().last().expect("New Action made an action"); assert_eq!(recorded.set.as_deref(), Some("Web")); } #[test] fn insert_stop_adds_a_stop_after_the_selected_step() { let mut app = app(); - app.session.actions.list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("A", vec![ActionStep::new("select.all", json!({})), ActionStep::new("select.inverse", json!({}))])).unwrap(); fire(&mut app, C::InsertStop); assert!(!app.dialog_open(), "Insert Stop… needs a selected action"); app.ui.actions.panel.selected = Some(ActionSelection::Step(0, 0)); @@ -183,7 +184,7 @@ fn insert_stop_adds_a_stop_after_the_selected_step() { set(&mut app, id, "message", json!("Check the mask")); set(&mut app, id, "allowContinue", json!(true)); ok(&mut app, id); - let action = app.session.actions.list.action(0).unwrap(); + let action = app.session.actions().list.action(0).unwrap(); assert_eq!(action.steps[1], ActionStep::new(photocraft_engine::atn_cmds::STOP_MESSAGE, json!({"message": "Check the mask", "allowContinue": true}))); assert!(action.dialogs.contains(&1), "an inserted Stop has its dialog toggle on"); assert_eq!(app.ui.actions.panel.selected, Some(ActionSelection::Step(0, 1))); @@ -194,7 +195,7 @@ fn insert_stop_adds_a_stop_after_the_selected_step() { let id = top_dialog(&app); set(&mut app, id, "message", json!("Last")); ok(&mut app, id); - let steps = &app.session.actions.list.action(0).unwrap().steps; + let steps = &app.session.actions().list.action(0).unwrap().steps; assert_eq!(steps.len(), 4); assert_eq!(steps[3].params["message"], "Last"); assert_eq!(app.ui.actions.panel.selected, Some(ActionSelection::Step(0, 3))); @@ -203,5 +204,5 @@ fn insert_stop_adds_a_stop_after_the_selected_step() { let id = top_dialog(&app); let app_ctx = app.ctx().clone(); crate::dialogs::cancel(&mut app, &app_ctx, id).unwrap(); - assert_eq!(app.session.actions.list.action(0).unwrap().steps.len(), 4); + assert_eq!(app.session.actions().list.action(0).unwrap().steps.len(), 4); } diff --git a/crates/ui-egui/src/panels/actions/panel_menu_tests.rs b/crates/ui-egui/src/panels/actions/panel_menu_tests.rs index 0715dcf605..e15ed52aa0 100644 --- a/crates/ui-egui/src/panels/actions/panel_menu_tests.rs +++ b/crates/ui-egui/src/panels/actions/panel_menu_tests.rs @@ -1,6 +1,7 @@ //! Real panel controls compose the menu-item commands with consent and retained selection. These trials read the //! dialog host (`app.framework`), so they live in the crate; the ones that use only the public API stay in //! `tests/it/actions_panel_menu.rs`. +use photocraft_engine::actions_cmds::ActionsExt; use std::sync::atomic::{AtomicUsize, Ordering}; use craft::automation::ui::actions::{ActionSelection, ActionsPanelCommands}; @@ -22,7 +23,7 @@ fn harness() -> Harness<'static, Box> { app.run("file.new", json!({"width":16,"height":12})).unwrap(); let mut a = Action::new("A", vec![]); a.set = Some("S".into()); - app.session.actions.list.push(a).unwrap(); + app.session.actions_mut().list.push(a).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); app.ui.actions.panel.expanded.insert("A".into()); let mut h = @@ -93,7 +94,7 @@ fn cancel(h: &mut Harness<'static, Box>, id: DialogId) { /// The steps of action `A`. fn steps(app: &PhotocraftApp) -> Vec { - app.session.actions.list.action(0).unwrap().steps.clone() + app.session.actions().list.action(0).unwrap().steps.clone() } /// Menu insertion uses an actual chooser and never samples or executes current command settings. @@ -121,7 +122,7 @@ fn insert_menu_item_chooser_cancels_or_records_descriptor_free_filter_event() { expected.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap(); let expected = photocraft_compose::flatten(&expected.active().unwrap().doc).into_px(); assert_ne!(expected, original, "the Gaussian fixture has a visible effect"); - h.state_mut().session.actions.list.insert_step(0, 1, ActionStep::new("select.all", json!({}))).unwrap(); + h.state_mut().session.actions_mut().list.insert_step(0, 1, ActionStep::new("select.all", json!({}))).unwrap(); let paused = h.state_mut().run("actions.play", json!({"action":"A"})).unwrap(); let dialog = paused_dialog(&paused); assert_eq!(set_field(&mut h, dialog, "radius", json!(2))["ok"], true); @@ -137,8 +138,8 @@ fn control_playback_opens_menu_settings_only_for_menu_invocation() { let ctx = h.ctx.clone(); let app = h.state_mut(); app.run("actions.insertMenuItem", json!({"action":"A","id":"filter.blur.gaussianBlur"})).unwrap(); - app.session.actions.list.insert_step(0, 0, ActionStep::new("select.all", json!({}))).unwrap(); - app.session.actions.list.insert_step(0, 2, ActionStep::new("select.deselect", json!({}))).unwrap(); + app.session.actions_mut().list.insert_step(0, 0, ActionStep::new("select.all", json!({}))).unwrap(); + app.session.actions_mut().list.insert_step(0, 2, ActionStep::new("select.deselect", json!({}))).unwrap(); app.session.edit_prefs(|prefs| prefs.actions.performance = PlaybackPerformance::StepByStep); // Starting at the menu step checks the original dialog bug. Starting one step earlier @@ -214,7 +215,7 @@ fn paused_menu_preview_keeps_the_requesting_gate_and_rejects_retargeting() { // The stored step now names another command than the editor opened for. h.state_mut() .session - .actions + .actions_mut() .list .replace_step(0, 0, ActionStep::new(atn_cmds::MENU_ITEM, json!({"id":"filter.distort.displace","eventKind":"name"}))) .unwrap(); diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index b6b66bbe90..bc0045c853 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -7,6 +7,7 @@ //! redraws between them. Esc, the panel's Stop button, an edit of the action list or a new recording end //! it there, keeping the steps already applied. Programmatic playback never waits. +use photocraft_engine::actions_cmds::ActionsExt; use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; @@ -62,7 +63,7 @@ pub(super) fn step_pause(app: &PhotocraftApp) -> Option { /// Park `action` after its step `i` (`ran` steps of it so far): it continues from the next step /// after `wait`. Returns the `paused` value the runner reports. pub(super) fn pace(app: &mut PhotocraftApp, action: &str, i: usize, id: &str, ran: u64, wait: Duration) -> Value { - let rev = app.session.actions.list.revision(); + let rev = app.session.actions().list.revision(); let gate = app.session.authorize; let pb = &mut app.paused_playbacks; let token = pb.pause(action.to_string(), i.saturating_add(1), gate); @@ -102,7 +103,7 @@ pub(crate) fn stop(app: &mut PhotocraftApp) -> bool { pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(timer) = app.paused_playbacks.timer else { return }; let esc = !app.dialog_open() && crate::window_keys::take_escape(ctx); - let changed = timer.rev != app.session.actions.list.revision() || app.session.recording.target.is_some(); + let changed = timer.rev != app.session.actions().list.revision() || app.session.recording.target.is_some(); if esc || changed || !app.paused_playbacks.paused.contains_key(&timer.token) { stop(app); return; diff --git a/crates/ui-egui/src/panels/actions/playback_tests.rs b/crates/ui-egui/src/panels/actions/playback_tests.rs index 94f50bc68e..05a57ed139 100644 --- a/crates/ui-egui/src/panels/actions/playback_tests.rs +++ b/crates/ui-egui/src/panels/actions/playback_tests.rs @@ -2,6 +2,7 @@ //! frame (and the wait) between steps, in one history state when Create a single history state is //! on; Esc and the Stop button end them keeping the steps applied. Measured in the reference //! application 2026-11-05. +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use photocraft_engine::actions_cmds::ActionStep; use web_time::{Duration, Instant}; @@ -16,7 +17,7 @@ fn app_with(performance: &str, seconds: u8, single: bool) -> Box app.run("file.new", json!({"width": 8, "height": 6})).unwrap(); app.run("actions.setPlayback", json!({"performance": performance, "seconds": seconds, "singleState": single})).unwrap(); let steps = ["A", "B", "C"].map(|n| ActionStep::new("layer.new.layer", json!({"name": n}))).to_vec(); - app.session.actions.list.push(Action::new("Three", steps)).unwrap(); + app.session.actions_mut().list.push(Action::new("Three", steps)).unwrap(); app } @@ -131,7 +132,7 @@ fn esc_or_stop_ends_the_playback_and_keeps_the_steps_applied() { frame(&mut app, &ctx, Vec::new()); } _ => { - app.session.actions.list.push(Action::new("One", vec![ActionStep::new("layer.new.layer", json!({"name": "D"}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("One", vec![ActionStep::new("layer.new.layer", json!({"name": "D"}))])).unwrap(); app.run("actions.setPlayback", json!({"performance": "accelerated"})).unwrap(); play(&mut app, &json!({"action": "One"})).unwrap(); } @@ -191,7 +192,7 @@ fn nested_and_set_playback_stay_one_play() { let mut app = app_with("step", 1, true); let ctx = app.ctx().clone(); app.session - .actions + .actions_mut() .list .push(Action::new( "Caller", @@ -218,7 +219,7 @@ fn nested_and_set_playback_stay_one_play() { // Counted as Accelerated counts it: the Play Action step is one step of its caller. assert_eq!(app.ui.status, "Played 3 steps"); let mut fast = app_with("accelerated", 1, true); - fast.session.actions.list.push(app.session.actions.list.actions()[1].clone()).unwrap(); + fast.session.actions_mut().list.push(app.session.actions().list.actions()[1].clone()).unwrap(); let v = play_targets(&mut fast, &[1], 0, 0).unwrap().unwrap(); assert_eq!(v["ran"], 3, "{v}"); } diff --git a/crates/ui-egui/src/panels/actions/record_again.rs b/crates/ui-egui/src/panels/actions/record_again.rs index 2b8936a22b..575b8b7a3f 100644 --- a/crates/ui-egui/src/panels/actions/record_again.rs +++ b/crates/ui-egui/src/panels/actions/record_again.rs @@ -1,4 +1,5 @@ //! One editor owns one original step; previews and confirmation retain its authority. +use photocraft_engine::actions_cmds::ActionsExt; use craft::ui::dialog::DialogId; use photocraft_engine::{ actions_edit_cmds, @@ -33,7 +34,7 @@ fn authorize(app: &PhotocraftApp, held: &Held, id: &str, params: &Value) -> Resu /// Refuse stale selection or a different document before preview or confirmation can edit it. fn unchanged(app: &PhotocraftApp, held: &Held) -> Result<(), String> { super::suspended_guard(app, COMMAND)?; - if held.selection.get("revision").and_then(Value::as_u64) != Some(app.session.actions.list.revision()) + if held.selection.get("revision").and_then(Value::as_u64) != Some(app.session.actions().list.revision()) || app.session.recording.target.is_some() || app.session.recording.playing > 0 { @@ -52,7 +53,7 @@ pub(super) fn open(app: &mut PhotocraftApp, action: usize, step: usize) -> Resul return Err(tl!("Confirm or cancel the pending Record Again editor first.").into()); } app.held_record_again = None; - let selection = json!({"action": action, "step": step, "revision": app.session.actions.list.revision()}); + let selection = json!({"action": action, "step": step, "revision": app.session.actions().list.revision()}); let target = actions_edit_cmds::record_again_target(&app.session, &selection).map_err(|e| e.to_string())?; let gate = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }); let mut held = Held { diff --git a/crates/ui-egui/src/panels/actions/record_again_tests.rs b/crates/ui-egui/src/panels/actions/record_again_tests.rs index 08cfbb9473..4d9ba05b56 100644 --- a/crates/ui-egui/src/panels/actions/record_again_tests.rs +++ b/crates/ui-egui/src/panels/actions/record_again_tests.rs @@ -1,5 +1,6 @@ //! Record Again uses the real editor while retaining the selected step and permissions. These trials read the dialog //! host (`app.framework`), so they live in the crate. +use photocraft_engine::actions_cmds::ActionsExt; use std::sync::atomic::{AtomicUsize, Ordering}; use craft::automation::ui::actions::{ActionSelection, ActionsPanelCommands}; @@ -24,7 +25,7 @@ fn harness(command: &str, params: Value) -> Harness<'static, Box> let mut action = Action::new("A", vec![ActionStep::new(command, params), ActionStep::new("select.all", json!({}))]); action.disabled.insert(0); action.dialogs.insert(0); - app.session.actions.list.push(action).unwrap(); + app.session.actions_mut().list.push(action).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Step(0, 0)); let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1000.0, 760.0)).build_ui_state(|ui, app| crate::dialogs::run(app, ui), app); @@ -88,13 +89,13 @@ fn sizing() -> Harness<'static, Box> { #[test] fn seeded_editor_cancels_or_updates_only_the_original_step() { let mut h = sizing(); - let original = h.state().session.actions.list.clone(); + let original = h.state().session.actions().list.clone(); let revision = h.state().session.active().unwrap().revision; let dialog = open(&mut h); assert_eq!(number(&h, dialog, "width"), Some(4.0)); assert_eq!(number(&h, dialog, "height"), Some(3.0)); cancel(&mut h, dialog); - assert_eq!(h.state().session.actions.list, original); + assert_eq!(h.state().session.actions().list, original); assert_eq!(h.state().session.active().unwrap().revision, revision); assert!(!is_open(&h, dialog)); let dialog = open(&mut h); @@ -103,7 +104,7 @@ fn seeded_editor_cancels_or_updates_only_the_original_step() { assert_eq!(set_field(&mut h, dialog, "height", json!(5))["ok"], true); confirm(&mut h, dialog).unwrap(); assert!(!h.state().dialog_open()); - let action = h.state().session.actions.list.action(0).unwrap(); + let action = h.state().session.actions().list.action(0).unwrap(); assert_eq!(action.steps.len(), 2); assert_eq!(action.steps[0].params["width"].as_f64(), Some(6.0)); assert!(action.disabled.contains(&0)); @@ -145,18 +146,18 @@ fn stale_denied_or_failed_edit_preserves_the_stored_step() { } "retargeted" => { let other = ActionStep::new("select.all", json!({})); - h.state_mut().session.actions.list.replace_step(0, 0, other).unwrap(); + h.state_mut().session.actions_mut().list.replace_step(0, 0, other).unwrap(); } _ => { accepted = set_field(&mut h, dialog, "percent", json!(-1))["ok"] == true; } } - let original = h.state().session.actions.list.clone(); + let original = h.state().session.actions().list.clone(); let revision = h.state().session.active().unwrap().revision; if accepted { assert!(confirm(&mut h, dialog).is_err(), "{mode}"); } - assert_eq!(h.state().session.actions.list, original, "{mode}"); + assert_eq!(h.state().session.actions().list, original, "{mode}"); assert_eq!(h.state().session.active().unwrap().revision, revision, "{mode}"); cancel(&mut h, dialog); let retry = open(&mut h); @@ -168,7 +169,7 @@ fn stale_denied_or_failed_edit_preserves_the_stored_step() { #[test] fn another_dialog_cannot_consume_the_selected_step() { let mut h = sizing(); - let original = h.state().session.actions.list.clone(); + let original = h.state().session.actions().list.clone(); let real = open(&mut h); let key = h.state().framework.dialogs.open_dialogs().into_iter().find(|open| open.id == real).and_then(|open| open.key).expect("the editor has a key"); // A second hosted dialog with the same key and values, as another opener could make it. @@ -186,7 +187,7 @@ fn another_dialog_cannot_consume_the_selected_step() { ); h.run_steps(3); let _ = confirm(&mut h, fake); - assert_eq!(h.state().session.actions.list, original, "the impostor's answer does not touch the stored step"); + assert_eq!(h.state().session.actions().list, original, "the impostor's answer does not touch the stored step"); assert!(is_open(&h, real), "the real editor is still waiting for its own answer"); confirm(&mut h, real).unwrap(); assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_engine::doc::Size::new(4, 3)); @@ -235,7 +236,7 @@ fn filter_and_adjustment_previews_retain_permissions_before_evaluation() { if command == "image.adjustments.levels" { assert!(crate::dialogs::adjust_preview::display_doc(h.state_mut(), 0).is_some(), "the permitted adjustment preview is evaluated"); } - let original = h.state().session.actions.list.clone(); + let original = h.state().session.actions().list.clone(); let revision = h.state().session.active().unwrap().revision; if command.starts_with("filter.") { set_field(&mut h, dialog, "radius", json!(8)); @@ -249,10 +250,10 @@ fn filter_and_adjustment_previews_retain_permissions_before_evaluation() { PREVIEW_CHECKS.store(0, Ordering::SeqCst); preview_routes(h.state_mut(), &context); assert!(PREVIEW_CHECKS.load(Ordering::SeqCst) > 0, "the changed actual request was refused before evaluation: {command}"); - assert_eq!(h.state().session.actions.list, original); + assert_eq!(h.state().session.actions().list, original); assert_eq!(h.state().session.active().unwrap().revision, revision); let answer = confirm(&mut h, dialog); assert!(answer.is_err(), "OK with the changed settings is refused: {command}"); - assert_eq!(h.state().session.actions.list, original); + assert_eq!(h.state().session.actions().list, original); } } diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index 950cf8bde3..37434625e0 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -2,6 +2,7 @@ //! [`ActionPlayer`] its step semantics (dialogs, Stop messages, shell saves and views), and the //! paused playbacks that continue after a step dialog, a Stop message or a Step by Step wait. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::actions::{ActionPlayer, ActionRunner, ActionStep, PlaybackBudget, PlaybackRefusal, PlaybackReport, StepOutcome}; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{HostedCanvasSize, HostedImageSize, HostedParamDialog}; @@ -24,7 +25,7 @@ pub(crate) fn play_targets(app: &mut PhotocraftApp, targets: &[usize], from: usi playback::stop(app); let (mut last, mut ran) = (None, before); for (n, &i) in targets.iter().enumerate() { - let name = app.session.actions.list.action(i).map(|a| a.name.clone()); + let name = app.session.actions().list.action(i).map(|a| a.name.clone()); let params = if n == 0 && from > 0 { json!({"action": i, "from": from}) } else { json!({"action": i}) }; let mut v = app.run("actions.play", params)?; ran = ran.saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); @@ -37,7 +38,7 @@ pub(crate) fn play_targets(app: &mut PhotocraftApp, targets: &[usize], from: usi if let Some(dialog) = paused.filter(|_| !failed) { // As they are now, not by index: the list can be reordered while the dialog is open // (`actions.move`), and one deleted and made again under its name isn't the same action. - let list = &app.session.actions.list; + let list = &app.session.actions().list; let rest: Vec = targets.get(n + 1..).unwrap_or_default().iter().filter_map(|i| list.action(*i).cloned()).collect(); let token = paused_token(app, &dialog); if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) @@ -509,7 +510,7 @@ fn play_steps( }; let owner = recording .map(|(_, idx)| { - let into = app.session.actions.list.action(idx).map(|a| a.name.clone()); + let into = app.session.actions().list.action(idx).map(|a| a.name.clone()); json!({"index": idx, "into": into, "action": action.name, "from": from}) }) .or(suspended); @@ -551,7 +552,7 @@ fn play_steps( } if !ended { // The runner borrows the app for the whole play, so the player reads its own copy of the playable list. - let list = app.session.actions.playable().clone(); + let list = app.session.actions().playable().clone(); let mut runner = ShellRunner { app: &mut *app, interactive, resolved: None, ending: None, detail: None, wait: None }; let report: PlaybackReport = ActionPlayer::play(&list, index, from, &mut runner, budget); let ShellRunner { ending, detail, wait, .. } = runner; @@ -670,7 +671,7 @@ fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { // `suspended_guard` refuses what would move the recorded action, but another command may // still replace the list: the call goes to the action of that name, never to whatever now // sits at the old index, and is dropped if that action is gone. - let list = app.session.actions.list.actions(); + let list = app.session.actions().list.actions(); let target = if list.get(idx).is_some_and(|a| a.name == into) { Some(idx) } else { list.iter().position(|a| a.name == into) }; if let Some(idx) = target && app.session.recording.target.is_none() @@ -907,7 +908,7 @@ pub(crate) fn check_editor(app: &PhotocraftApp, dialog: DialogId, command: &str, /// Check that preview and confirmation still target the command and receiver that opened the editor. fn check_menu_editor(app: &PhotocraftApp, paused: &PausedPlayback, command: &str, params: &Value) -> Result<(), String> { - let actions = app.session.actions.list.actions(); + let actions = app.session.actions().list.actions(); if let Some((_, original)) = &paused.menu_editor && (original != command || paused.played.iter().any(|played| actions.iter().find(|action| action.name == played.name) != Some(played)) @@ -1060,7 +1061,7 @@ pub fn resume(app: &mut PhotocraftApp, token: u64) -> Result<(), String> { || !paused.callers.is_empty() || app .session - .actions + .actions() .list .actions() .iter() @@ -1085,7 +1086,7 @@ pub fn resume(app: &mut PhotocraftApp, token: u64) -> Result<(), String> { // The rest plays by name: refuse it when an action of the paused call changed meanwhile, so a // new action of the same name never plays from the old one's step. With nothing left to play, // the call simply ends. (Another document coming to the front fails `history.resume` above.) - let list = app.session.actions.list.actions(); + let list = app.session.actions().list.actions(); if remaining && paused.played.iter().any(|a| list.iter().find(|b| b.name == a.name) != Some(a)) { let error = "the action changed while it was paused"; actions_cmds::finish_pending_history(&mut app.session); @@ -1132,7 +1133,7 @@ pub fn resume(app: &mut PhotocraftApp, token: u64) -> Result<(), String> { && v.get("paused").is_none() && v.get("stopped").is_none() { - let list = app.session.actions.list.actions(); + let list = app.session.actions().list.actions(); let rest: Vec = paused.then.iter().map_while(|then| list.iter().position(|a| a == then)).collect(); match play_targets(app, &rest, 0, ran) { Ok(Some(r)) => played = Ok(r), diff --git a/crates/ui-egui/src/panels/actions/runner_tests.rs b/crates/ui-egui/src/panels/actions/runner_tests.rs index 5b6cf5f076..88bbafa5ca 100644 --- a/crates/ui-egui/src/panels/actions/runner_tests.rs +++ b/crates/ui-egui/src/panels/actions/runner_tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::automation::actions::{ActionList, ActionStep}; @@ -21,18 +22,18 @@ fn new_action(name: &str, pairs: Vec<(String, Value)>) -> Action { /// Add `action` to the session's list. fn add_action(app: &mut PhotocraftApp, action: Action) { - app.session.actions.list.push(action).expect("a name the list does not hold yet"); + app.session.actions_mut().list.push(action).expect("a name the list does not hold yet"); } /// The steps of action `index` as `(command, params)` pairs, the form the journal and the engine's /// results keep. fn pairs(app: &PhotocraftApp, index: usize) -> Vec<(String, Value)> { - app.session.actions.list.actions()[index].steps.iter().map(|s| (s.command.clone(), s.params.clone())).collect() + app.session.actions().list.actions()[index].steps.iter().map(|s| (s.command.clone(), s.params.clone())).collect() } /// The commands of action `index`'s steps. fn commands(app: &PhotocraftApp, index: usize) -> Vec { - app.session.actions.list.actions()[index].steps.iter().map(|s| s.command.clone()).collect() + app.session.actions().list.actions()[index].steps.iter().map(|s| s.command.clone()).collect() } /// Edit the session's actions as a plain vector, to reach states the list's own edits do not @@ -40,9 +41,9 @@ fn commands(app: &PhotocraftApp, index: usize) -> Vec { /// replaces the old one through [`ActionList::replace`], so the revision only moves forward; a /// name taken twice is renamed, as for any load. fn edit_actions(app: &mut PhotocraftApp, edit: impl FnOnce(&mut Vec)) { - let mut file = app.session.actions.list.to_file(); + let mut file = app.session.actions().list.to_file(); edit(&mut file.actions); - app.session.actions.list.replace(ActionList::from_file(file)); + app.session.actions_mut().list.replace(ActionList::from_file(file)); } /// Press the footer's Play on the selected action (or `action` from step `from`), as the panel @@ -315,12 +316,12 @@ fn spelling_playback_blocks_library_edits_until_done() { let error = app.run("actions.clearAll", json!({"confirm": true})).unwrap_err(); assert_eq!(app.ui.status, error); assert!(app.ui.status_error); - assert_eq!(app.session.actions.list.actions()[0].name, "Spell"); + assert_eq!(app.session.actions().list.actions()[0].name, "Spell"); close_spelling(&mut app); let st = app.session.active().unwrap(); assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "Tail"); app.run("actions.clearAll", json!({"confirm": true})).unwrap(); - assert!(app.session.actions.list.actions().is_empty()); + assert!(app.session.actions().list.actions().is_empty()); } fn deny_second_spelling_change(id: &str, params: &Value) -> photocraft_engine::Result<()> { @@ -435,7 +436,7 @@ fn nested_shell_actions_include_view_steps_and_propagate_failures() { let output = dir.path().join(if mixed { "mixed" } else { "success" }); let inputs = if mixed { vec![&input, &corrupt] } else { vec![&input] }; let batch = json!({"input": inputs, "output": output, "steps": [], "format": "png"}); - let index = app.session.actions.list.actions().len(); + let index = app.session.actions().list.actions().len(); let name = if mixed { "Mixed Batch" } else { "Successful Batch" }; add_action(&mut app, new_action(name, vec![("file.automate.batch".into(), batch), ("file.new".into(), json!({"width": 2, "height": 2}))])); let result = app.run("actions.play", json!({"action": index})).unwrap(); @@ -478,7 +479,7 @@ fn played_view_steps_act_on_the_document_the_steps_before_them_opened() { assert_ne!(opened, 0); assert!(app.ui.views[opened].pending.ends_with(&[ViewCommands::ZoomIn, ViewCommands::ZoomIn, ViewCommands::FitOnScreen].map(ViewRequest::Command))); assert!(app.ui.views[0].pending.is_empty(), "the document open before is left alone"); - let around = app.session.actions.list.actions().iter().position(|a| a.name == "Around").unwrap(); + let around = app.session.actions().list.actions().iter().position(|a| a.name == "Around").unwrap(); assert_eq!(commands(&app, around), ["actions.play"], "the view steps are not recorded a second time"); } @@ -493,13 +494,13 @@ fn view_menu_commands_record_append_and_replay_after_resize() { super::begin_recording(&mut app, Some(0)); crate::menus::invoke(&mut app, &ctx, "view.fitOnScreen", json!({})).unwrap(); app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list.actions().len(), 1); + assert_eq!(app.session.actions().list.actions().len(), 1); assert_eq!(commands(&app, 0), ["image.canvasSize", "view.fitOnScreen"]); assert_eq!(label_of("view.fitOnScreen"), "Fit on Screen"); // Persisted actions retain the menu step, and playback fits the new document. - let saved = serde_json::to_string(&app.session.actions.list.to_file()).unwrap(); + let saved = serde_json::to_string(&app.session.actions().list.to_file()).unwrap(); let file = serde_json::from_str(&saved).unwrap(); - app.session.actions.list.replace(ActionList::from_file(file)); + app.session.actions_mut().list.replace(ActionList::from_file(file)); app.run("file.new", json!({"width": 200, "height": 140})).unwrap(); app.run("view.actualPixels", json!({})).unwrap(); let result = app.run("actions.play", json!({"action": 0})).unwrap(); @@ -794,7 +795,7 @@ fn recorded_save_as_with_the_suggested_name_saves_each_document_under_its_own() [("file.saveAs".into(), json!({"folder": "out", "extension": "psd"})), ("file.saveAs".into(), json!({"path": "out/renamed.psd"}))] ); // Played on two other documents: each under its own name in the recorded folder. - app.session.actions.list.delete_step(0, 1).unwrap(); + app.session.actions_mut().list.delete_step(0, 1).unwrap(); written.borrow_mut().clear(); let mut expected = Vec::new(); for name in ["second", "third"] { @@ -1004,7 +1005,7 @@ fn a_check_spelling_step_with_its_dialog_opens_it_and_done_continues() { assert!(layer_names(&app).contains(&"after".to_string()), "Done played the rest"); assert!(app.ui.status.starts_with("Played"), "{}", app.ui.status); // With its dialog off, the step checks without opening anything and changes nothing. - app.session.actions.list.set_dialog(0, 0, false).unwrap(); + app.session.actions_mut().list.set_dialog(0, 0, false).unwrap(); let v = play(&mut app, &json!({"action": "Spell"})).unwrap(); assert_eq!(v["ran"], 2, "{v}"); assert!(app.ui.type_panels.spell.is_none()); @@ -1261,7 +1262,7 @@ fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { let live = app.session.journal.len(); let id = pause_child(&mut app); assert!(app.session.recording.target.is_none(), "recording stays suspended while the step dialog is open"); - let names = |app: &PhotocraftApp| app.session.actions.list.actions().iter().map(|a| a.name.clone()).collect::>(); + let names = |app: &PhotocraftApp| app.session.actions().list.actions().iter().map(|a| a.name.clone()).collect::>(); let before = names(&app); assert_eq!(app.run("actions.record", json!({"name": "Intruder"})), Err(refusal.clone()), "no second recording while the call is suspended"); assert_eq!(app.run("actions.delete", json!({"action": "Owner"})), Err(refusal.clone()), "the suspended owner can't be deleted"); @@ -1329,7 +1330,7 @@ fn a_failing_resumed_playback_ends_the_recorded_call_once() { let mut app = recording_with_dialog_child(); let id = pause_child(&mut app); // The rest of the call can't be found any more: resuming it fails. - app.session.actions.list.rename(0, "Renamed", |_, _, _| {}).unwrap(); + app.session.actions_mut().list.rename(0, "Renamed", |_, _, _| {}).unwrap(); assert!(answer_ok(&mut app, id).is_err(), "the resumed playback fails"); assert!(app.session.recording.target.is_some(), "recording comes back when the resumed playback fails"); app.run("actions.stop", json!({})).unwrap(); @@ -1345,7 +1346,7 @@ fn a_suspended_call_is_recorded_into_its_action_after_the_list_changes() { answer_ok(&mut app, id).unwrap(); app.run("actions.stop", json!({})).unwrap(); assert!(pairs(&app, 1).is_empty(), "the action now at the old index gets nothing"); - assert_eq!(app.session.actions.list.actions()[2].name, "Owner"); + assert_eq!(app.session.actions().list.actions()[2].name, "Owner"); assert_eq!(pairs(&app, 2), child_call()); } @@ -1409,7 +1410,7 @@ fn recording_with_displace_child(answers: impl IntoIterator app.session.authorize = Some(deny_wide_blur), @@ -1710,7 +1711,7 @@ fn configured_gates_require_one_composed_policy_for_automated_resume() { assert!(!std::ptr::fn_addr_eq(deny_wide_blur as Gate, deny_file_open as Gate)); for (automated, identical) in [(false, false), (true, false), (true, true)] { let mut app = gated_blur_fixture(true, false); - app.session.actions.list.insert_step(0, 1, ActionStep::new("layer.renameLayer", json!({"name":"Allowed tail"}))).unwrap(); + app.session.actions_mut().list.insert_step(0, 1, ActionStep::new("layer.renameLayer", json!({"name":"Allowed tail"}))).unwrap(); app.session.authorize = Some(deny_wide_blur); let service: Gate = if identical { deny_wide_blur } else { deny_file_open }; app.services.automation_authorize = Some(service); @@ -1749,7 +1750,7 @@ fn configured_gates_require_one_composed_policy_for_automated_resume() { /// A policy change after the final spelling step must not discard completed edits when no tail remains to dispatch. fn a_changed_gate_after_the_last_spelling_step_keeps_completed_edits() { let (mut app, before, past) = paused_history_spelling(true, Some(deny_wide_blur)); - app.session.actions.list.delete_step(0, 2).unwrap(); + app.session.actions_mut().list.delete_step(0, 2).unwrap(); spelling_change(&mut app, json!({"action":"change","start":0,"end":3,"word":"Teh","replace":"The"})).unwrap(); let corrected = app.session.active().unwrap().doc.clone(); app.session.authorize = Some(|_, _| Ok(())); @@ -1786,7 +1787,7 @@ fn paused_adjustments_bind_implicit_pixel_and_mask_receivers() { } else if targeting == "null" { params["layer"] = Value::Null; } - app.session.actions.list.replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", params)).unwrap(); + app.session.actions_mut().list.replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", params)).unwrap(); let dialog = pause_gated_blur(&mut app, None); app.session.select_layer(b).unwrap(); let before = app.session.active().unwrap().doc.clone(); @@ -1817,7 +1818,7 @@ fn paused_adjustments_bind_implicit_pixel_and_mask_receivers() { let b = photocraft_doc::LayerId(app.run("layer.new.layer", json!({"name":"B"})).unwrap()["layer"].as_u64().unwrap()); app.session.select_layer(a).unwrap(); app.session - .actions + .actions_mut() .list .replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", json!({"brightness":40,"target":{"channel":0}}))) .unwrap(); @@ -1837,7 +1838,7 @@ fn paused_adjustments_bind_implicit_pixel_and_mask_receivers() { app.run("layer.layerMask.revealAll", json!({})).unwrap(); app.run("edit.fill", json!({"color":"#808080","target":"mask"})).unwrap(); assert!(app.layer_mask_targeted()); - app.session.actions.list.replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", json!({"brightness":40}))).unwrap(); + app.session.actions_mut().list.replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", json!({"brightness":40}))).unwrap(); let before = app.session.active().unwrap().doc.clone(); let rows = app.session.active().unwrap().history.past_len(); let dialog = pause_gated_blur(&mut app, None); @@ -1861,7 +1862,7 @@ fn a_document_channel_adjustment_survives_an_active_layer_change() { app.run("edit.fill", json!({"color":"#808080","target":{"channel":0}})).unwrap(); app.session.select_layer(a).unwrap(); app.session - .actions + .actions_mut() .list .replace_step(0, 0, ActionStep::new("image.adjustments.brightnessContrast", json!({"brightness":40,"target":{"channel":0}}))) .unwrap(); @@ -1887,9 +1888,9 @@ fn an_implicit_paused_filter_refuses_a_public_api_receiver_change() { app.run("select.deselect", json!({})).unwrap(); app.session.select_layer(a).unwrap(); if explicit { - let mut step = app.session.actions.list.actions()[0].steps[0].clone(); + let mut step = app.session.actions().list.actions()[0].steps[0].clone(); step.params["layer"] = json!(a.0); - app.session.actions.list.replace_step(0, 0, step).unwrap(); + app.session.actions_mut().list.replace_step(0, 0, step).unwrap(); } let dialog = pause_gated_blur(&mut app, None); // Supported host/session API, not a modal-blocked native menu/control command. @@ -2062,7 +2063,7 @@ fn a_kept_gate_does_not_carry_into_the_rest_of_a_set_after_a_pause() { // With that step off, the tail passes, and the user's own action after it plays with the // user's access. - app.session.actions.list.set_step(0, 2, false).unwrap(); + app.session.actions_mut().list.set_step(0, 2, false).unwrap(); play_set(&mut app, "S"); let dialog = last_dialog(&app); answer_ok(&mut app, dialog).unwrap(); diff --git a/crates/ui-egui/src/panels/actions/stop_tests.rs b/crates/ui-egui/src/panels/actions/stop_tests.rs index d83a00202d..5579344f09 100644 --- a/crates/ui-egui/src/panels/actions/stop_tests.rs +++ b/crates/ui-egui/src/panels/actions/stop_tests.rs @@ -2,6 +2,7 @@ //! and Stop; with the toggle off it ends the playback without a word; a pause inside a called //! action continues into its callers. Behaviour measured in the reference application //! (2026-11-05). +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::ui::dialog::{DialogId, StandardPrompt}; use photocraft_engine::actions_cmds::ActionStep; @@ -35,7 +36,7 @@ pub(super) fn stop_app(allow: bool, with_dialog: bool) -> Box { } let (bytes, _) = photocraft_engine::atn_cmds::export("Stops", &[&action], &[], false).unwrap(); app.run("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&bytes)})).unwrap(); - assert_eq!(app.session.actions.list.actions()[0].dialogs.contains(&1), with_dialog); + assert_eq!(app.session.actions().list.actions()[0].dialogs.contains(&1), with_dialog); app } @@ -44,7 +45,7 @@ fn nested_app(allow: bool) -> Box { let mut app = stop_app(allow, true); for (name, child) in [("Parent", "Stop Test"), ("Grandparent", "Parent")] { app.session - .actions + .actions_mut() .list .push(Action::new( name, @@ -173,7 +174,7 @@ fn a_stop_restores_a_suspended_recording_once_for_every_exit() { } assert!(app.session.recording.target.is_some()); app.run("actions.stop", json!({})).unwrap(); - let owner = app.session.actions.list.actions().iter().find(|a| a.name == "Owner").unwrap(); + let owner = app.session.actions().list.actions().iter().find(|a| a.name == "Owner").unwrap(); assert_eq!(owner.steps, vec![ActionStep::new("actions.play", json!({"action": "Stop Test"}))]); assert_idle(&app); } @@ -184,10 +185,10 @@ fn a_stop_restores_a_suspended_recording_once_for_every_exit() { fn continue_inside_a_called_action_finishes_every_caller_once() { let mut app = nested_app(true); // A second pause in Parent, after the call, keeps Grandparent's continuation too. - let parent = app.session.actions.list.actions().iter().position(|a| a.name == "Parent").unwrap(); + let parent = app.session.actions().list.actions().iter().position(|a| a.name == "Parent").unwrap(); let pause = ActionStep::new(STOP_MESSAGE, json!({"message": "Parent pause", "allowContinue": true})); - app.session.actions.list.insert_step(parent, 2, pause).unwrap(); - app.session.actions.list.set_dialog(parent, 2, true).unwrap(); + app.session.actions_mut().list.insert_step(parent, 2, pause).unwrap(); + app.session.actions_mut().list.set_dialog(parent, 2, true).unwrap(); let history = app.session.active().unwrap().history.past_len(); app.run("actions.record", json!({"name": "Owner"})).unwrap(); let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); @@ -210,7 +211,7 @@ fn continue_inside_a_called_action_finishes_every_caller_once() { assert_eq!(st.history.undo_label(), Some("Action: Grandparent")); assert!(app.session.recording.target.is_some()); app.run("actions.stop", json!({})).unwrap(); - let owner = app.session.actions.list.actions().iter().find(|a| a.name == "Owner").unwrap(); + let owner = app.session.actions().list.actions().iter().find(|a| a.name == "Owner").unwrap(); assert_eq!(owner.steps, vec![ActionStep::new("actions.play", json!({"action": "Grandparent"}))]); } @@ -219,7 +220,7 @@ fn stop_a_hard_stop_or_a_failing_child_ends_every_caller() { for (allow, confirm, fail) in [(true, false, false), (false, true, false), (true, true, true)] { let mut app = nested_app(allow); if fail { - app.session.actions.list.replace_step(0, 2, ActionStep::new("layer.select", json!({"layer": 999_999}))).unwrap(); + app.session.actions_mut().list.replace_step(0, 2, ActionStep::new("layer.select", json!({"layer": 999_999}))).unwrap(); } let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); assert_eq!(v["paused"]["step"], 1, "{v}"); @@ -236,7 +237,7 @@ fn stop_a_hard_stop_or_a_failing_child_ends_every_caller() { #[test] fn a_silent_stop_inside_a_called_action_ends_its_callers() { let mut app = nested_app(true); - app.session.actions.list.set_dialog(0, 1, false).unwrap(); + app.session.actions_mut().list.set_dialog(0, 1, false).unwrap(); let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); assert!(v.get("failed").is_none(), "{v}"); assert!(v["stopped"].is_object(), "{v}"); @@ -247,7 +248,7 @@ fn a_silent_stop_inside_a_called_action_ends_its_callers() { #[test] fn a_resumed_called_action_still_refuses_to_call_its_paused_callers() { let mut app = nested_app(true); - app.session.actions.list.replace_step(0, 2, ActionStep::new("actions.play", json!({"action": "Grandparent"}))).unwrap(); + app.session.actions_mut().list.replace_step(0, 2, ActionStep::new("actions.play", json!({"action": "Grandparent"}))).unwrap(); let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); assert_eq!(v["paused"]["step"], 1, "{v}"); { @@ -264,7 +265,7 @@ fn a_resumed_called_action_still_refuses_to_call_its_paused_callers() { #[test] fn a_filter_dialog_inside_a_called_action_continues_its_callers_after_ok() { let mut app = nested_app(true); - app.session.actions.list.replace_step(0, 1, ActionStep::new("filter.blur.gaussianBlur", json!({"radius": 1.5}))).unwrap(); + app.session.actions_mut().list.replace_step(0, 1, ActionStep::new("filter.blur.gaussianBlur", json!({"radius": 1.5}))).unwrap(); app.background_jobs = true; let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); answer(&mut app, paused_dialog(&v), true).unwrap(); @@ -276,9 +277,9 @@ fn a_filter_dialog_inside_a_called_action_continues_its_callers_after_ok() { /// `If` makes Before, runs `Stop Test` when `condition` holds (`Other` when not), then makes After. fn conditional_app(condition: &str) -> Box { let mut app = stop_app(true, true); - app.session.actions.list.push(Action::new("Other", vec![ActionStep::new("layer.new.layer", json!({"name": "Other"}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("Other", vec![ActionStep::new("layer.new.layer", json!({"name": "Other"}))])).unwrap(); app.session - .actions + .actions_mut() .list .push(Action::new( "If", @@ -317,7 +318,7 @@ fn a_conditional_branch_plays_through_the_panel_and_its_stop_shows_its_message() assert_eq!(names(&app), ["Before", "Other", "After"]); assert_idle(&app); let mut app = conditional_app("always"); - app.session.actions.list.set_dialog(0, 1, false).unwrap(); + app.session.actions_mut().list.set_dialog(0, 1, false).unwrap(); let v = play(&mut app, &json!({"action": "If"})).unwrap(); assert!(v["stopped"].is_object() && v.get("failed").is_none(), "{v}"); assert_eq!(names(&app), ["Before", "Prefix"], "a Stop without its dialog ends the caller too"); @@ -337,10 +338,10 @@ fn a_paused_action_replaced_under_the_same_name_does_not_continue() { let v = play(&mut app, &json!({"action": "Grandparent"})).unwrap(); assert_eq!(v["paused"]["step"], 1, "{v}"); let id = stop_prompt(&app); - let i = app.session.actions.list.actions().iter().position(|a| a.name == replaced).unwrap(); + let i = app.session.actions().list.actions().iter().position(|a| a.name == replaced).unwrap(); let steps = (0..4).map(|n| ActionStep::new("layer.new.layer", json!({"name": format!("Replacement {n}")}))).collect(); - app.session.actions.list.delete_action(i).unwrap(); - app.session.actions.list.push(Action::new(replaced, steps)).unwrap(); + app.session.actions_mut().list.delete_action(i).unwrap(); + app.session.actions_mut().list.push(Action::new(replaced, steps)).unwrap(); answer(&mut app, id, true).unwrap(); assert_eq!(names(&app), ["Grandparent prefix", "Parent prefix", "Prefix"], "{replaced}: nothing of either action's tail runs"); assert!(app.ui.status_error && app.ui.status.contains("changed"), "{}", app.ui.status); diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index fc1ce0c436..be2ee64885 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::automation::actions::ActionStep; use craft::automation::ui::actions::ActionsHost as _; @@ -17,7 +18,7 @@ fn step(id: &str, params: Value) -> ActionStep { fn push(app: &mut PhotocraftApp, name: &str, set: Option<&str>, steps: Vec) { let mut action = Action::new(name, steps); action.set = set.map(str::to_owned); - app.session.actions.list.push(action).unwrap(); + app.session.actions_mut().list.push(action).unwrap(); } fn layer_names(app: &PhotocraftApp) -> Vec { @@ -25,7 +26,7 @@ fn layer_names(app: &PhotocraftApp) -> Vec { } fn commands(app: &PhotocraftApp, action: usize) -> Vec { - app.session.actions.list.action(action).unwrap().steps.iter().map(|s| s.command.clone()).collect() + app.session.actions().list.action(action).unwrap().steps.iter().map(|s| s.command.clone()).collect() } /// Two sets, Web listed first: "Resize" (Web) adds a layer "w", "Sharpen" and "Soften" (Retouch) @@ -71,7 +72,7 @@ fn a_function_key_with_shift_and_command_plays_its_action() { let mut app = new_app(); app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); app.session - .actions + .actions_mut() .list .push(Action { name: "Action 1".into(), steps: vec![step("layer.new.layer", json!({}))], disabled: Default::default(), ..Default::default() }) .unwrap(); @@ -117,11 +118,11 @@ fn the_host_reads_the_shortcut_text_the_engine_writes() { push(&mut app, "Keyed", None, vec![]); let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); assign_shortcut(&mut app, "Keyed", &key).unwrap(); - let action = app.session.actions.list.action(0).unwrap(); + let action = app.session.actions().list.action(0).unwrap(); let choice = PhotoActions::new(&app.session, false).shortcut(action); assert_eq!(choice, Some(craft::automation::ui::actions::ShortcutChoice::new(2, true, true))); assign_shortcut(&mut app, "Keyed", "Alt+F2").unwrap(); - let action = app.session.actions.list.action(0).unwrap(); + let action = app.session.actions().list.action(0).unwrap(); assert_eq!(PhotoActions::new(&app.session, false).shortcut(action), None); } @@ -133,12 +134,12 @@ fn step_check_box_excludes_the_step_from_playback_and_batch() { push(&mut app, "Three", None, steps.to_vec()); // PLAN: `ToggleEdit` is non-exhaustive with no constructor outside the framework; the include cell's rule is `set_step_cell`. set_step_cell(&mut app, 0, 1, true, false).unwrap(); - let action = app.session.actions.list.action(0).unwrap(); + let action = app.session.actions().list.action(0).unwrap(); assert!(action.disabled.contains(&1)); assert_eq!(action_steps(action).len(), 2, "Batch and droplets get only the checked steps"); // A cell already at the wanted value runs nothing: the engine command would flip it back. set_step_cell(&mut app, 0, 1, true, false).unwrap(); - assert!(app.session.actions.list.action(0).unwrap().disabled.contains(&1)); + assert!(app.session.actions().list.action(0).unwrap().disabled.contains(&1)); apply_actions_events(&mut app, vec![ActionsEvent::play(0, 0)]); assert_eq!(layer_names(&app), ["A", "C"]); } @@ -159,7 +160,7 @@ fn reordering_moves_a_step_within_its_action_and_an_action_into_a_set() { assert_eq!(commands(&app, 0).len(), 3); assert!(commands(&app, 1).is_empty()); reorder(&mut app, ActionSelection::Action(1), ActionPlace::action(0, Some("Web".into()))).unwrap(); - let list = &app.session.actions.list; + let list = &app.session.actions().list; assert_eq!((list.action(0).unwrap().name.as_str(), list.set_of(0)), ("Second", Some("Web"))); assert_eq!((list.action(1).unwrap().name.as_str(), list.set_of(1)), ("First", None)); } @@ -234,7 +235,7 @@ fn new_action_with_no_set_selected_is_in_no_set() { assert!(app.ui.actions.panel.selected.is_none()); apply_actions_events(&mut app, vec![ActionsEvent::begin_recording(None)]); app.run("actions.stop", json!({})).unwrap(); - let list = &app.session.actions.list; + let list = &app.session.actions().list; assert_eq!((list.actions().len(), list.action(1).unwrap().name.as_str(), list.set_of(1)), (2, "Action 2", None)); } @@ -254,11 +255,11 @@ fn reopening_the_actions_panel_keeps_the_selected_set_and_empty_sets() { assert!(!is_shown(&app, "actions"), "closed"); show_panel(&mut app, "actions", Some(true)).unwrap(); assert!(is_shown(&app, "actions") && is_front(&app, "actions"), "open again"); - assert_eq!(app.session.actions.list.sets(), ["Retouch", "Web", "Print"]); + assert_eq!(app.session.actions().list.sets(), ["Retouch", "Web", "Print"]); assert_eq!(app.ui.actions.panel.selected, Some(ActionSelection::Set("Web".into()))); apply_actions_events(&mut app, vec![ActionsEvent::begin_recording(None)]); app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list.set_of(1), Some("Web")); + assert_eq!(app.session.actions().list.set_of(1), Some("Web")); } /// #7535: with a set's folder row selected and no action, recording makes a new action in that set. @@ -272,7 +273,7 @@ fn start_recording_with_a_set_selected_records_a_new_action_into_it() { assert_eq!(new_action_set(&app).as_deref(), Some("Web")); apply_actions_events(&mut app, vec![ActionsEvent::begin_recording(None)]); app.run("actions.stop", json!({})).unwrap(); - let list = &app.session.actions.list; + let list = &app.session.actions().list; assert_eq!((list.action(1).unwrap().name.as_str(), list.set_of(1)), ("Action 2", Some("Web"))); } diff --git a/crates/ui-egui/src/panels/channels_panel/tests.rs b/crates/ui-egui/src/panels/channels_panel/tests.rs index 7edf035067..8c178e4f51 100644 --- a/crates/ui-egui/src/panels/channels_panel/tests.rs +++ b/crates/ui-egui/src/panels/channels_panel/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use craft::automation::actions::{Action, ActionStep}; use craft::behavior::value::{EditEvent, Mixed}; @@ -163,7 +164,7 @@ fn recording_a_colour_row_click_saves_as_photoshop_select() { app.run("actions.record", json!({"name": "Click"})).unwrap(); target(&mut app, Row::Color(k), false); app.run("actions.stop", json!({})).unwrap(); - let recorded = app.session.actions.list.actions().iter().find(|a| a.name == "Click").unwrap().steps.clone(); + let recorded = app.session.actions().list.actions().iter().find(|a| a.name == "Click").unwrap().steps.clone(); assert_eq!(recorded, vec![ActionStep::new("channel.target", json!({"channel": {"color": name}, "extend": false}))], "{mode}"); } } @@ -209,13 +210,13 @@ fn recorded_colour_clicks_save_as_component_selects() { s.execute("channel.target", json!({"channel": "composite"})).unwrap(); let params = json!({"channel": Row::Color(k).target_reference(color_mode), "extend": false}); assert_eq!(s.execute("channel.target", params.clone()).unwrap(), by_index, "{mode}/{k}"); - s.actions.list.push(Action::new("Click", vec![ActionStep::new("channel.target", params)])).unwrap(); + s.actions_mut().list.push(Action::new("Click", vec![ActionStep::new("channel.target", params)])).unwrap(); let saved = s.execute("actions.save", json!({"action": "Click"})).unwrap_or_else(|e| panic!("{mode}/{k}: {e}")); assert_eq!(saved["skipped"], json!([])); let loaded = s.execute("actions.load", json!({"data": saved["data"]})).unwrap(); assert_eq!(loaded["unsupported"], json!([]), "{mode}/{k}"); let name = photocraft_engine::channel_cmds::color_names(color_mode)[k].to_ascii_lowercase(); - assert_eq!(s.actions.list.actions().last().unwrap().steps, vec![ActionStep::new("channel.target", json!({"channel": {"color": name}}))]); + assert_eq!(s.actions().list.actions().last().unwrap().steps, vec![ActionStep::new("channel.target", json!({"channel": {"color": name}}))]); } } // Rows the colour names can't express keep their reference. diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 4a6f0b42af..185695197b 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -2,6 +2,7 @@ //! `LayerTree` over the active document), `PhotoThumbs` (its thumbnails), the settings and filter //! conversions, and the row menus as entries. +use photocraft_engine::link_watch::LinkWatchExt; use std::collections::HashSet; use std::sync::Arc; diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 3b8cc76f2e..d58277f2fb 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -2,6 +2,7 @@ //! framework's `PresetBrowser` and `PresetPicker`. Rows come from a panel's groups in the panel's folder order; the //! browser's events run as the panel's engine commands, through one mapping for every preset panel (`events`). +use photocraft_engine::presets::PresetsExt; use craft::color_ui::ui::gradient::GradientRamp; use craft::keymap::CommandRef; use craft::theme::Srgba; @@ -348,7 +349,7 @@ fn paint_gradient(cx: &ContentPainterCx, rect: Rect, stops: &[(f32, [f32; 4])]) /// applies it. pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let groups = &app.session.presets.gradients; + let groups = &app.session.presets().gradients; // PLAN: the current-gradient strip above the browser needs a painter component; the browser's selected row shows it. let folders: Vec = groups .iter() @@ -388,7 +389,7 @@ pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let library = held_patterns(app); let folders: Vec = app .session - .presets + .presets() .pattern_groups .iter() .map(|group| Folder { @@ -447,14 +448,14 @@ impl StyleLibrary { /// views keyed by it settle. pub(crate) fn held(app: &mut PhotocraftApp) -> Arc> { let patterns = patterns_stamp(&app.session.patterns); - let stamp = (app.session.presets.revision(), patterns); + let stamp = (app.session.presets().revision(), patterns); if let Some((held, library)) = &app.preset_art.styles && *held == stamp { return Arc::clone(library); } let styles = - app.session.presets.styles.iter().flat_map(|group| group.items.iter()).map(|style| (style_stamp(style, patterns), style.clone())).collect(); + app.session.presets().styles.iter().flat_map(|group| group.items.iter()).map(|style| (style_stamp(style, patterns), style.clone())).collect(); let library = Arc::new(Tracked::new(StyleLibrary { styles, patterns: app.session.patterns.clone() })); app.preset_art.styles = Some((stamp, Arc::clone(&library))); library @@ -494,7 +495,7 @@ pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// The Styles folders: each style group with its styles, keyed and named by the style's name. fn style_folders(app: &PhotocraftApp) -> Vec { - let groups = &app.session.presets.styles; + let groups = &app.session.presets().styles; groups .iter() .map(|group| Folder { name: group.name.clone(), items: group.items.iter().map(|style| (style.name.clone(), style.name.clone())).collect() }) @@ -511,7 +512,7 @@ fn style_files(any: bool, export: Option) -> PresetFiles<'static, /// What the Styles panel menu is built from: whether any style exists, the selected style and the browser's view. fn styles_menu_facts(app: &PhotocraftApp) -> (bool, Option, PresetView) { - let any = app.session.presets.styles.iter().any(|group| !group.items.is_empty()); + let any = app.session.presets().styles.iter().any(|group| !group.items.is_empty()); let selected = app.ui.presets_ui.selected.get(STYLES.id).cloned().map(PresetKey::Item); let view = app.ui.presets_ui.browsers.get(STYLES.id).map_or(PresetView::Grid, |state| state.view); (any, selected, view) @@ -548,7 +549,7 @@ pub(crate) fn styles_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandStat /// view. pub(crate) fn styles_source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { let view = app.ui.presets_ui.browsers.get(STYLES.id).map_or(PresetView::Grid, |state| state.view); - let facts = (app.session.presets.revision(), app.ui.presets_ui.selected.get(STYLES.id), view); + let facts = (app.session.presets().revision(), app.ui.presets_ui.selected.get(STYLES.id), view); crate::app::framework::derived_states(app, name, &facts, || styles_states(app)) } @@ -773,7 +774,7 @@ pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let current = app.ui.tool; let presets: Vec<(String, String)> = app .session - .presets + .presets() .tool_presets .iter() .filter(|preset| !only || Tool::from_name(&preset.tool) == Some(current)) diff --git a/crates/ui-egui/src/panels/preset_browser/tests.rs b/crates/ui-egui/src/panels/preset_browser/tests.rs index 6044d8c57e..9dc5102945 100644 --- a/crates/ui-egui/src/panels/preset_browser/tests.rs +++ b/crates/ui-egui/src/panels/preset_browser/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use super::*; use craft::behavior::{EditEvent, Mixed}; use craft::keymap::Mods; @@ -192,7 +193,7 @@ fn pattern_and_style_pictures_follow_a_scratch_read_error_transition() { /// The flat list of the app's style presets. fn styles(app: &PhotocraftApp) -> Vec { - app.session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect() + app.session.presets().styles.iter().flat_map(|group| group.items.iter().cloned()).collect() } /// #16221: a style's picture key covers its effect values and the patterns' pixels: a same-named style with as many diff --git a/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs b/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs index 3b99335d0d..a67e913e57 100644 --- a/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs +++ b/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs @@ -1,5 +1,6 @@ //! Read-only clone geometry shared by the panel, overlay and source marker. +use photocraft_engine::presets::PresetsExt; use photocraft_engine::presets::clone_source::{Mapping, resolve}; use serde_json::{Value, json}; @@ -24,7 +25,7 @@ pub(crate) fn remember_clone_cursor(app: &mut PhotocraftApp, at: [f64; 2]) -> bo /// Resolve the exact sampling geometry without storing a painting anchor or changing a source. pub fn clone_mapping_at(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option { - let slot = app.session.presets.clone.active(); + let slot = app.session.presets().clone.active(); let source = slot.source?; let start = crate::canvas::paint_tool::stroking(app).filter(|stroke| matches!(stroke.tool, Tool::CloneStamp | Tool::Healing)).map(|stroke| stroke.start); let first = start.or(at).or(slot.last_anchor).or(slot.anchor).unwrap_or(source); diff --git a/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs b/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs index 4bb97f89e1..204c390c3f 100644 --- a/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs +++ b/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use super::*; use crate::canvas::testing::{self, ToolEvent, tool_event}; use photocraft_engine::Session; @@ -30,12 +31,12 @@ fn clone_offset_hover_readout_does_not_establish_a_painting_anchor() { for aligned in [false, true] { let mut app = app(); app.ui.tool_options.clone_aligned = aligned; - let before = app.session.presets.clone.clone(); + let before = app.session.presets().clone.clone(); let revision = app.session.active().unwrap().revision; for at in [[40.0, 30.0], [50.0, 40.0]] { remember_clone_cursor(&mut app, at); assert_eq!(clone_offset_readout(&app), Some([16.0 - at[0], 16.0 - at[1]])); - assert_eq!(app.session.presets.clone, before); + assert_eq!(app.session.presets().clone, before); assert_eq!(app.session.active().unwrap().revision, revision); } } @@ -67,22 +68,22 @@ fn clone_offset_readout_tracks_aligned_mode_without_replacing_its_saved_anchor() stamp(&mut app, [40.0, 30.0]); remember_clone_cursor(&mut app, [50.0, 40.0]); assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); - let original_anchor = app.session.presets.clone.active().anchor; + let original_anchor = app.session.presets().clone.active().anchor; app.ui.tool_options.clone_aligned = false; assert_eq!(clone_offset_readout(&app), Some([-34.0, -24.0])); stamp(&mut app, [50.0, 40.0]); - assert_eq!(app.session.presets.clone.active().anchor, original_anchor); + assert_eq!(app.session.presets().clone.active().anchor, original_anchor); assert_eq!(clone_offset_readout(&app), Some([-34.0, -24.0])); app.ui.tool_options.clone_aligned = true; assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); - assert_eq!(app.session.presets.clone.active().anchor, original_anchor); + assert_eq!(app.session.presets().clone.active().anchor, original_anchor); } /// A slot switch changes the source; a cursor from another destination cannot set its reference. #[test] fn clone_offset_readout_uses_the_selected_slot_and_destination_document() { let mut app = app(); - let source_layer = app.session.presets.clone.active().layer.unwrap(); + let source_layer = app.session.presets().clone.active().layer.unwrap(); remember_clone_cursor(&mut app, [40.0, 30.0]); app.run("cloneSource.set", json!({"index": 2, "source": [20,16], "layer": source_layer})).unwrap(); assert_eq!(clone_offset_readout(&app), Some([-20.0, -14.0])); @@ -121,7 +122,7 @@ fn clone_offsets_share_transformed_sampling_geometry_during_a_stroke() { for (got, want) in sample.into_iter().zip(want) { assert!((got - want).abs() < 1e-8); } - assert!(app.session.presets.clone.active().anchor.is_none()); + assert!(app.session.presets().clone.active().anchor.is_none()); testing::release(&mut app, [44.0, 32.0], egui::Modifiers::NONE); } } @@ -175,6 +176,6 @@ fn clone_marker_follows_the_engine_slot() { testing::press(&mut app, [40.0, 40.0], egui::Modifiers::NONE); assert_eq!(clone_sample_point(&app, Some([50.0, 30.0])), Some([20.0, 0.0])); testing::release(&mut app, [40.0, 40.0], egui::Modifiers::NONE); - app.session.presets.clone.active_mut().anchor = Some([20.0, 20.0]); + app.session.presets_mut().clone.active_mut().anchor = Some([20.0, 20.0]); assert_eq!(clone_sample_point(&app, Some([30.0, 30.0])), Some([20.0, 20.0])); } diff --git a/crates/ui-egui/src/panels/preset_panels/clone_source.rs b/crates/ui-egui/src/panels/preset_panels/clone_source.rs index 2e5143b505..650d8cbb76 100644 --- a/crates/ui-egui/src/panels/preset_panels/clone_source.rs +++ b/crates/ui-egui/src/panels/preset_panels/clone_source.rs @@ -1,6 +1,7 @@ //! The Clone Source panel: five source slots, the slot's offset, scale, rotation and flips, and the overlay options. //! Every edit is a `cloneSource.*` engine command. +use photocraft_engine::presets::PresetsExt; use craft::behavior::{EditEvent, GestureId, Mixed}; use craft::ui::buttons::{Button, ToggleButton}; use craft::ui::choice::Checkbox; @@ -57,7 +58,7 @@ fn toggle(ui: &mut egui::Ui, label: &str, value: bool) -> Option { /// The `cloneSource` registry body. pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let cs = app.session.presets.clone.clone(); + let cs = app.session.presets().clone.clone(); let slot = cs.active().clone(); let mut select = None; Row::new().show(ui, |ui, _| { diff --git a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs index 70f690d557..600478ca9f 100644 --- a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs +++ b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs @@ -73,6 +73,7 @@ pub(crate) fn new_params(app: &PhotocraftApp, tool: Tool) -> Value { #[cfg(test)] mod tests { + use photocraft_engine::presets::PresetsExt; use super::*; fn app() -> Box { @@ -132,7 +133,7 @@ mod tests { let p = new_params(&app, Tool::RectMarquee); let r = app.run("tool.presets.new", p).unwrap(); let name = r["name"].as_str().unwrap().to_string(); - let stored = app.session.presets.tool_presets.iter().find(|t| t.name == name).unwrap().options["toolOptions"].as_object().unwrap().clone(); + let stored = app.session.presets().tool_presets.iter().find(|t| t.name == name).unwrap().options["toolOptions"].as_object().unwrap().clone(); assert_eq!(stored["feather"], json!(5.0)); assert!(stored.keys().all(|k| !k.starts_with("crop") && !k.starts_with("move")), "{stored:?}"); let mut flipped = serde_json::to_value(&app.ui.tool_options).unwrap(); diff --git a/crates/ui-egui/src/panels/swatches_ui.rs b/crates/ui-egui/src/panels/swatches_ui.rs index 81fd58c88a..bb6ef62e73 100644 --- a/crates/ui-egui/src/panels/swatches_ui.rs +++ b/crates/ui-egui/src/panels/swatches_ui.rs @@ -8,6 +8,8 @@ //! Import/Replace (`.aco`, `.act`, `.ase`), Export (`.aco`) and Export for Exchange (`.ase`) and Reset. The panel //! reports `SwatchEdit`s; [`apply_edit`] maps each to one `swatches.*` engine command. +use photocraft_engine::presets::PresetsExt; +use photocraft_engine::color_cmds::ColorExt; use std::ffi::OsStr; use serde_json::{Value, json}; @@ -53,7 +55,7 @@ pub fn use_swatch(app: &mut PhotocraftApp, name: &str, background: bool) { /// The converter that shows CMYK swatches and the colour models behind them: the working CMYK profile's. /// `CmykConverter::new` shares the transforms of a profile, so building it per use costs a lookup. fn cmyk_converter(app: &PhotocraftApp) -> Option { - CmykConverter::new(app.session.color.working(photocraft_doc::ColorMode::Cmyk)).ok() + CmykConverter::new(app.session.color().working(photocraft_doc::ColorMode::Cmyk)).ok() } /// The words of the panel and of its file entries, from the context's environment, so the names a menu command makes @@ -68,7 +70,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let foreground = Srgba::from_array(app.session.tools.foreground); let converter = cmyk_converter(app); let out = { - let mut panel = SwatchesPanel::new(&app.session.presets.swatches, Bind::bound(&mut app.ui.swatches), foreground); + let mut panel = SwatchesPanel::new(&app.session.presets().swatches, Bind::bound(&mut app.ui.swatches), foreground); if let Some(converter) = &converter { panel = panel.cmyk(converter); } @@ -84,7 +86,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// A swatch was clicked: select it and set the foreground, or the background with Alt or Cmd/Ctrl held. pub(crate) fn apply_used(app: &mut PhotocraftApp, at: SwatchAt, background: bool) { - let name = app.session.presets.swatches.get(at.group).and_then(|g| g.entries.get(at.index)).map(|e| e.name.clone()); + let name = app.session.presets().swatches.get(at.group).and_then(|g| g.entries.get(at.index)).map(|e| e.name.clone()); if let Some(name) = name { app.ui.swatches.selected = Some(SwatchKey::Swatch(name.clone())); use_swatch(app, &name, background); @@ -240,12 +242,12 @@ pub(crate) fn panel_rows(_app: &PhotocraftApp) -> Vec { /// The state of each Swatches command: both exports wait for a swatch. pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> { - SwatchesMenu::states(&app.session.presets.swatches).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() + SwatchesMenu::states(&app.session.presets().swatches).into_iter().map(|(command, state)| (CommandRef::from(command), state)).collect() } /// [`command_states`], derived from the presets the swatches live in. pub(crate) fn source_states(app: &PhotocraftApp, name: &'static str) -> std::sync::Arc { - crate::app::framework::derived_states(app, name, &app.session.presets.revision(), || command_states(app)) + crate::app::framework::derived_states(app, name, &app.session.presets().revision(), || command_states(app)) } /// Runs a fired command of the Swatches menu; false for another set's command. @@ -253,7 +255,7 @@ pub(crate) fn run_fired(app: &mut PhotocraftApp, ctx: &egui::Context, command: & let Some(command) = SwatchesCommand::from_ref(command) else { return false }; let foreground = Srgba::from_array(app.session.tools.foreground); let (swatch_words, _) = words(ctx); - let out = SwatchesMenu::run_command(&app.session.presets.swatches, &mut app.ui.swatches, command, foreground, &swatch_words); + let out = SwatchesMenu::run_command(&app.session.presets().swatches, &mut app.ui.swatches, command, foreground, &swatch_words); if let Some(edit) = out.edit { apply_edit(app, edit); } @@ -319,7 +321,7 @@ mod tests { }; let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); let before = steps(&app); - let names: Vec = app.session.presets.swatches[0].entries.iter().take(2).map(|s| s.name.clone()).collect(); + let names: Vec = app.session.presets().swatches[0].entries.iter().take(2).map(|s| s.name.clone()).collect(); use_swatch(&mut app, &names[0], false); let fg = app.session.tools.foreground; assert_eq!(fill(&app), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 1.0))), "{} filled the shape", names[0]); @@ -359,9 +361,9 @@ mod tests { assert_eq!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "foreground untouched (default black)"); assert_eq!(app.ui.swatches.selected, Some(SwatchKey::Swatch("Black".into()))); // The footer's trash deletes the selection. - let n = app.session.presets.swatches[0].entries.len(); + let n = app.session.presets().swatches[0].entries.len(); apply_edit(&mut app, SwatchEdit::delete("Black".into())); - assert_eq!(app.session.presets.swatches[0].entries.len(), n - 1); + assert_eq!(app.session.presets().swatches[0].entries.len(), n - 1); assert_eq!(app.ui.swatches.selected, None); } @@ -371,11 +373,11 @@ mod tests { app.session.tools.foreground = [0.5, 0.25, 1.0, 1.0]; let color = SwatchColor::Rgb([0.5, 0.25, 1.0]); apply_edit(&mut app, SwatchEdit::add(Some("Dark".into()), "Color Swatch 1".into(), color)); - let dark = app.session.presets.swatches.iter().find(|g| g.name == "Dark").unwrap(); + let dark = app.session.presets().swatches.iter().find(|g| g.name == "Dark").unwrap(); assert_eq!(dark.entries.last().unwrap().name, "Color Swatch 1", "into the selected swatch's group"); assert_eq!(app.ui.swatches.rename, Some(SwatchKey::Swatch("Color Swatch 1".into())), "renamed in place"); add_from_picker(&mut app, PickedColor::cmyk(Srgba::rgb(0.0, 1.0, 1.0), [100.0, 0.0, 0.0, 0.0])); - let s = app.session.presets.swatches[0].entries.last().unwrap(); + let s = app.session.presets().swatches[0].entries.last().unwrap(); assert_eq!(s.color, photocraft_engine::presets::swatches::SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0])); } @@ -400,10 +402,10 @@ mod tests { })); assert!(run_fired(&mut app, &ctx, &CommandRef::from(SwatchesCommand::Import))); app.poll_file_dialog(); - assert_eq!(app.session.presets.swatches.last().unwrap().name, "Ocean"); + assert_eq!(app.session.presets().swatches.last().unwrap().name, "Ocean"); assert!(run_fired(&mut app, &ctx, &CommandRef::from(SwatchesCommand::Replace))); app.poll_file_dialog(); - assert_eq!(app.session.presets.swatches.len(), 1, "replace"); + assert_eq!(app.session.presets().swatches.len(), 1, "replace"); assert!(run_fired(&mut app, &ctx, &CommandRef::from(SwatchesCommand::ExportExchange))); app.poll_file_dialog(); let written = written.lock().unwrap(); @@ -416,14 +418,14 @@ mod tests { #[test] fn dragging_a_group_header_reorders_and_persists() { let mut app = app(); - let names: Vec = app.session.presets.swatches.iter().map(|g| g.name.clone()).collect(); + let names: Vec = app.session.presets().swatches.iter().map(|g| g.name.clone()).collect(); assert!(names.len() >= 2, "the default library has folders: {names:?}"); let last = names.last().unwrap().clone(); - let rev = app.session.presets.revision(); + let rev = app.session.presets().revision(); apply_edit(&mut app, SwatchEdit::move_group(last.clone(), 0)); - let order: Vec = app.session.presets.swatches.iter().map(|g| g.name.clone()).collect(); + let order: Vec = app.session.presets().swatches.iter().map(|g| g.name.clone()).collect(); assert_eq!(order[0], last, "the dragged folder moved to the front: {order:?}"); assert_eq!(order[1], names[0]); - assert_ne!(app.session.presets.revision(), rev, "the library saves its new order"); + assert_ne!(app.session.presets().revision(), rev, "the library saves its new order"); } } diff --git a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs index 1968305985..97c049658b 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs @@ -198,6 +198,7 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { + use photocraft_engine::actions_cmds::ActionsExt; use craft::ui::dialog::StackDialog as _; use photocraft_engine::actions_cmds::ActionStep; @@ -293,7 +294,7 @@ mod tests { app.run("actions.stop", json!({})).unwrap(); assert!(app.ui.type_panels.spell.is_none()); assert!(!app.framework.dialogs.is_open::()); - let action = app.session.actions.list.action(0).unwrap(); + let action = app.session.actions().list.action(0).unwrap(); assert_eq!(action.steps, vec![ActionStep::new("edit.checkSpelling", json!({"allLayers": false}))]); assert_eq!(action.dialogs.iter().copied().collect::>(), [0]); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/save.rs b/crates/ui-egui/src/prefs/prefs_ui/save.rs index 4843231752..e84ac6fd3e 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/save.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/save.rs @@ -1,3 +1,5 @@ +use photocraft_engine::prefs::SavedPrefsExt; +use photocraft_engine::link_watch::LinkWatchExt; use std::time::Instant; use craft::platform::autosave::{AutosaveDoc, interval_for_minutes}; diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs index 8ede607906..a457605526 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs @@ -3,6 +3,7 @@ //! dialog's recording, conflict bar and undo are craft-menu's own (its trials); these tests drive //! the session the app wraps around it. +use photocraft_engine::prefs::SavedPrefsExt; use craft::keymap::{Binding, CommandRef, Policy}; use egui::{Event, Key, Modifiers}; use egui_kittest::Harness; diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index cf5fea05e8..fd70a45a51 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -8,6 +8,7 @@ //! //! The Toolbar tab is not here: Edit › Toolbar opens the toolbar drawer. +use photocraft_engine::actions_cmds::ActionsExt; use std::collections::{BTreeMap, BTreeSet}; use craft::keymap::import::kys; @@ -82,7 +83,7 @@ pub(crate) fn profiles_of(prefs: &Preferences) -> Profiles { pub(crate) fn draft_keymap(app: &PhotocraftApp) -> Keymap { let platform = windows::os_of(app.ctx()); // The runtime catalog's held rows while they are current; built here before the first frame holds them. - let rows = match app.framework.catalog_rows_at(app.session.actions.list.revision()) { + let rows = match app.framework.catalog_rows_at(app.session.actions().list.revision()) { Some(rows) => rows.to_vec(), None => crate::shortcut_dispatch::command_rows(app), }; diff --git a/crates/ui-egui/src/prefs/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs index 901995dfae..928266d63f 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/startup.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/startup.rs @@ -1,3 +1,4 @@ +use photocraft_engine::prefs::SavedPrefsExt; use photocraft_engine::preset_store::PresetStoreExt; use super::{JobEvent, JobOutcome, PhotocraftApp, Started, Value, json, prefs}; diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 548e942aed..0c51975a5d 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::prefs::SavedPrefsExt; use super::appearance::{display_scale, selected_theme}; use super::*; use crate::theme::{AppTheme, Tokens}; diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index cd6d2a8434..2c4d3677f8 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -162,6 +162,7 @@ pub(crate) fn run_import(app: &mut PhotocraftApp, cmd: &str, what: &str, stem: & #[cfg(test)] mod tests { + use photocraft_engine::presets::PresetsExt; use std::sync::Arc; use craft::host::{PickKind, Picked, ScriptedFiles}; @@ -255,7 +256,7 @@ mod tests { GrdGradient { name: "Ember".into(), stops: vec![stop(0.0, GrdColor::Foreground), stop(1.0, GrdColor::Rgb([1.0, 0.0, 0.0]))], ..Default::default() }; let grd = write(&[ember]); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let groups = |app: &PhotocraftApp, g: &str| app.session.presets.gradients.iter().filter(|x| x.name == g).count(); + let groups = |app: &PhotocraftApp, g: &str| app.session.presets().gradients.iter().filter(|x| x.name == g).count(); open(&mut app, "Fire.grd", &grd).unwrap().unwrap(); assert_eq!(groups(&app, "Fire"), 1); assert!(prompt(&app).is_none(), "a new group imports without asking"); diff --git a/crates/ui-egui/src/profile_open_tests.rs b/crates/ui-egui/src/profile_open_tests.rs index 50e3586e18..75ec8c3c19 100644 --- a/crates/ui-egui/src/profile_open_tests.rs +++ b/crates/ui-egui/src/profile_open_tests.rs @@ -3,6 +3,7 @@ //! Mismatch prompt at a time, naming its file, before that file opens; OK opens it and asks about //! the next; Cancel opens neither it nor the files still to come. +use photocraft_engine::color_cmds::ColorExt; use crate::{PhotocraftApp, Services}; use craft::color_ui::ui::ProfileMismatchDialog; use craft::ui::dialog::DialogId; @@ -225,7 +226,7 @@ fn remember_answers_the_waiting_files_and_stops_asking() { for name in ["a.png", "b.png", "c.png"] { assert_eq!(profile(&h, name).as_deref(), Some("sRGB IEC61966-2.1"), "background {background}: {name} converted"); } - let settings = &h.state().session.color.settings; + let settings = &h.state().session.color().settings; assert_eq!(settings.policy(photocraft_doc::ColorMode::Rgb), photocraft_engine::color_cmds::Policy::Convert); assert!(!settings.ask_on_mismatch, "background {background}"); h.state_mut().open_file("/pics/d.png", &adobe_png()).unwrap(); @@ -242,5 +243,5 @@ fn without_remember_the_next_file_still_asks() { open_three(&mut h); answer(&mut h, CONVERT); assert!(h.state().framework.dialogs.is_open::(), "the next file asks"); - assert!(h.state().session.color.settings.ask_on_mismatch); + assert!(h.state().session.color().settings.ask_on_mismatch); } diff --git a/crates/ui-egui/src/toolbar_custom_group_layout_tests.rs b/crates/ui-egui/src/toolbar_custom_group_layout_tests.rs index 0b0b629a19..c5c8503f02 100644 --- a/crates/ui-egui/src/toolbar_custom_group_layout_tests.rs +++ b/crates/ui-egui/src/toolbar_custom_group_layout_tests.rs @@ -3,6 +3,7 @@ //! Shift+letter steps through a key's tools in layout order across slots, an empty toolbar is //! allowed, `reset` brings back the default layout, and older settings still load. +use photocraft_engine::prefs::SavedPrefsExt; use egui::{Key, Modifiers, vec2}; use egui_kittest::kittest::Queryable; use photocraft_engine::prefs::{DEFAULT_TOOLBAR, Preferences, ToolbarCustomization}; diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index e0a0006db7..3d9d6918f4 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -7,6 +7,7 @@ //! [`bars`], the two panels in [`log_panel`] and [`notes_panel`], the dialogs in [`dialogs`], and the note alerts in //! [`note_alerts`]. +use photocraft_engine::color_cmds::ColorExt; use craft::behavior::Selection; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -114,7 +115,7 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { // A check item with no document too: an item's kind never changes (native menus). let kind = id.strip_prefix("view.proofSetup.").and_then(photocraft_engine::proof_sim::ProofKind::from_id)?; let Some(d) = app.session.active() else { return Some(false) }; - let pv = app.session.color.proof(d.doc.id); + let pv = app.session.color().proof(d.doc.id); Some(pv.enabled && pv.setup.kind == kind) } } diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 9312e8920a..a314ef3730 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -12,6 +12,7 @@ //! hidden target layer answers its click with the reference's alert rather than the status line //! (#12033). +use photocraft_engine::color_cmds::ColorExt; use egui::{Align2, Color32, CornerRadius, FontId, Pos2, RichText, Stroke, pos2, vec2}; use photocraft_doc::{Document, Ruler}; use serde::{Deserialize, Serialize}; @@ -124,7 +125,7 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { // A check item with no document too: an item's kind never changes (native menus). let kind = id.strip_prefix("view.proofSetup.").and_then(photocraft_engine::proof_sim::ProofKind::from_id)?; let Some(d) = app.session.active() else { return Some(false) }; - let pv = app.session.color.proof(d.doc.id); + let pv = app.session.color().proof(d.doc.id); Some(pv.enabled && pv.setup.kind == kind) } } diff --git a/crates/ui-egui/src/tools/crop_presets.rs b/crates/ui-egui/src/tools/crop_presets.rs index 0db65d4497..a6ebf25b66 100644 --- a/crates/ui-egui/src/tools/crop_presets.rs +++ b/crates/ui-egui/src/tools/crop_presets.rs @@ -13,6 +13,7 @@ //! - Delete Crop Preset… lists the saved crop presets in a multi-select list; OK deletes the //! selected ones (`tool.presets.edit` delete). Nothing opens with no saved crop preset. +use photocraft_engine::presets::PresetsExt; use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::draw::ui::crop::{CropSettings, CropUserPreset}; use craft::ui::contract::{Bind, Show as _, ShowCollection as _}; @@ -46,7 +47,7 @@ fn label(text: impl ToString) -> Label { /// `CropSettings::choose` use: every caller passes this same list. pub fn user_presets(app: &PhotocraftApp) -> Vec { app.session - .presets + .presets() .tool_presets .iter() .filter(|p| Tool::from_name(&p.tool) == Some(Tool::Crop)) @@ -295,8 +296,8 @@ mod tests { assert_eq!(names(&app), ["Poster", "3 : 2"]); // An old-format preset lists and applies; junk options are not listed. - app.session.presets.tool_presets.push(ToolPreset { name: "Old".into(), tool: "crop".into(), options: json!({"toolOptions": {"crop_ratio": "2:5"}}) }); - app.session.presets.tool_presets.push(ToolPreset { name: "Junk".into(), tool: "crop".into(), options: json!({"toolOptions": {"crop": {"ratio": 5}}}) }); + app.session.presets_mut().tool_presets.push(ToolPreset { name: "Old".into(), tool: "crop".into(), options: json!({"toolOptions": {"crop_ratio": "2:5"}}) }); + app.session.presets_mut().tool_presets.push(ToolPreset { name: "Junk".into(), tool: "crop".into(), options: json!({"toolOptions": {"crop": {"ratio": 5}}}) }); assert_eq!(names(&app), ["Poster", "3 : 2", "Old"]); crate::prefs_ui::save_preferences(&mut app).unwrap(); @@ -322,7 +323,7 @@ mod tests { confirm(&mut fresh, &ctx, id).unwrap(); assert_eq!(names(&fresh), ["3 : 2", "Old"]); // Other tool presets are untouched. - assert!(fresh.session.presets.tool_presets.iter().any(|p| p.name == "Soft Round 100 px")); + assert!(fresh.session.presets().tool_presets.iter().any(|p| p.name == "Soft Round 100 px")); } #[test] diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 11d8883160..89a3756277 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::actions_cmds::ActionsExt; use super as crop_ui; use crate::PhotocraftApp; use crate::canvas::{ToolEvent, tool_event}; @@ -183,7 +184,7 @@ fn edit_undo_steps_the_crop_box_not_the_document() { assert_eq!(crop_ui::is_enabled(&app, "edit.redo"), Some(false), "no box step to redo"); let ctx = crate::canvas::testing::ctx(&app); crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); - assert!(app.session.actions.list.library_undo().is_some(), "the library edit remains available"); + assert!(app.session.actions().list.library_undo().is_some(), "the library edit remains available"); assert_eq!(crop_ui::frame(&app), Some(before), "undo restores the box"); assert_eq!(app.session.active().unwrap().history.past_len(), doc_steps, "the document is untouched"); app.run("edit.redo", json!({})).unwrap(); diff --git a/crates/ui-egui/src/tools/gradient_ui/bar.rs b/crates/ui-egui/src/tools/gradient_ui/bar.rs index 44a75278d9..a22b84d07e 100644 --- a/crates/ui-egui/src/tools/gradient_ui/bar.rs +++ b/crates/ui-egui/src/tools/gradient_ui/bar.rs @@ -1,6 +1,7 @@ //! The Gradient tool's options-bar cells: Mode (live Gradient or Classic gradient), the gradient swatch, the style, //! and for the Classic gradient the blend mode and Opacity, then Reverse and Dither. +use photocraft_engine::presets::PresetsExt; use craft::draw::ui::gradient::{GradientFillWords, GradientStyle, GradientSwatch}; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel}; @@ -42,7 +43,7 @@ pub(crate) fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // A selected gradient fill layer is edited live whatever the stored choice: the Mode cell reads Gradient and is greyed. let locked_live = fill_layer_active(app); let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let tool_stops = stops::of_preset(&app.session.presets.gradient, fg, bg); + let tool_stops = stops::of_preset(&app.session.presets().gradient, fg, bg); let sampler = stops::sampler(fg, bg); let words = Env::of(ui).words::(); let styles: Vec> = GradientStyle::ALL.iter().map(|style| Entry::new(*style, style.label(&words)).icon(style.icon())).collect(); diff --git a/crates/ui-egui/src/tools/gradient_ui/editor.rs b/crates/ui-egui/src/tools/gradient_ui/editor.rs index 67b23a0a1d..887d73a5aa 100644 --- a/crates/ui-egui/src/tools/gradient_ui/editor.rs +++ b/crates/ui-egui/src/tools/gradient_ui/editor.rs @@ -1,6 +1,7 @@ //! The Gradient Editor panel (`gradientEditor`). With a gradient fill layer selected it shows that layer's gradient //! (the Properties rows); without one it edits the gradient the Gradient tool paints with. +use photocraft_engine::presets::PresetsExt; use craft::behavior::EditEvent; // The stop bar is craft-color's. use craft::color_ui::ui::gradient::{GradientEditor, StopRef, StopRows, StopRules}; @@ -39,7 +40,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// pass in one frame gets no pointer input, so its editor reports no event and applies nothing again. fn tool_gradient(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let mut shown = app.gradient.preset.clone().unwrap_or_else(|| stops::of_preset(&app.session.presets.gradient, fg, bg)); + let mut shown = app.gradient.preset.clone().unwrap_or_else(|| stops::of_preset(&app.session.presets().gradient, fg, bg)); let sampler = stops::sampler(fg, bg); let sampled = (0..shown.color.len()).find_map(|i| crate::screen_picker::take(app, ("gradient-editor", i))); diff --git a/crates/ui-egui/src/tools/gradient_ui/tests.rs b/crates/ui-egui/src/tools/gradient_ui/tests.rs index b6ad81af6a..93c7faaae7 100644 --- a/crates/ui-egui/src/tools/gradient_ui/tests.rs +++ b/crates/ui-egui/src/tools/gradient_ui/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use super::*; use crate::canvas::ToolEvent; @@ -148,11 +149,11 @@ fn preview_shows_the_drag_before_commit() { #[test] fn the_editor_edits_the_current_gradient_without_a_layer() { let mut h = super::editor_tests::editor(false); - let before = h.state().session.presets.gradient.stops.len(); + let before = h.state().session.presets().gradient.stops.len(); let doc = h.state().session.active().unwrap().doc.clone(); let history = h.state().session.active().unwrap().history.past_len(); super::editor_tests::add_stop(&mut h); - assert_eq!(h.state().session.presets.gradient.stops.len(), before + 1, "the stop went into the current gradient"); + assert_eq!(h.state().session.presets().gradient.stops.len(), before + 1, "the stop went into the current gradient"); assert_eq!(h.state().session.active().unwrap().doc, doc, "the document is untouched"); assert_eq!(h.state().session.active().unwrap().history.past_len(), history, "no history step"); } diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 6a665c346a..2ab9a34f5b 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -18,6 +18,7 @@ //! a tool switch and selection-only changes; it analyses nothing until Refresh is clicked //! ([`refresh`]): not on the first hover, on another document, or after a pixel edit. +use photocraft_engine::smartselect_cmds::SmartSelectExt; use std::sync::Arc; use craft::behavior::kurbo::{Point, Rect}; @@ -153,7 +154,7 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo Ok(found) => { if let Some(r) = found { if photocraft_engine::layer_multi_cmds::same_pixels(&job.doc, &doc_arc) { - app.session.object_finder.insert(&doc_arc, target, Arc::clone(&r)); + app.session.object_finder_mut().insert(&doc_arc, target, Arc::clone(&r)); let mask = mask_of(&mut app.texture_serials, &r); f.mask = Some((r, mask)); } @@ -171,7 +172,7 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo } let inside = |r: &Region| r.at(px[0], px[1]) >= 0.5; if !f.shown.as_deref().is_some_and(inside) { - f.shown = app.session.object_finder.lookup(&doc_arc, target, at[0] as f32, at[1] as f32); + f.shown = app.session.object_finder().lookup(&doc_arc, target, at[0] as f32, at[1] as f32); } match &f.shown { Some(r) if !f.mask.as_ref().is_some_and(|(m, _)| Arc::ptr_eq(m, r)) => f.mask = Some((Arc::clone(r), mask_of(&mut app.texture_serials, r))), @@ -343,7 +344,7 @@ mod tests { // Elsewhere on the same object: served from the cache, no new lookup. let u = update(&mut app, Some([120.0, 90.0]), false, 200.0, &ctx); assert!(u.shown.is_some_and(|s| Arc::ptr_eq(&s, &r)) && !u.busy); - assert_eq!(app.session.object_finder.len(), 1); + assert_eq!(app.session.object_finder().len(), 1); // The background highlights nothing. assert!(hover(&mut app, [4.0, 4.0]).shown.is_none()); } diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index f08ddfd715..356cb1ca36 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -3,6 +3,7 @@ //! selection tools (Quick Selection, Object Selection): gesture → engine command, options bars, //! and the clone-source marker point. The options bars are in [`bar`]. +use photocraft_engine::presets::PresetsExt; use craft::keymap::Mods; use serde_json::{Value, json}; @@ -42,7 +43,7 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { // the aligned pairing and applies the slot's scale/rotation/flip. An empty slot refuses to // paint, as with no source at all: `ui.clone_source` / `ui.clone_offset` carry no document, // so falling back to them would read another document's coordinates from this one's pixels. - app.session.presets.clone.active().source?; + app.session.presets().clone.active().source?; Some(p) } @@ -704,7 +705,7 @@ pub fn source_marker_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option< if !matches!(app.ui.tool, Tool::CloneStamp | Tool::Healing) { return None; } - let slot = app.session.presets.clone.active(); + let slot = app.session.presets().clone.active(); if slot.document_closed || slot.document.is_some_and(|id| app.session.active().is_none_or(|st| st.doc.id != id)) { return None; } diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/heal.rs b/crates/ui-egui/src/tools/retouch_ui/bar/heal.rs index 0d3e036c47..f3bb700c12 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/heal.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/heal.rs @@ -1,6 +1,7 @@ //! The Retouch options bar's healing family: Remove, Patch, Content-Aware Move, Spot Healing, Clone Stamp and //! Healing Brush. Also holds the cells the toning and selection families share. +use photocraft_engine::presets::PresetsExt; use craft::behavior::Value; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; @@ -141,7 +142,7 @@ pub(super) fn spot_healing(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option /// The options of Clone Stamp and Healing Brush. In an Indexed Color document the Clone Stamp's /// Sample greys at Current Layer and keeps the stored choice for other documents (#12613). pub(super) fn clone(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option { - let source_unset = app.session.presets.clone.active().source.is_none(); + let source_unset = app.session.presets().clone.active().source.is_none(); let indexed = crate::retouch_ui::clone_stamp_indexed(app); let o = &mut app.ui.tool_options; check(ui, tl!("Aligned"), &mut o.clone_aligned, true, None); diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index 5bf39d290a..bf1962b45c 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -1,5 +1,6 @@ //! Shape toolbar edits share the engine commands used by the Properties panel. +use photocraft_engine::presets::PresetsExt; use craft::behavior::{EditEvent, Mixed}; use craft::draw::stroke::StrokeStyle; use craft::draw::ui::shape::{ShapeAppearance, ShapeBar, ShapeChange, ShapePaint, ShapeToolSettings, VectorMode}; @@ -211,11 +212,11 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool let sampled = [ShapePaint::Fill, ShapePaint::Stroke].into_iter().find_map(|p| crate::screen_picker::take(app, ("shape-bar", p)).map(|c| (p, c))); let recent_colors: Vec = crate::paint_picker::recent_colors(&app.session).into_iter().map(|c| srgba([c[0], c[1], c[2], 1.0])).collect(); - let groups = ShapeGradients::groups_of(&app.session.presets.gradients, fg, bg); - let gradients = ShapeGradients { groups, current: &app.session.presets.gradient, recent: &mut app.ui.recent_gradients, fg, bg }; + let groups = ShapeGradients::groups_of(&app.session.presets().gradients, fg, bg); + let gradients = ShapeGradients { groups, current: &app.session.presets().gradient, recent: &mut app.ui.recent_gradients, fg, bg }; let current = [fill.clone(), stroke.as_ref().map(|s| s.paint.clone())]; let mut library = - ChipLibrary::new(&recent_colors, &app.session.presets.swatches, &mut app.ui.paint_folders, gradients, &mut app.ui.shape_gradient_state, current); + ChipLibrary::new(&recent_colors, &app.session.presets().swatches, &mut app.ui.paint_folders, gradients, &mut app.ui.shape_gradient_state, current); let out = ShapeBar::new(kind, &settings, &appearance, ppi) .paint(paint) .fallbacks(srgba(fg), srgba(bg)) diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 2e05332523..d9e5c9e5dd 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1,3 +1,4 @@ +use photocraft_engine::color_cmds::ColorExt; use super::*; use craft::behavior::geometry::quad::BoxState; use craft::behavior::kurbo::{Point, Rect, Vec2}; @@ -1634,9 +1635,9 @@ fn transform_preview_preserves_displayed_profile_colors() { Ok(()) }) .unwrap(); - app.session.color.settings.monitor_profile = monitor.into(); + app.session.color_mut().settings.monitor_profile = monitor.into(); let st = app.session.active().unwrap(); - let display = app.session.color.canvas_display(&st.doc).unwrap(); + let display = app.session.color().canvas_display(&st.doc).unwrap(); assert_eq!(!display.is_identity(), wide_gamut || monitor != "srgb"); let composite = photocraft_compose::render(&st.doc, bounds); let expected = crate::canvas::display_image(Some(&display), &composite); @@ -1683,7 +1684,7 @@ fn preview_applies_the_linked_mask() { #[test] fn transform_selection_tint_is_not_document_color() { let mut app = app_with_square(8, photocraft_geom::Rect::new(0, 0, 8, 8)); - app.session.color.settings.monitor_profile = "display-p3".into(); + app.session.color_mut().settings.monitor_profile = "display-p3".into(); app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); let ctx = gpu_ctx(); begin_selection(&mut app, &ctx).unwrap(); @@ -1708,9 +1709,9 @@ fn transform_covering_layer_uses_the_same_monitor_profile() { Ok(()) }) .unwrap(); - app.session.color.settings.monitor_profile = "display-p3".into(); + app.session.color_mut().settings.monitor_profile = "display-p3".into(); let doc = app.session.active().unwrap().doc.clone(); - let display = app.session.color.canvas_display(&doc).unwrap(); + let display = app.session.color().canvas_display(&doc).unwrap(); let expected = [lower, upper].map(|id| { let mut solo = (*doc).clone(); for layer in &mut solo.layers { diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index e0ad6ae1ed..0b2e22f892 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -3,6 +3,7 @@ //! view flip and layer transform; size edits apply at layer and selection scope, for native and //! PSD-round-tripped text, as one history step per drag. +use photocraft_engine::color_cmds::ColorExt; use crate::app::framework::BuildApp; use craft::keymap::Mods; use craft::text::ui::character::{CharacterControls, ParagraphControls}; diff --git a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs index bbed5a4bee..030d51342a 100644 --- a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs @@ -3,6 +3,7 @@ //! Horizontal Type Mask tool keeps the horizontal buttons (not measured); the Vertical Type Mask //! tool's are in `vertical_mask_align_buttons_tests` (#12088). +use photocraft_engine::color_cmds::ColorExt; use crate::app::framework::BuildApp; use egui::accesskit::Toggled; diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index face470c71..e48afffbc4 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -1,3 +1,4 @@ +use photocraft_engine::presets::PresetsExt; use craft::behavior::EditEvent; use craft::color_ui::ui::Paint; use craft::draw::ui::pen::PathOptionsPopover; @@ -451,12 +452,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra let was_linked = app.ui.arrow_default == Some(target); let mut linked = was_linked; let recent_colors: Vec = crate::paint_picker::recent_colors(&app.session).into_iter().map(|c| Srgba::new(c[0], c[1], c[2], 1.0)).collect(); - let groups = crate::shape_gradient_ui::ShapeGradients::groups_of(&app.session.presets.gradients, fg, bg); - let gradients = crate::shape_gradient_ui::ShapeGradients { groups, current: &app.session.presets.gradient, recent: &mut app.ui.recent_gradients, fg, bg }; + let groups = crate::shape_gradient_ui::ShapeGradients::groups_of(&app.session.presets().gradients, fg, bg); + let gradients = crate::shape_gradient_ui::ShapeGradients { groups, current: &app.session.presets().gradient, recent: &mut app.ui.recent_gradients, fg, bg }; let current = [sh.fill.clone(), sh.stroke.as_ref().map(|s| s.paint.clone())]; let mut library = crate::shape_paint_ui::ChipLibrary::new( &recent_colors, - &app.session.presets.swatches, + &app.session.presets().swatches, &mut app.ui.paint_folders, gradients, &mut app.ui.shape_gradient_state, diff --git a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs index 0f3cd40906..3994d808b0 100644 --- a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs @@ -1,4 +1,5 @@ //! Pointer, keyboard, colour precision and history regressions for shape appearance controls. +use photocraft_engine::presets::PresetsExt; use super::*; use crate::shape_options::set_tool_paint; use crate::shape_paint_ui::color_of; @@ -511,7 +512,7 @@ fn stroke_swatch_gradient_tab_sets_the_next_shapes_stroke() { assert_eq!(h.state().ui.tool_options.stroke_width, 3.0, "choosing a gradient enables the stroke"); h.get_by_label("Blue 01").click(); h.run_steps(2); - let presets = h.state().session.presets.gradients.clone(); + let presets = h.state().session.presets().gradients.clone(); let blue = presets.iter().flat_map(|g| &g.items).find(|p| p.name == "Blue 01").unwrap(); let (fg, bg) = (h.state().session.tools.foreground, h.state().session.tools.background); let blue_stops = blue.fill_stops(fg, bg).0; diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs index f9be1ff1d4..5ccd685ff1 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs @@ -1,6 +1,7 @@ //! Undo back to where a Pen path was finished gives the path back to the Pen, and Redo finishes //! it again (`pen_resume`). +use photocraft_engine::actions_cmds::ActionsExt; use super::*; use crate::canvas::testing; @@ -615,7 +616,7 @@ fn failed_pen_draft_after_tool_switch_leaves_library_undo_to_each_entrypoint() { app.run("edit.undo", json!({})).unwrap(); } } - assert_eq!(app.session.actions.list.sets(), ["Keep"], "{tool:?}, {entry}: the library was restored"); + assert_eq!(app.session.actions().list.sets(), ["Keep"], "{tool:?}, {entry}: the library was restored"); assert_eq!(app.ui.pen, draft, "{tool:?}, {entry}: hidden anchors are untouched"); assert_eq!(app.session.active().unwrap().history.past_len(), history); } @@ -636,7 +637,7 @@ fn active_failed_pen_drafts_keep_anchor_undo_and_library_pending() { menu(&mut app, "edit.undo"); } assert_eq!(app.ui.pen.as_ref().unwrap().draft.knots.len(), 1, "{tool:?}: the active editor owns Undo"); - assert!(app.session.actions.list.sets().is_empty(), "the library Undo is still pending"); + assert!(app.session.actions().list.sets().is_empty(), "the library Undo is still pending"); assert_eq!(app.session.active().unwrap().history.past_len(), history); } } @@ -654,7 +655,7 @@ fn hidden_failed_pen_drafts_do_not_take_document_history_steps() { assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the document edit was undone"); assert_eq!(app.ui.pen, draft, "the retained draft was not edited"); assert!(!crate::menus::is_enabled(&app, "history.stepBackward"), "hidden anchors cannot enable another History step"); - assert!(app.session.actions.list.sets().is_empty(), "History does not consume the library Undo"); + assert!(app.session.actions().list.sets().is_empty(), "History does not consume the library Undo"); } } @@ -708,13 +709,13 @@ fn failed_freeform_drafts_keep_same_tool_anchor_undo() { _ => menu(&mut app, "history.stepBackward"), } assert_eq!(app.ui.pen.as_ref().unwrap().triples(), draft.triples()[..2].to_vec(), "{entry}: retain the old fitted-anchor Undo"); - assert!(app.session.actions.list.sets().is_empty(), "the library Undo stays pending"); + assert!(app.session.actions().list.sets().is_empty(), "the library Undo stays pending"); assert_eq!(app.session.active().unwrap().history.past_len(), history); switch_tool(&mut app, Tool::Brush); let remaining = app.ui.pen.clone(); assert_eq!(crate::actions::library::edit_undo_label(&app), Some("Undo Clear All Actions")); menu(&mut app, "edit.undo"); - assert_eq!(app.session.actions.list.sets(), ["Keep"]); + assert_eq!(app.session.actions().list.sets(), ["Keep"]); assert_eq!(app.ui.pen, remaining, "another tool does not edit the failed Freeform draft"); } } @@ -735,7 +736,7 @@ fn freeform_selection_does_not_claim_a_failed_pen_or_curvature_draft() { } else { menu(&mut app, "edit.undo"); } - assert_eq!(app.session.actions.list.sets(), ["Keep"], "{tool:?}: undo the library, not foreign anchors"); + assert_eq!(app.session.actions().list.sets(), ["Keep"], "{tool:?}: undo the library, not foreign anchors"); assert_eq!(app.ui.pen, draft); assert_eq!(app.session.active().unwrap().history.past_len(), history); } diff --git a/crates/ui-egui/src/transform_fx_tests.rs b/crates/ui-egui/src/transform_fx_tests.rs index 88a9dd2d4d..c6ec95e208 100644 --- a/crates/ui-egui/src/transform_fx_tests.rs +++ b/crates/ui-egui/src/transform_fx_tests.rs @@ -2,6 +2,7 @@ //! canvas: at every bit depth and colour mode, for pixel layers and groups, following edits made //! while the box is open, and matching what the commit leaves. +use photocraft_engine::color_cmds::ColorExt; use egui::ColorImage; use photocraft_doc::{Layer, LayerId}; use serde_json::json; @@ -71,7 +72,7 @@ fn styled_texture_tracks_monitor_changes_without_recoloring_effect_inputs() { begin(&mut app); let raw = composite(&app, 1.0).unwrap().0; for monitor in ["srgb", "display-p3", "srgb"] { - app.session.color.settings.monitor_profile = monitor.into(); + app.session.color_mut().settings.monitor_profile = monitor.into(); crate::canvas::testing::frame(&mut app); assert_eq!(composite(&app, 1.0).unwrap().0.pixels, raw.pixels, "monitor={monitor}: effects still use document colors"); } diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 05fcfe7c2d..d901911dd0 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -2,6 +2,7 @@ //! drag one step) and never reach the document under the open box; and the //! handles have a generous grab radius, so a press just off a corner scales instead of rotating. +use photocraft_engine::actions_cmds::ActionsExt; use egui::{Key, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; use serde_json::json; @@ -138,9 +139,9 @@ fn undo_steps_back_through_the_transform_not_the_document() { // Outside the transform, ⌘Z is the document's Undo again. key(&mut h, Modifiers::COMMAND, Key::Z); assert_eq!(width(&h), 100, "the committed transform is undone"); - assert_eq!(h.state().session.actions.list.sets().len(), 1); + assert_eq!(h.state().session.actions().list.sets().len(), 1); key(&mut h, Modifiers::COMMAND, Key::Z); - assert!(h.state().session.actions.list.sets().is_empty(), "the preceding library edit is next"); + assert!(h.state().session.actions().list.sets().is_empty(), "the preceding library edit is next"); } /// `engine.execute` over the control channel (and MCP, which goes through it) as a programmatic diff --git a/crates/ui-egui/tests/it/actions_duplicate.rs b/crates/ui-egui/tests/it/actions_duplicate.rs index c3ae109d3d..70647e8475 100644 --- a/crates/ui-egui/tests/it/actions_duplicate.rs +++ b/crates/ui-egui/tests/it/actions_duplicate.rs @@ -1,4 +1,5 @@ //! The panel duplicates the selected action/step and keeps its new row selected. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::ActionSelection; use egui_kittest::Harness; use photocraft_engine::{ @@ -28,7 +29,7 @@ fn duplicate_menu_selects_the_new_action_and_then_the_new_step() { let mut a = Action::new("Source", vec![ActionStep::new("select.all", json!({}))]); a.disabled.insert(0); a.dialogs.insert(0); - app.session.actions.list.push(a).unwrap(); + app.session.actions_mut().list.push(a).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); app.ui.actions.panel.expanded.insert("Source".into()); let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(360.0, 460.0)).build_ui_state(|ui, app| dialogs::run(app, ui), app); @@ -41,7 +42,7 @@ fn duplicate_menu_selects_the_new_action_and_then_the_new_step() { h.run_steps(3); }; fire(&mut h); - let list = &h.state().session.actions.list; + let list = &h.state().session.actions().list; assert_eq!(list.actions().len(), 2); assert_eq!(list.action(1).unwrap().name, "Source copy"); assert_eq!(h.state().ui.actions.panel.selected, Some(ActionSelection::Action(1))); @@ -49,7 +50,7 @@ fn duplicate_menu_selects_the_new_action_and_then_the_new_step() { h.state_mut().ui.actions.panel.selected = Some(ActionSelection::Step(1, 0)); fire(&mut h); assert_eq!(h.state().ui.actions.panel.selected, Some(ActionSelection::Step(1, 1))); - let copied = h.state().session.actions.list.action(1).unwrap(); + let copied = h.state().session.actions().list.action(1).unwrap(); assert_eq!(copied.steps.len(), 2); assert_eq!(copied.disabled.iter().copied().collect::>(), [0, 1]); assert_eq!(copied.dialogs.iter().copied().collect::>(), [0, 1]); @@ -59,15 +60,15 @@ fn duplicate_menu_selects_the_new_action_and_then_the_new_step() { fn duplicate_cannot_shift_the_owner_of_a_suspended_recording() { let mut app = PhotocraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 8, "height": 6})).unwrap(); - app.session.actions.list.push(Action::new("Menu", vec![ActionStep::new(atn_cmds::MENU_ITEM, json!({"id": "image.imageSize"}))])).unwrap(); + app.session.actions_mut().list.push(Action::new("Menu", vec![ActionStep::new(atn_cmds::MENU_ITEM, json!({"id": "image.imageSize"}))])).unwrap(); app.run("actions.record", json!({"name": "Owner"})).unwrap(); let result = app.run("actions.play", json!({"action": "Menu"})).unwrap(); let dialog = result["paused"]["dialog"].clone(); - let list = app.session.actions.list.clone(); + let list = app.session.actions().list.clone(); assert!(app.session.recording.target.is_none()); let error = app.run("actions.duplicate", json!({"action": "Menu"})).unwrap_err(); assert!(error.contains("Confirm or cancel"), "{error}"); - assert_eq!(app.session.actions.list, list); + assert_eq!(app.session.actions().list, list); let app_ctx = app.ctx().clone(); let cancelled = control(&mut app, &app_ctx, "ui.dialog.cancel", json!({"dialog": dialog})); assert_eq!(cancelled["ok"], true, "{cancelled}"); diff --git a/crates/ui-egui/tests/it/actions_panel_menu.rs b/crates/ui-egui/tests/it/actions_panel_menu.rs index bc60979f5b..de88b418c8 100644 --- a/crates/ui-egui/tests/it/actions_panel_menu.rs +++ b/crates/ui-egui/tests/it/actions_panel_menu.rs @@ -1,5 +1,6 @@ //! Real panel controls compose the remaining commands with consent and retained selection. The trials that read //! the dialog host are unit tests in `panels/actions/panel_menu_tests.rs`. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::ui::actions::{ActionSelection, ActionsPanelCommands}; use craft::ui::runtime::commands::CommandRef; use egui_kittest::Harness; @@ -22,7 +23,7 @@ fn harness() -> Harness<'static, Box> { app.run("file.new", json!({"width":16,"height":12})).unwrap(); let mut a = Action::new("A", vec![]); a.set = Some("S".into()); - app.session.actions.list.push(a).unwrap(); + app.session.actions_mut().list.push(a).unwrap(); app.ui.actions.panel.selected = Some(ActionSelection::Action(0)); app.ui.actions.panel.expanded.insert("A".into()); let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1100.0, 900.0)).build_ui_state(|ui, app| dialogs::run(app, ui), app); @@ -50,7 +51,7 @@ fn fire(h: &mut Harness<'static, Box>, command: ActionsPanelComma /// The steps of action `A`. fn steps(app: &PhotocraftApp) -> Vec { - app.session.actions.list.action(0).unwrap().steps.clone() + app.session.actions().list.action(0).unwrap().steps.clone() } /// The checkbox changes recording policy rather than disabling actual painting. diff --git a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs index efc331b4f3..fcdd436f7d 100644 --- a/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs +++ b/crates/ui-egui/tests/it/gpu_tests/canvas_16f.rs @@ -3,6 +3,7 @@ //! documents keep their `Rgba8Unorm` texture byte for byte. Skips when there is no GPU adapter or //! it can't render to `Rgba16Float`. +use photocraft_engine::color_cmds::ColorExt; use std::collections::HashSet; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/crates/ui-egui/tests/it/gpu_tests/display_shadows.rs b/crates/ui-egui/tests/it/gpu_tests/display_shadows.rs index ff336e1514..89a587d548 100644 --- a/crates/ui-egui/tests/it/gpu_tests/display_shadows.rs +++ b/crates/ui-egui/tests/it/gpu_tests/display_shadows.rs @@ -4,6 +4,7 @@ //! profiles and expected values implement ICC.1:2010 Annex F.3's matrix/TRC equations. //! A uniform 33³ display LUT used to make input sRGB 1–7 noticeably too dark. +use photocraft_engine::color_cmds::ColorExt; use std::sync::Arc; use craft::cms::{Builtin, Profile, curve::Curve}; @@ -160,7 +161,7 @@ fn gpu_display_shadows_match_independent_icc_reference_at_all_depths() { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default()); app.set_wgpu(cc.wgpu_render_state.as_ref().expect("render state").clone()); - app.session.color.set_displays(Ok(vec![Display { + app.session.color_mut().set_displays(Ok(vec![Display { id: 1, name: "Synthetic display".into(), frame: [0.0, 0.0, 1000.0, 700.0], diff --git a/crates/ui-egui/tests/it/layout_perf.rs b/crates/ui-egui/tests/it/layout_perf.rs index 124e5e6879..13a8ad8016 100644 --- a/crates/ui-egui/tests/it/layout_perf.rs +++ b/crates/ui-egui/tests/it/layout_perf.rs @@ -7,6 +7,7 @@ #[path = "../support/layout_doc.rs"] mod layout_doc; +use photocraft_engine::color_cmds::ColorExt; use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; use photocraft_doc::{Document, LayerContent, LayerId}; diff --git a/crates/ui-egui/tests/it/tone_targets.rs b/crates/ui-egui/tests/it/tone_targets.rs index b0060e0728..6519fac13a 100644 --- a/crates/ui-egui/tests/it/tone_targets.rs +++ b/crates/ui-egui/tests/it/tone_targets.rs @@ -1,4 +1,5 @@ //! Levels/Curves must use the same grayscale target in their controls, pickers and commands. +use photocraft_engine::actions_cmds::ActionsExt; use craft::automation::actions::ActionStep; use craft::automation::ui::actions::ActionSelection; use craft::ui::dialog::DialogId; @@ -139,7 +140,7 @@ fn next_case(h: &mut Harness<'static, Box>, from: &Session, filte app.session.add_document(doc, None); app.session.select_layer(st.active_layer.unwrap()).unwrap(); app.session.active_mut().unwrap().channel_view = st.channel_view.clone(); - app.session.actions = from.actions.clone(); + *app.session.actions_mut() = from.actions().clone(); app.ui.mask_target = false; app.ui.vector_mask_target = false; app.ui.filter_mask_target = filter_mask; @@ -286,12 +287,12 @@ fn add_action(app: &mut PhotocraftApp, name: &str, command: impl Into, p if dialog { action.dialogs.insert(0); } - app.session.actions.list.push(action).unwrap(); + app.session.actions_mut().list.push(action).unwrap(); } /// The parameters the first step of the first action is recorded with. fn recorded_params(h: &Harness<'static, Box>) -> Value { - h.state().session.actions.list.to_file().actions[0].steps[0].params.clone() + h.state().session.actions().list.to_file().actions[0].steps[0].params.clone() } /// Plays `action` on `h`, which pauses at its dialog. diff --git a/crates/ui-egui/tests/it/workspace_presets.rs b/crates/ui-egui/tests/it/workspace_presets.rs index 9c5cb8cac7..c0b1c8c984 100644 --- a/crates/ui-egui/tests/it/workspace_presets.rs +++ b/crates/ui-egui/tests/it/workspace_presets.rs @@ -1,5 +1,6 @@ //! #1120: workspace selection/reset must apply useful layouts, including saved layouts. +use photocraft_engine::prefs::SavedPrefsExt; use photocraft_engine::Session; use photocraft_ui_egui::dock; use photocraft_ui_egui::{PhotocraftApp, menus}; diff --git a/scripts/engine_split/rust_source.py b/scripts/engine_split/rust_source.py index bd708bebab..e9ec3d5205 100644 --- a/scripts/engine_split/rust_source.py +++ b/scripts/engine_split/rust_source.py @@ -5,6 +5,8 @@ the same offsets. `test_regions` finds a crate's test code: whole files reached `#[cfg(test)]` (or `#[cfg(all(test, ...))]`) `mod x;`, and the `#[cfg(test)]` items and bare `#[test]` functions of other files (the test harness compiles `#[test]` functions only in test builds). `#[cfg(any(test, ...))]` items are not test code: other builds compile them too. +`edited_definitions` finds a branch's edits to definitions a step moved or changed, for the steps' +`branch` modes. """ import os, re, subprocess @@ -155,3 +157,70 @@ def git(*args, check=True): def git_show(ref, path): r = subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True) return r.stdout if r.returncode == 0 else None + + +HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? ") + + +def definition_lines(src, item): + """1-based (first, last) lines of `item` (`"fn name"`, `"struct Name"`, ...) in `src`, its doc + comments and attributes included.""" + masked = mask(src) + kind, name = item.split() + m = re.search(rf"^[ \t]*(?:pub(?:\([a-z:]+\))?\s+)?{kind}\s+{re.escape(name)}\b", masked, re.M) + if not m: + return None + i, depth = m.end(), 0 + while i < len(masked): + c = masked[i] + if c == "{": + depth += 1 + elif c == "}": + depth -= 1 + if depth == 0: + break + elif c == ";" and depth == 0: + break + i += 1 + lines = src.splitlines() + first = src.count("\n", 0, m.start()) + 1 + while first > 1 and lines[first - 2].lstrip().startswith(("///", "#[")): + first -= 1 + return first, src.count("\n", 0, i) + 1 + + +def edited_definitions(base, head, items, roots): + """The `(file, item)` pairs of `items` that the branch `base..head` edits: a changed line names the + item, or a hunk's old-side lines overlap the item's definition in `base`. `file` is relative to + whichever of `roots` (directory prefixes ending in `/`) holds it.""" + diff = subprocess.run(["git", "diff", "-U0", base, head, "--", *roots], capture_output=True, text=True, check=True).stdout + current = None + hunks, ranges, paths = {}, {}, {} + for line in diff.splitlines(): + if line.startswith("--- "): + path = line[4:].removeprefix("a/") + current = None + if path != "/dev/null": + current = path + for root in roots: + current = current.removeprefix(root) + paths[current] = path + elif line.startswith("+++ "): + continue + elif current and (h := HUNK.match(line)): + start, count = int(h[1]), int(h[2] or 1) + # A pure insertion (count 0) sits after `start`. + ranges.setdefault(current, []).append((start, start + max(count, 1) - 1) if count else (start, start + 1)) + elif line.startswith(("+", "-")) and current: + hunks.setdefault(current, []).append(line[1:]) + out = [] + for file, item in items: + name = item.split()[1] + named = any(re.search(rf"\b{re.escape(name)}\b", line) for line in hunks.get(file, [])) + inside = False + if file in ranges and (src := git_show(base, paths[file])) is not None: + span = definition_lines(src, item) + inside = span is not None and any(a <= span[1] and b >= span[0] for a, b in ranges[file]) + if named or inside: + out.append((file, item)) + return out diff --git a/scripts/engine_split/session_state.py b/scripts/engine_split/session_state.py index 4852cca83d..f722cf3f10 100755 --- a/scripts/engine_split/session_state.py +++ b/scripts/engine_split/session_state.py @@ -22,10 +22,10 @@ slot read through `preset_store::PresetStoreExt` (`s.preset_store()`, `s.preset_ Running either mode twice gives the same result. What it cannot do is printed at the end of every run. """ -import argparse, os, re, subprocess, sys +import argparse, os, re, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from rust_source import git, git_show, mask # noqa: E402 +from rust_source import edited_definitions, git # noqa: E402 FIELDS = ["record_tools", "recording", "take", "playing", "playback_stack", "playback_steps", "budget_shared", "batch_depth", "script_depth", "script_steps"] RENAMED = {"recording": "target"} @@ -123,62 +123,11 @@ def split(): print(f"session_state split: {n} files rewritten") -HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? ") - - -def definition_lines(src, item): - """1-based (first, last) lines of `item` in `src`, its doc comments and attributes included.""" - masked = mask(src) - kind, name = item.split() - m = re.search(rf"^[ \t]*(?:pub(?:\([a-z:]+\))?\s+)?{kind}\s+{re.escape(name)}\b", masked, re.M) - if not m: - return None - i, depth = m.end(), 0 - while i < len(masked): - c = masked[i] - if c == "{": - depth += 1 - elif c == "}": - depth -= 1 - if depth == 0: - break - elif c == ";" and depth == 0: - break - i += 1 - lines = src.splitlines() - first = src.count("\n", 0, m.start()) + 1 - while first > 1 and lines[first - 2].lstrip().startswith(("///", "#[")): - first -= 1 - return first, src.count("\n", 0, i) + 1 - - def moved_edits(base, head): - diff = subprocess.run(["git", "diff", "-U0", base, head, "--", "crates/engine/src", SRC], capture_output=True, text=True, check=True).stdout - current = None - hunks, ranges, paths = {}, {}, {} - for line in diff.splitlines(): - if line.startswith("--- "): - path = line[4:].removeprefix("a/") - current = path.removeprefix("crates/engine/src/").removeprefix(SRC) if path != "/dev/null" else None - if current: - paths[current] = path - elif line.startswith("+++ "): - continue - elif current and (h := HUNK.match(line)): - start, count = int(h[1]), int(h[2] or 1) - # A pure insertion (count 0) sits after `start`. - ranges.setdefault(current, []).append((start, start + max(count, 1) - 1) if count else (start, start + 1)) - elif line.startswith(("+", "-")) and current: - hunks.setdefault(current, []).append(line[1:]) - for old_file, item, new_file in MOVED: - name = item.split()[1] - named = any(re.search(rf"\b{re.escape(name)}\b", line) for line in hunks.get(old_file, [])) - inside = False - if old_file in ranges and (src := git_show(base, paths[old_file])) is not None: - span = definition_lines(src, item) - inside = span is not None and any(a <= span[1] and b >= span[0] for a, b in ranges[old_file]) - if named or inside: - REPORT.append(f"NOT DONE: the branch edits {old_file} near `{item}`; that definition is in {SRC}{new_file} now") + new_files = {(old_file, item): new_file for old_file, item, new_file in MOVED} + for old_file, item in edited_definitions(base, head, list(new_files), ["crates/engine/src/", SRC]): + new_file = new_files[(old_file, item)] + REPORT.append(f"NOT DONE: the branch edits {old_file} near `{item}`; that definition is in {SRC}{new_file} now") def branch(base, head): diff --git a/scripts/engine_split/slot_access.py b/scripts/engine_split/slot_access.py new file mode 100644 index 0000000000..2a2ba9c14d --- /dev/null +++ b/scripts/engine_split/slot_access.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 +"""Engine split, step 6: session slots and extension traits. + +State that only crates above engine core read left `Session`'s fields for session slots, each read +through its module's extension trait: + + s.color ColorState color_cmds::ColorExt color() / color_mut() + s.presets Tracked presets::PresetsExt presets() / presets_mut() + s.actions ActionState actions_cmds::ActionsExt actions() / actions_mut() + s.object_finder ObjectFinderCache smartselect_cmds::SmartSelectExt object_finder() / object_finder_mut() + s.print_spooler Option print_cmds::PrintExt print_spooler() -> Option<&_> / print_spooler_mut() + s.printer_source Option print_cmds::PrintExt printer_source() -> Option<&_> / printer_source_mut() + +`presets()` / `presets_mut()` return the `Tracked` itself, so `.revision()` and `.edit(..)` stay as +they were and a deref takes one more `*` (`&mut *s.presets` is `&mut **s.presets_mut()`). + +The `impl Session` methods of modules above core are trait methods now (same names, same files): +`open_document` (ColorExt), `start_link_scan`, `missing_links`, `missing_links_revision`, +`poll_link_scan` (link_watch::LinkWatchExt), `load_presets_json` (PresetsExt), +`brush_presets_changed`, `attach_preset_store`, `sync_preset_store`, `load_brush_tips` +(preset_store::PresetStoreExt), `prefs_to_json`, `prefs_value`, `load_prefs_json`, `saved_prefs`, +`set_saved_prefs` (prefs::SavedPrefsExt). Calling them needs the trait imported. The crate-private +`s.presets_changed()` is the free function `presets::presets_changed(s)`. + + python3 scripts/engine_split/slot_access.py split + Rewrites every Rust file of the engine and its dependents (`ROOTS`) and adds the trait imports. + + python3 scripts/engine_split/slot_access.py branch --base --head + On a branch rebased onto the step (`--head` is the branch from before the rebase, + `ORIG_HEAD` right after it): rewrites the files the branch changed, and lists the branch's + edits to the methods that became trait methods or free functions. A branch from before + step 5 runs `session_state.py branch` first: its rules match `s.actions.`. + + cargo check --message-format json ... | python3 scripts/engine_split/slot_access.py fix + Applies what the compiler points at: a field access the rewrite missed, a read accessor + that has to be `_mut` (or the other way round), an accessor on a type that isn't a session + (put back), a missing or unused trait import. Run check and fix again until nothing changes. + +Running any mode twice gives the same result. What it cannot do is printed at the end of every run. +""" +import argparse, json, os, re, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from rust_source import block_end, edited_definitions, git, mask # noqa: E402 + +CORE = "crates/engine-core/src/" +# The engine and the crates that use it; nothing below the engine has a session. +ROOTS = ("crates/engine-core", "crates/engine/", "crates/ui-egui", "crates/automation", "apps") + +# field -> (module, trait, type, definition file, optional slot); `TRACKED` slots hold `Tracked`. +SLOTS = { + "color": ("color_cmds", "ColorExt", "ColorState", "cmd/color_cmds.rs", False), + "presets": ("presets", "PresetsExt", "PresetState", "presets.rs", False), + "actions": ("actions_cmds", "ActionsExt", "ActionState", "cmd/actions_cmds.rs", False), + "object_finder": ("smartselect_cmds", "SmartSelectExt", "ObjectFinderCache", "cmd/smartselect_cmds.rs", False), + "print_spooler": ("print_cmds", "PrintExt", "Spooler", "cmd/print_cmds.rs", True), + "printer_source": ("print_cmds", "PrintExt", "PrinterSource", "cmd/print_cmds.rs", True), +} +# trait -> (module, methods besides the accessors) +TRAITS = { + "ColorExt": ("color_cmds", ["open_document"]), + "LinkWatchExt": ("link_watch", ["start_link_scan", "missing_links", "missing_links_revision", "poll_link_scan"]), + "PresetsExt": ("presets", ["load_presets_json"]), + "PresetStoreExt": ("preset_store", ["brush_presets_changed", "attach_preset_store", "sync_preset_store", "load_brush_tips"]), + "SavedPrefsExt": ("prefs", ["prefs_to_json", "prefs_value", "load_prefs_json", "saved_prefs", "set_saved_prefs"]), + "ActionsExt": ("actions_cmds", []), + "SmartSelectExt": ("smartselect_cmds", []), + "PrintExt": ("print_cmds", []), +} +TRACKED = {"presets"} +# `craft_tracked::Tracked`'s own methods: (reads, writes). +TRACKED_METHODS = ({"revision", "source"}, {"edit"}) +# Former inherent methods and helpers, by file under `CORE`: what each is now. +MOVED = [ + ("cmd/color_cmds.rs", "open_document", "a `ColorExt` method"), + ("link_watch.rs", "start_link_scan", "a `LinkWatchExt` method"), + ("link_watch.rs", "missing_links", "a `LinkWatchExt` method"), + ("link_watch.rs", "missing_links_revision", "a `LinkWatchExt` method"), + ("link_watch.rs", "poll_link_scan", "a `LinkWatchExt` method"), + ("link_watch.rs", "note_missing_links", "a free function `note_missing_links(s, ..)`"), + ("link_watch.rs", "apply_link_stamps", "a free function `apply_link_stamps(s, ..)`"), + ("presets.rs", "load_presets_json", "a `PresetsExt` method"), + ("presets.rs", "presets_changed", "a free function `presets_changed(s)`"), + ("preset_store.rs", "brush_presets_changed", "a `PresetStoreExt` method"), + ("preset_store.rs", "attach_preset_store", "a `PresetStoreExt` method"), + ("preset_store.rs", "sync_preset_store", "a `PresetStoreExt` method"), + ("preset_store.rs", "load_brush_tips", "a `PresetStoreExt` method"), + ("prefs/saved.rs", "prefs_to_json", "a `SavedPrefsExt` method"), + ("prefs/saved.rs", "prefs_value", "a `SavedPrefsExt` method"), + ("prefs/saved.rs", "load_prefs_json", "a `SavedPrefsExt` method"), + ("prefs/saved.rs", "saved_prefs", "a `SavedPrefsExt` method"), + ("prefs/saved.rs", "set_saved_prefs", "a `SavedPrefsExt` method"), + ("prefs/saved.rs", "prefs_view", "a free function `prefs_view(s)`"), + ("prefs/saved.rs", "set_pref", "a free function `set_pref(s, ..)`"), +] +# Methods whose names other types also have: they never trigger an import on their own. +COMMON = {"open_document", "missing_links"} +ACCESSOR_TRAIT = {} +for f, (_, tr, _, _, _) in SLOTS.items(): + ACCESSOR_TRAIT[f] = tr + ACCESSOR_TRAIT[f + "_mut"] = tr +METHOD_TRAIT = {m: t for t, (_, ms) in TRAITS.items() for m in ms} +# Receivers that hold a field of the same name and are never a session. +NOT_SESSION = {"tools", "ui", "list", "imported", "file", "saved", "imp", "parsed", "panel", "brush", "gradient", "tool", "style", "shape", "edit", "pattern", "export", "document"} +# A session expression right before the field: `s`, `session`, `self` (in `impl ... Session` files), +# `x.session`, `session()`. +SESSION = r"(?:(?])|\+=|-=|\*=|/=|%=|\|=|&=|\^=|<<=|>>=)") +PLACE = re.compile(r"(?:\.\w+(?!\s*[\(\w])|\[[^\[\]\n]*\])*") + +REPORT = [] + + +def members(): + """Per slot field: (fields, methods, methods taking `&mut self`), read from the engine source.""" + out = {} + srcs = {} + for d, _, files in os.walk(CORE): + for name in files: + if name.endswith(".rs"): + p = os.path.join(d, name) + with open(p, encoding="utf-8") as fh: + srcs[p] = fh.read() + for field, (_, _, ty, defn, optional) in SLOTS.items(): + fields, methods, muts = set(), set(), set() + if not optional: + m = re.search(r"pub struct " + ty + r"\b[^{;]*\{(.*?)\n\}", srcs.get(CORE + defn, ""), re.S) + if m: + fields |= set(re.findall(r"^\s*(?:pub(?:\([a-z]+\))? )?(\w+):", m.group(1), re.M)) + for src in srcs.values(): + for im in re.finditer(r"\nimpl (?:crate::(?:\w+::)*)?" + ty + r" \{(.*?)\n\}", src, re.S): + for fm in re.finditer(r"^ (?:pub(?:\([a-z]+\))? )?fn (\w+)(?:<[^>]*>)?\((&mut self)?", im.group(1), re.M): + methods.add(fm.group(1)) + if fm.group(2): + muts.add(fm.group(1)) + if field in TRACKED: + methods |= TRACKED_METHODS[0] | TRACKED_METHODS[1] + muts |= TRACKED_METHODS[1] + out[field] = (fields, methods, muts) + return out + + +MEMBERS = None + + +def all_muts(): + s = set(STD_MUT) + for _, _, muts in MEMBERS.values(): + s |= muts + return s + + +def writes(masked, start, end, field): + """Whether the access `masked[start:end]` (`X.field`) is written through, from the text around it.""" + head = masked[max(0, start - 200) : start] + if re.search(r"&\s*mut\s*$", head): + return True + rest = masked[end : end + 300] + place = PLACE.match(rest) + after = rest[place.end() :] + if ASSIGN.match(after): + return True + call = re.match(r"\s*\.(\w+)\s*(?:::<[^>]*>)?\s*\(", after) + if call and call.group(1) in all_muts(): + return True + return False + + +# A receiver chain right before `.field`: `s`, `app.session`, `h.state_mut().session`. +RECEIVER = re.compile(r"(?:\w+(?:\(\))?\.)*\w+(?:\(\))?$") + + +def receiver_start(masked, start): + m = RECEIVER.search(masked[max(0, start - 200) : start]) + return start - len(m.group(0)) if m else start + + +def rewrite_text(text, path): + masked = mask(text) + edits = [] # (start, end, replacement) + impl_session = re.search(r"\bimpl\b[^{\n]*\bSession\s*\{", masked) is not None + used_traits = set() + # A deref of a `Tracked` slot on a session receiver: one more `*` through the accessor. + for field in TRACKED: + rx = r"(&\s*mut\s*|&\s*)?\*\s*(" + SESSION + r")\.(" + field + r")\b(?!\s*[\(\w])" + for m in re.finditer(rx, masked): + if m.group(2) == "self" and not impl_session: + continue + borrow = m.group(1) or "" + mut = "mut" in borrow or (not borrow and ASSIGN.match(masked[m.end() : m.end() + 80]) is not None) + edits.append((m.start(2), m.start(2), "*")) + edits.append((m.start(3), m.end(3), field + ("_mut()" if mut else "()"))) + used_traits.add(SLOTS[field][1]) + for field, (fields, methods, _) in MEMBERS.items(): + optional = SLOTS[field][4] + # `X.field.member`: only members of the slot type, so same-named fields elsewhere stay. + if not optional: + for m in re.finditer(r"(?]*>)?\s*\()?", masked): + recv, member, is_call = m.group(1), m.group(4), m.group(5) is not None + if recv in NOT_SESSION or (recv == "self" and not impl_session): + continue + if (is_call and member not in methods) or (not is_call and member not in fields): + continue + fs, fe = m.start(3), m.end(3) + mut = writes(masked, receiver_start(masked, fs - 1), fe, field) or (is_call and member in MEMBERS[field][2]) + edits.append((fs, fe, field + ("_mut()" if mut else "()"))) + used_traits.add(SLOTS[field][1]) + # Whole-field uses on a session receiver. + for m in re.finditer(r"(&\s*(?:mut\s+)?)?(" + SESSION + r")\.(" + field + r")\b(?!\s*[\(\w])", masked): + fs, fe = m.start(3), m.end(3) + if any(a <= fs < b for a, b, _ in edits): + continue + recv_text = m.group(2) + if recv_text in ("s", "sess", "self"): + continue # other types name their fields the same: `fix` rewrites the session ones + + if re.match(r"\s*\.", masked[fe:]) and not optional: + continue # `X.field.member` with a member the slot type doesn't have + borrow = m.group(1) + rest = masked[fe : fe + 80] + if optional: + opt = re.match(r"\.(as_ref|as_mut|is_some|is_none|clone|take|as_deref)\(\)", rest) + if opt: + kind = opt.group(1) + to = {"as_ref": "()", "as_deref": "()", "is_some": "().is_some()", "is_none": "().is_none()", "clone": "().cloned()", "as_mut": "_mut().as_mut()", "take": "_mut().take()"}[kind] + edits.append((fs, fe + opt.end(), field + to)) + used_traits.add(SLOTS[field][1]) + continue + if ASSIGN.match(rest) and not borrow: + rs = m.start(2) + edits.append((rs, rs, "*")) + edits.append((fs, fe, field + "_mut()")) + elif borrow: + mut = "mut" in borrow + edits.append((m.start(1), m.start(2), "")) + edits.append((fs, fe, field + ("_mut()" if mut else "()"))) + elif optional: + REPORT.append(f"{path}: `{field}` used as a whole; write `{field}()` (Option<&_>) or `{field}_mut()`") + continue + else: + mut = writes(masked, m.start(2), fe, field) + edits.append((fs, fe, field + ("_mut()" if mut else "()"))) + used_traits.add(SLOTS[field][1]) + # `s.presets_changed()` is the crate-private free function. + if path.startswith(CORE) or ("/" + CORE) in path: + calls = list(re.finditer(r"(?::;` unless the file already names the trait in a `use` or defines it.""" + masked = mask(text) + # A `use` inside an inline module (`mod tests { .. }`) doesn't reach the file's other code. + if any(enclosing_mod(masked, m.start()) is None for m in re.finditer(r"\b(?:use|trait)\b[^;{]*\b" + trait + r"\b", masked)): + return text + line = f"use {trait_path(path, trait)};\n" + m = re.search(r"^use ", masked, re.M) + if m: + return text[: m.start()] + line + text[m.start() :] + pos = 0 + for lm in re.finditer(r"^(?://!.*|#!\[.*\]|\s*)\n", text, re.M): + if lm.start() != pos: + break + pos = lm.end() + return text[:pos] + line + text[pos:] + + +def enclosing_mod(masked, pos): + """The body start of the innermost inline `mod x { ... }` holding `pos`, or None at file level.""" + best = None + for m in re.finditer(r"\bmod\s+\w+\s*\{", masked[:pos]): + if block_end(masked, m.start()) > pos: + best = m.end() + return best + + +def add_import_in(text, path, trait, body): + """Adds the trait's `use` at the top of the inline module whose body starts at `body`.""" + masked = mask(text) + end = block_end(masked, body - 1) + if re.search(r"\buse\b[^;{]*\b" + trait + r"\b", masked[body:end]): + return text + nl = text.index("\n", body) + 1 + indent = re.match(r"[ \t]*", text[nl:]).group(0) + return text[:nl] + f"{indent}use {trait_path(path, trait)};\n" + text[nl:] + + +def rewrite(path): + with open(path, encoding="utf-8") as f: + old = f.read() + new = rewrite_text(old, path) + if new != old: + with open(path, "w", encoding="utf-8") as f: + f.write(new) + return True + return False + + +def rust_files(roots): + for root in roots: + for d, _, files in os.walk(root): + if "/target" in d or "/vendor" in d or d.startswith("vendor"): + continue + for name in files: + if name.endswith(".rs"): + yield os.path.join(d, name) + + +# ---------------------------------------------------------------- fix mode + +ACCESSOR_READ = re.compile(r"\.(" + "|".join(SLOTS) + r")\(\)") + + +def fix(stream): + edits = {} # path -> [(start, end, replacement)] + imports = {} # path -> {trait} + removals = {} # path -> {1-based line of an unused trait import} + left = [] + for line in stream: + line = line.strip() + if not line.startswith("{"): + continue + try: + msg = json.loads(line) + except ValueError: + continue + if msg.get("reason") != "compiler-message": + continue + d = msg["message"] + code = (d.get("code") or {}).get("code") + spans = [s for s in d.get("spans", []) if s.get("is_primary")] + if not spans: + continue + sp = spans[0] + path = sp["file_name"] + if not os.path.exists(path) or "/vendor/" in path or path.startswith("vendor/"): + continue + text = read(path) + b0, b1 = byte_to_char(text, sp["byte_start"]), byte_to_char(text, sp["byte_end"]) + snippet = text[b0:b1] + text_msg = d["message"] + if code in ("E0609", "E0615"): + m = re.match(r"(?:no field|attempted to take value of method) `(\w+)` on type `[^`]*Session[^`]*`", text_msg) + if m and m.group(1) in SLOTS: + field = m.group(1) + module = enclosing_mod(mask(text), b0) + masked = mask(text) + mut = writes(masked, receiver_start(masked, b0 - 1), b1, field) + rest = masked[b1 : b1 + 80] + if ASSIGN.match(rest): + edits.setdefault(path, []).append((receiver_start(masked, b0 - 1), receiver_start(masked, b0 - 1), "*")) + mut = True + borrow = re.search(r"&\s*(mut\s+)?$", masked[: receiver_start(masked, b0 - 1)]) + if borrow: + edits.setdefault(path, []).append((borrow.start(), borrow.end(), "")) + mut = bool(borrow.group(1)) + opt = re.match(r"\.(as_ref|as_deref|clone|as_mut|take)\(\)", rest) if SLOTS[field][4] else None + if opt: + # An Option slot: the read accessor is already `Option<&_>`. + to = {"as_ref": "()", "as_deref": "()", "clone": "().cloned()", "as_mut": "_mut().as_mut()", "take": "_mut().take()"}[opt.group(1)] + edits.setdefault(path, []).append((b0, b1 + opt.end(), field + to)) + else: + edits.setdefault(path, []).append((b0, b1, field + ("_mut()" if mut else "()"))) + imports.setdefault(path, set()).add((SLOTS[field][1], module)) + continue + if code in ("E0596", "E0594"): + ms = list(ACCESSOR_READ.finditer(snippet)) + if ms: + m = ms[-1] + edits.setdefault(path, []).append((b0 + m.start(1), b0 + m.end(1) + 2, m.group(1) + "_mut()")) + continue + after = re.match(r"\.(" + "|".join(SLOTS) + r")_mut\(\)", text[b1 : b1 + 40]) + if after: + edits.setdefault(path, []).append((b1 + 1, b1 + after.end(), after.group(1) + "()")) + continue + if code == "E0599": + m = re.match(r"no method named `(\w+)` found for (.*)", text_msg) + if m: + name, on = m.group(1), m.group(2) + trait = ACCESSOR_TRAIT.get(name) or METHOD_TRAIT.get(name) + in_scope_hint = any("not in scope" in (c.get("message") or "") or "trait" in (c.get("message") or "") for c in d.get("children", [])) + if trait and "Session" in on and in_scope_hint: + imports.setdefault(path, set()).add((trait, enclosing_mod(mask(text), b0))) + continue + if name in ACCESSOR_TRAIT and "Session" not in on: + field = name.removesuffix("_mut") + end = b1 + (2 if text[b1 : b1 + 2] == "()" else 0) + edits.setdefault(path, []).append((b0, end, field)) + if not re.match(r"\s*[\.\[]", text[end : end + 2]): + # A whole-field rewrite: `*x.field_mut() = v` was `x.field = v`; otherwise + # it was `&x.field` / `&mut x.field`. + rs = receiver_start(mask(text), b0 - 1) + if rs > 0 and text[rs - 1] == "*": + edits.setdefault(path, []).append((rs - 1, rs, "")) + else: + edits.setdefault(path, []).append((rs, rs, "&mut " if name.endswith("_mut") else "&")) + continue + if code == "E0425" and re.match(r"cannot find function `presets_changed`", text_msg): + imports.setdefault(path, set()).add(("presets_changed", enclosing_mod(mask(text), b0))) + continue + if d.get("level") == "warning" and code == "unused_imports": + # The import the warning points at, wherever it is (file level or an inline module). + if any(tr in snippet for tr in [*TRAITS, "presets_changed"]): + removals.setdefault(path, set()).add(sp["line_start"]) + continue + if d.get("level") == "error": + left.append(f"{path}:{sp['line_start']}: {code or ''} {text_msg}") + if left or edits or imports: + # An unused-import warning next to errors may only mean the code using it didn't type-check. + removals = {} + for path in set(edits) | set(imports) | set(removals): + text = apply(read(path), edits.get(path, [])) + # Innermost module first, so earlier insertion offsets stay valid. + for tr, module in sorted(imports.get(path, ()), key=lambda x: -(x[1] or 0)): + text = add_import(text, path, tr) if module is None else add_import_in(text, path, tr, module) + lines = text.splitlines(keepends=True) + for n in sorted(removals.get(path, ()), reverse=True): + if re.match(r"\s*use [\w:]*::\w+;\n", lines[n - 1]): + del lines[n - 1] + text = "".join(lines) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + n = sum(len(v) for v in edits.values()) + sum(len(v) for v in imports.values()) + sum(len(v) for v in removals.values()) + print(f"slot_access fix: {n} edits in {len(set(edits) | set(imports) | set(removals))} files; {len(left)} errors left for hand fixes") + for line in left: + print(" " + line) + + +def read(path): + with open(path, encoding="utf-8") as f: + return f.read() + + +def byte_to_char(text, b): + return len(text.encode("utf-8")[:b].decode("utf-8", errors="ignore")) + + +CANNOT_DO = """ +What this script cannot do (the compiler points at each): + - borrow conflicts: an accessor borrows the whole session, so `s.presets_mut().x.push(s.tools.y)` + or a slot reference held while another session field is read needs the other read in a local + first (`let y = s.tools.y.clone(); s.presets_mut().x.push(y);`); + - a reference to a slot taken through another binding and written later (`let c = s.color(); ...`): + make it `color_mut()`; + - a trait import in an inline module without `use super::*`; + - a `Tracked` slot borrowed through another binding and dereferenced later + (`let p = &mut s.presets; ... &mut **p`): add the `*` by hand; + - a new `Session` field read only above core: make it a slot of its crate (`Install::slot` in + `register`, an accessor on the module's extension trait). +""" + + +def main(): + global MEMBERS + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="mode", required=True) + sub.add_parser("split") + b = sub.add_parser("branch") + b.add_argument("--base", required=True) + b.add_argument("--head", required=True) + sub.add_parser("fix") + args = ap.parse_args() + os.chdir(git("rev-parse", "--show-toplevel").strip()) + MEMBERS = members() + if args.mode == "split": + n = sum(rewrite(p) for p in rust_files(ROOTS)) + print(f"slot_access split: {n} files rewritten") + elif args.mode == "branch": + changed = git("diff", "--name-only", f"{args.base}...{args.head}").split() + n = sum(rewrite(p) for p in changed if p.endswith(".rs") and p.startswith(ROOTS) and os.path.exists(p)) + now = {(f, "fn " + name): what for f, name, what in MOVED} + for f, item in edited_definitions(args.base, args.head, list(now), ["crates/engine/src/", CORE]): + REPORT.append(f"NOT DONE: the branch edits `{item}` in {CORE}{f}; it is {now[(f, item)]} now (same file): re-apply the edit there") + print(f"slot_access branch: {n} files rewritten") + else: + fix(sys.stdin) + for line in REPORT: + print(line) + print(CANNOT_DO) + + +if __name__ == "__main__": + main()