From 051ee2aff772d72575a891df7967f40e2d2ed6cc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 27 Oct 2026 20:14:10 +0000 Subject: [PATCH] Split oversized functions and fix imports in photocraft crates Moves code into named helpers (PSD export blocks, key-shortcut stages, options-bar tool controls, liquify wheel handling, CAF options bar) without changing behaviour, and restores imports left unfinished in the engine and UI crates. Clippy still reports cognitive-complexity errors in ui-egui; those are being split next. --- AGENTS.md | 2 +- crates/automation/src/server/conventions.rs | 7 +- crates/automation/src/server/progress.rs | 2 +- crates/automation/src/server/transport.rs | 2 +- crates/automation/src/workspace/tests.rs | 4 + crates/compose/src/content.rs | 2 +- crates/compose/src/extents.rs | 2 +- crates/engine/src/adjust_params/tests.rs | 8 + crates/engine/src/cmd/adjust_params.rs | 2 +- crates/engine/src/cmd/atn_cmds/adjustments.rs | 2 +- crates/engine/src/cmd/atn_cmds/convert.rs | 2 +- crates/engine/src/cmd/atn_cmds/descriptors.rs | 2 +- crates/engine/src/cmd/atn_cmds/events.rs | 2 +- crates/engine/src/cmd/atn_cmds/fields.rs | 2 +- crates/engine/src/cmd/atn_cmds/files.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_doc.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_image.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_layer.rs | 2 +- crates/engine/src/cmd/atn_cmds/steps_make.rs | 305 ++--- crates/engine/src/cmd/atn_cmds/tables.rs | 2 +- .../engine/src/cmd/brush_cmds/mixer_live.rs | 5 +- crates/engine/src/cmd/channel_cmds/calc.rs | 2 +- crates/engine/src/cmd/channel_cmds/manage.rs | 4 +- crates/engine/src/cmd/channel_cmds/planes.rs | 2 +- crates/engine/src/cmd/channel_cmds/refs.rs | 2 +- .../engine/src/cmd/channel_cmds/selection.rs | 2 +- crates/engine/src/cmd/channel_cmds/spot.rs | 2 +- .../engine/src/cmd/channel_cmds/targeting.rs | 2 +- crates/engine/src/cmd/channel_cmds/view.rs | 2 +- .../src/cmd/edit_menu_cmds/content_aware.rs | 5 +- .../cmd/edit_menu_cmds/content_aware_scale.rs | 4 +- crates/engine/src/cmd/edit_menu_cmds/fade.rs | 5 +- .../src/cmd/edit_menu_cmds/find_replace.rs | 2 +- .../engine/src/cmd/edit_menu_cmds/presets.rs | 2 +- crates/engine/src/cmd/edit_menu_cmds/purge.rs | 2 +- crates/engine/src/cmd/enabled.rs | 2 +- crates/engine/src/cmd/file_cmds/batch_run.rs | 2 +- crates/engine/src/cmd/file_cmds/export.rs | 2 +- crates/engine/src/cmd/file_cmds/info.rs | 2 +- crates/engine/src/cmd/file_cmds/open.rs | 5 +- crates/engine/src/cmd/file_cmds/paths.rs | 2 +- crates/engine/src/cmd/file_cmds/processing.rs | 5 +- crates/engine/src/cmd/file_cmds/save.rs | 2 +- .../engine/src/cmd/layer_multi_cmds/align.rs | 2 +- .../engine/src/cmd/layer_multi_cmds/damage.rs | 2 +- .../engine/src/cmd/layer_multi_cmds/moves.rs | 2 +- .../src/cmd/layer_multi_cmds/selection.rs | 2 +- .../src/cmd/layer_multi_cmds/structure.rs | 2 +- crates/engine/src/cmd/layer_params.rs | 2 +- crates/engine/src/cmd/ops.rs | 2 +- crates/engine/src/cmd/params.rs | 2 +- .../src/cmd/retouch_cmds/art_history.rs | 2 +- crates/engine/src/cmd/retouch_cmds/clone.rs | 6 +- .../cmd/retouch_cmds/content_aware_move.rs | 5 +- crates/engine/src/cmd/retouch_cmds/dab.rs | 6 +- crates/engine/src/cmd/retouch_cmds/heal.rs | 5 +- crates/engine/src/cmd/retouch_cmds/patch.rs | 5 +- .../engine/src/cmd/retouch_cmds/periodic.rs | 2 +- crates/engine/src/cmd/retouch_cmds/remove.rs | 5 +- .../engine/src/cmd/retouch_cmds/sampling.rs | 2 +- crates/engine/src/cmd/smart_cmds/contents.rs | 5 +- crates/engine/src/cmd/smart_cmds/filters.rs | 5 +- crates/engine/src/cmd/smart_cmds/placing.rs | 5 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 5 +- crates/engine/src/cmd/smart_cmds/source.rs | 5 +- crates/engine/src/cmd/type_caret_cmds.rs | 19 + crates/engine/src/cmd/type_cmds.rs | 19 + crates/engine/src/cmd/vector_cmds/params.rs | 5 +- crates/engine/src/cmd/vector_cmds/paths.rs | 5 +- crates/engine/src/cmd/vector_cmds/shape.rs | 5 +- .../engine/src/cmd/vector_cmds/vector_mask.rs | 2 +- crates/engine/src/cmd/web_cmds/assets.rs | 2 +- crates/engine/src/cmd/web_cmds/optimizer.rs | 2 +- crates/engine/src/cmd/web_cmds/quick.rs | 2 +- crates/engine/src/cmd/web_cmds/save_web.rs | 2 +- crates/engine/src/cmd/web_cmds/settings.rs | 2 +- crates/engine/src/doc_state.rs | 2 +- crates/engine/src/error.rs | 2 +- crates/engine/src/layer_style.rs | 476 ++++---- crates/engine/src/prefs/cmds.rs | 2 +- crates/engine/src/prefs/customize.rs | 131 +- crates/engine/src/prefs/files.rs | 2 +- crates/engine/src/prefs/shortcuts.rs | 2 +- crates/engine/src/prefs/store.rs | 2 +- crates/engine/src/prefs/validate.rs | 7 +- crates/engine/src/session.rs | 5 +- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/session/execute.rs | 7 +- crates/engine/src/session/history.rs | 2 +- crates/engine/src/session/layers.rs | 2 +- crates/io/src/psd_export/merged.rs | 2 + crates/ui-egui/src/app.rs | 10 +- crates/ui-egui/src/app/clipboard.rs | 2 +- crates/ui-egui/src/app/commands.rs | 169 +-- crates/ui-egui/src/app/control.rs | 2 +- crates/ui-egui/src/app/files.rs | 5 +- crates/ui-egui/src/app/frame.rs | 8 +- crates/ui-egui/src/app/gpu.rs | 2 +- crates/ui-egui/src/app/ime.rs | 2 +- crates/ui-egui/src/app/input.rs | 2 +- crates/ui-egui/src/app/prefs.rs | 2 +- crates/ui-egui/src/app/screenshot.rs | 2 +- crates/ui-egui/src/app/targets.rs | 2 +- crates/ui-egui/src/app/thumbs.rs | 2 +- crates/ui-egui/src/app/view.rs | 2 +- crates/ui-egui/src/app/window.rs | 2 +- crates/ui-egui/src/canvas.rs | 1059 +++++++++-------- crates/ui-egui/src/canvas/cursors.rs | 2 +- crates/ui-egui/src/canvas/display.rs | 2 +- crates/ui-egui/src/canvas/drag.rs | 2 +- crates/ui-egui/src/canvas/filter_preview.rs | 2 +- crates/ui-egui/src/canvas/gesture.rs | 2 +- .../ui-egui/src/canvas/gpu_canvas/budget.rs | 2 +- .../ui-egui/src/canvas/gpu_canvas/callback.rs | 2 +- .../src/canvas/gpu_canvas/doc_textures.rs | 2 +- crates/ui-egui/src/canvas/gpu_canvas/perf.rs | 2 +- .../src/canvas/gpu_canvas/resources.rs | 2 +- crates/ui-egui/src/canvas/gpu_canvas/setup.rs | 2 +- .../ui-egui/src/canvas/gpu_canvas/texels.rs | 2 +- crates/ui-egui/src/canvas/navigator.rs | 2 +- crates/ui-egui/src/canvas/paint.rs | 2 +- crates/ui-egui/src/canvas/selection.rs | 2 +- crates/ui-egui/src/canvas/start_screen.rs | 2 +- crates/ui-egui/src/canvas/strokes.rs | 2 +- crates/ui-egui/src/canvas/tabs.rs | 2 +- crates/ui-egui/src/canvas/textures.rs | 2 +- crates/ui-egui/src/canvas/tool_input.rs | 235 ++-- .../ui-egui/src/canvas/transform_controls.rs | 2 +- crates/ui-egui/src/canvas/view_xform.rs | 2 +- crates/ui-egui/src/control/dispatch.rs | 2 +- crates/ui-egui/src/control/params.rs | 2 +- .../src/dialogs/adjust_editors/basic.rs | 5 +- .../src/dialogs/adjust_editors/curves.rs | 5 +- .../dialogs/adjust_editors/gradient_map.rs | 5 +- .../dialogs/adjust_editors/hue_saturation.rs | 5 +- .../src/dialogs/adjust_editors/levels.rs | 2 +- .../src/dialogs/adjust_editors/session.rs | 2 +- crates/ui-egui/src/dialogs/caf_ui/controls.rs | 2 +- .../ui-egui/src/dialogs/caf_ui/lifecycle.rs | 2 +- crates/ui-egui/src/dialogs/caf_ui/preview.rs | 2 +- crates/ui-egui/src/dialogs/caf_ui/view.rs | 95 +- .../src/dialogs/camera_raw_ui/controls.rs | 5 +- .../src/dialogs/camera_raw_ui/convert.rs | 2 +- .../ui-egui/src/dialogs/camera_raw_ui/menu.rs | 2 +- .../ui-egui/src/dialogs/camera_raw_ui/open.rs | 2 +- .../src/dialogs/camera_raw_ui/proxy.rs | 2 +- .../src/dialogs/camera_raw_ui/sidecar.rs | 2 +- crates/ui-egui/src/dialogs/file_ui/print.rs | 2 +- crates/ui-egui/src/dialogs/file_ui/web.rs | 2 +- .../src/dialogs/file_ui/web_preview.rs | 2 +- crates/ui-egui/src/dialogs/liquify_ui.rs | 102 +- crates/ui-egui/src/i18n/tests.rs | 8 + crates/ui-egui/src/input/shortcuts.rs | 204 ++-- crates/ui-egui/src/menus/bar.rs | 2 +- crates/ui-egui/src/menus/invoke.rs | 129 +- crates/ui-egui/src/menus/items.rs | 2 +- crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/view_cmds/arrange.rs | 2 +- crates/ui-egui/src/menus/view_cmds/dialogs.rs | 2 +- .../ui-egui/src/menus/view_cmds/dispatch.rs | 2 +- crates/ui-egui/src/menus/view_cmds/options.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 155 +-- crates/ui-egui/src/panels/brush_controls.rs | 2 +- crates/ui-egui/src/panels/color.rs | 2 +- crates/ui-egui/src/panels/dock.rs | 2 +- crates/ui-egui/src/panels/history.rs | 2 +- crates/ui-egui/src/panels/info.rs | 2 +- crates/ui-egui/src/panels/layer_drag.rs | 2 +- crates/ui-egui/src/panels/layer_row.rs | 4 +- crates/ui-egui/src/panels/layers.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 2 +- crates/ui-egui/src/panels/options_bar.rs | 1018 ++++++++-------- crates/ui-egui/src/panels/preset_panels.rs | 82 +- .../src/panels/preset_panels/panels.rs | 5 +- crates/ui-egui/src/panels/properties.rs | 2 +- crates/ui-egui/src/panels/smart_ui.rs | 33 +- crates/ui-egui/src/panels/status_bar.rs | 2 +- crates/ui-egui/src/panels/title_bar.rs | 2 +- crates/ui-egui/src/panels/toolbar.rs | 2 +- .../ui-egui/src/prefs/prefs_ui/appearance.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/dialogs.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/fields.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/graphics.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/save.rs | 2 +- .../ui-egui/src/prefs/prefs_ui/shortcuts.rs | 2 +- crates/ui-egui/src/prefs/prefs_ui/startup.rs | 2 +- crates/ui-egui/src/screenshot_tests.rs | 243 ++-- crates/ui-egui/src/services.rs | 5 +- crates/ui-egui/src/state.rs | 8 + crates/ui-egui/src/state/color_panel.rs | 2 +- crates/ui-egui/src/state/panel_state.rs | 2 +- crates/ui-egui/src/state/tool.rs | 2 +- crates/ui-egui/src/state/tool_options.rs | 2 +- crates/ui-egui/src/state/transform.rs | 2 +- crates/ui-egui/src/theme.rs | 225 +++- .../src/tools/gradient_ui/properties_panel.rs | 6 +- .../ui-egui/src/tools/transform_tool/begin.rs | 5 +- .../src/tools/transform_tool/commit.rs | 4 +- .../src/tools/transform_tool/drag_modes.rs | 2 +- .../ui-egui/src/tools/transform_tool/draw.rs | 5 +- .../src/tools/transform_tool/options_bar.rs | 2 +- .../src/tools/transform_tool/pointer.rs | 5 +- .../src/tools/transform_tool/preview.rs | 2 +- .../ui-egui/src/tools/transform_tool/warp.rs | 2 +- .../ui-egui/src/tools/type_tool/defaults.rs | 2 +- crates/ui-egui/src/tools/type_tool/editing.rs | 2 +- crates/ui-egui/src/tools/type_tool/fonts.rs | 2 +- crates/ui-egui/src/tools/type_tool/ime.rs | 2 +- .../ui-egui/src/tools/type_tool/ime_edit.rs | 4 +- .../ui-egui/src/tools/type_tool/ime_tests.rs | 225 ++-- crates/ui-egui/src/tools/type_tool/keys.rs | 2 +- crates/ui-egui/src/tools/type_tool/layout.rs | 2 +- .../src/tools/type_tool/options_bar.rs | 2 +- crates/ui-egui/src/tools/type_tool/overlay.rs | 2 +- crates/ui-egui/src/tools/type_tool/panel.rs | 2 +- crates/ui-egui/src/tools/type_tool/pointer.rs | 2 +- .../ui-egui/src/tools/vector_ui/curvature.rs | 2 +- crates/ui-egui/src/tools/vector_ui/options.rs | 2 +- .../ui-egui/src/tools/vector_ui/path_ops.rs | 2 +- .../src/tools/vector_ui/paths_panel.rs | 2 +- crates/ui-egui/src/tools/vector_ui/pen.rs | 4 +- crates/ui-egui/src/tools/vector_ui/shapes.rs | 2 +- crates/ui-egui/src/widgets/angle_dial.rs | 3 +- crates/ui-egui/src/widgets/buttons.rs | 2 +- crates/ui-egui/src/widgets/color.rs | 2 +- crates/ui-egui/src/widgets/color_count.rs | 3 +- crates/ui-egui/src/widgets/dropdown.rs | 2 +- crates/ui-egui/src/widgets/fields.rs | 2 +- crates/ui-egui/src/widgets/panel.rs | 2 +- crates/ui-egui/src/widgets/scrub.rs | 2 +- crates/ui-egui/src/widgets/slider.rs | 2 +- crates/ui-egui/src/widgets/text_field.rs | 2 +- crates/ui-egui/src/widgets/units.rs | 2 +- 233 files changed, 3117 insertions(+), 2397 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4a3032f0a9..e1ffe55928 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file, - **Don't cascade.** Handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)`) and treat thread joins as `Result`s. - **Last-resort guard.** The app shell must catch an escaped panic around command dispatch and file import/export, reports it as an error and keeps the document. It's a safety net, not a licence to panic. Keep `panic = "unwind"`. - **Prove it.** Every crash fix comes with a small synthetic regression test that panicked before the fix. -- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic`/indexing in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. +- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic` in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. 1. **Everything is a command.** New user-visible behaviour = a command in the engine (`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path, shortcut, params doc, `enabled` and `run`, plus tests. The UI, CLI, control channel and MCP all dispatch commands by id. Use the **exact id from `crates/ui-egui/src/menu_catalog.rs`** and the menu item goes live automatically. Only pure view/window state (zoom, panels, screen mode) belongs to the shell (`menus.rs` `UI_COMMANDS`). 2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `photocraft-cms` (`Transform`, `transform::cached`). Test at several depths. diff --git a/crates/automation/src/server/conventions.rs b/crates/automation/src/server/conventions.rs index 6e2740041d..b48c41db87 100644 --- a/crates/automation/src/server/conventions.rs +++ b/crates/automation/src/server/conventions.rs @@ -1,7 +1,10 @@ //! Catalog metadata, strict tool envelopes and live resources. -use super::*; +use super::{Arc, Backend, BatchParams, DocIndex, ListParams, McpError, Parameters, PhotocraftMcp, RunParams, ServerHandler, Value, json}; use rmcp::RoleServer; -use rmcp::model::*; +use rmcp::model::{ + CallToolRequestParams, CallToolResponse, Implementation, ListResourcesResult, ListToolsResult, PaginatedRequestParams, ReadResourceRequestParams, + ReadResourceResponse, ReadResourceResult, ServerCapabilities, ServerConfig, Tool, ToolAnnotations, +}; use rmcp::service::RequestContext; const DOCUMENT: &str = "photocraft://document"; diff --git a/crates/automation/src/server/progress.rs b/crates/automation/src/server/progress.rs index 4182743083..1844203f8e 100644 --- a/crates/automation/src/server/progress.rs +++ b/crates/automation/src/server/progress.rs @@ -1,5 +1,5 @@ //! Render Video runs on the existing blocking worker; rmcp remains available for ping/cancel. -use super::*; +use super::{CallToolResult, PhotocraftMcp, Value, fail, no_backend, ok_json}; use rmcp::RoleServer; use rmcp::model::ProgressNotificationParam; use rmcp::service::RequestContext; diff --git a/crates/automation/src/server/transport.rs b/crates/automation/src/server/transport.rs index 82e96b13c3..87a98e0305 100644 --- a/crates/automation/src/server/transport.rs +++ b/crates/automation/src/server/transport.rs @@ -1,5 +1,5 @@ //! Recover malformed JSON lines before passing valid messages to rmcp. -use super::*; +use super::{AutomationError, PhotocraftMcp, ServiceExt, Value, json}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use crate::security::MAX_REQUEST_BYTES; diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 63a5b0b8c7..ad5138ef12 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -338,6 +338,10 @@ fn filesystem_commands_fail_closed() { for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}"); } +} + +#[test] +fn filesystem_command_paths_and_profiles_fail_closed() { // The UI-level examples in docs/control-protocol.md. for id in ["view.zoomIn", "window.theme.pro", "edit.search"] { assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}"); diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index 8335009f06..ea868d715e 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -2,7 +2,7 @@ use super::composite::{adjustment_quantum, blend_into, composite_stack}; use super::ctx::Ctx; use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside}; use super::fx_cache::effect_maps; -use super::{Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern}; +use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split}; /// Tile size for parallel rendering (tile results are independent). pub const RENDER_TILE: i32 = 256; diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index d6e04cc38f..d895f14bc9 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -1,6 +1,6 @@ use super::content::{render_content, surface_to_buffer}; use super::ctx::Ctx; -use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks}; +use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks, shape_split}; /// Bounds of a layer's own pixels (union over group children; the canvas /// for fill layers; an artboard's board). diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs index a7b6cc53de..47a06738f8 100644 --- a/crates/engine/src/adjust_params/tests.rs +++ b/crates/engine/src/adjust_params/tests.rs @@ -63,6 +63,11 @@ fn every_kind_round_trips_through_params() { #[test] fn params_reach_the_model() { + basic_params_reach_the_model(); + color_space_params_reach_the_model(); +} + +fn basic_params_reach_the_model() { let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap(); assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true }); let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap(); @@ -82,6 +87,9 @@ fn params_reach_the_model() { assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}"); let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap(); assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0)); +} + +fn color_space_params_reach_the_model() { // CMYK curves: ink channels; Lab: lightness without a composite. let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap(); assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2)); diff --git a/crates/engine/src/cmd/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs index 50a2fec992..ae1ba0a2b8 100644 --- a/crates/engine/src/cmd/adjust_params.rs +++ b/crates/engine/src/cmd/adjust_params.rs @@ -1,6 +1,6 @@ use super::enabled::{check_all_unlocked, is_mask_target, paint_surface}; use super::layer_params::{layer_param, mask_new_layer}; -use super::*; +use super::{Adjustment, ColorMode, EngineError, Layer, LayerContent, Map, Result, Session, Value, json, pixels}; /// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask). pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result { diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 321ca5ebc4..5da802b800 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -1,7 +1,7 @@ use super::descriptors::{color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, long, num, pct, text}; use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; use super::tables::{CHANNELS, channel_key, channel_ref, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Map, Value, json}; // ------------------------------------------------------------------ adjustments diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index b23c578ac6..78d65979bf 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -1,7 +1,7 @@ use super::descriptors::{desc, get_obj, jstr}; use super::events::{event_and_descriptor, event_for}; use super::fields::Mapped; -use super::*; +use super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem, D, DEFAULT_SET, Descriptor, PHOTOSHOP_STEP, UnicodeString, Value, atn, json}; // ------------------------------------------------------------------ import diff --git a/crates/engine/src/cmd/atn_cmds/descriptors.rs b/crates/engine/src/cmd/atn_cmds/descriptors.rs index 0fbecf60da..9e9835218b 100644 --- a/crates/engine/src/cmd/atn_cmds/descriptors.rs +++ b/crates/engine/src/cmd/atn_cmds/descriptors.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Class, D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json}; // ------------------------------------------------------------------ descriptor access diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 6d2fbc4382..3760e6916e 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -16,7 +16,7 @@ use super::steps_layer::{ }; use super::steps_make::{make_from, make_to, set_from, set_to}; use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; -use super::*; +use super::{AtnEvent, D, Descriptor, STOP_MESSAGE, Value, json}; /// An event: code (empty when Photoshop only has a string name), string name, the panel /// label, the command ids it exports (the first is the one simple events import to), and the diff --git a/crates/engine/src/cmd/atn_cmds/fields.rs b/crates/engine/src/cmd/atn_cmds/fields.rs index 8dd32a283c..dcce669a3f 100644 --- a/crates/engine/src/cmd/atn_cmds/fields.rs +++ b/crates/engine/src/cmd/atn_cmds/fields.rs @@ -1,6 +1,6 @@ use super::descriptors::{ang, color_desc, color_hex, enm, get_bool, get_enum, get_num, get_obj, long, pct, px}; use super::tables::{blend_label, blend_ps, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Map, Value, json}; // ------------------------------------------------------------------ field tables diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 9666a443bb..be7bd45151 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -1,5 +1,5 @@ use super::convert::{UniqueNames, export, import}; -use super::*; +use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; pub(super) fn load(s: &mut Session, p: &Value) -> Result { let cmd = "actions.load"; diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs index 36100c1066..12852536ca 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -5,7 +5,7 @@ use super::descriptors::{ }; use super::fields::{Mapped, none, step, steps}; use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Id, Map, ReferenceItem, STOP_MESSAGE, UnicodeString, Value, json}; /// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. pub(super) fn place_from(d: &Descriptor) -> Mapped { diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs index 8ef108f70e..a1b808bf34 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_image.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -5,7 +5,7 @@ use super::descriptors::{ use super::events::pixel_target; use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; use super::tables::{CHANNELS, INTERPOLATION, RADIAL_METHOD, RADIAL_QUALITY, channel_of, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Map, ReferenceItem, UnicodeString, Value, json}; /// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre, /// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs index 36e77d624b..9dbdad579b 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_layer.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -7,7 +7,7 @@ use super::events::pixel_target; use super::fields::{F, Kind, Mapped, fields_to, none, step, steps}; use super::steps_make::is_tool_class; use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json}; pub(super) fn select_from(d: &Descriptor) -> Mapped { let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 696a1f17f8..96f9033102 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -6,7 +6,7 @@ use super::descriptors::{ use super::fields::{Mapped, none, step, steps}; use super::steps_layer::quick_mask_ref; use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_back}; -use super::*; +use super::{D, Descriptor, Id, Map, ReferenceItem, Value, json}; /// A `patternLayer` descriptor's pattern, scale, angle and link as the params of /// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ @@ -59,82 +59,92 @@ const MASK_USING: &[(&str, &str)] = &[ ("HdSl", "layer.layerMask.hideSelection"), ]; +fn duplicate_layer_from_descriptor(d: &Descriptor) -> Option { + let r = get_ref(d, "null")?; + if ref_class(r).as_deref() != Some("Dcmn") || !matches!(target(r), Target::Class) { + return None; + } + let u = get_ref(d, "Usng")?; + if !matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) { + return None; + } + let mut params = layer_target(u)?; + params.insert("document".into(), "new".into()); + if let Some(n) = get_text(d, "Nm ") { + params.insert("documentName".into(), n.into()); + } + if let Some(n) = get_text(d, "LyrN") { + params.insert("name".into(), n.into()); + } + Some(step("layer.duplicate", Value::Object(params))) +} + +fn mask_from_descriptor(d: &Descriptor) -> Option { + let Some(D::Class(c)) = d.get("Nw ") else { return None }; + if trimmed(&c.class_id) != "Chnl" { + return None; + } + let at_mask = + get_ref(d, "At ").is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); + Some(match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { + Some(id) if at_mask => none(id), + _ => Mapped::Unsupported { harmless: false }, + }) +} + +fn new_document_from_descriptor(d: &Descriptor) -> Option { + let nw = get_obj(d, "Nw ")?; + if get_enum(d, "Usng").as_deref() == Some("Slct") { + let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; + let mut mapped_steps = vec![(id, json!({}))]; + if let Some(n) = get_text(nw, "Nm ") { + mapped_steps.push(("layer.setProps", json!({"name": n}))); + } + return Some(steps(mapped_steps)); + } + if get_text(nw, "preset").is_some() { + return Some(none("file.newFromClipboard")); + } + let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) else { + return Some(Mapped::Unsupported { harmless: false }); + }; + let res = get_num(nw, "Rslt").unwrap_or(72.0); + let to_px = |key: &str, value: f64| match nw.get(key) { + Some(D::UnitFloat { unit: PX, .. }) => value, + _ => value * res / 72.0, + }; + let mut params = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); + if let Some(n) = get_text(nw, "Nm ") { + params["name"] = json!(n); + } + if let Some(D::Class(c)) = nw.get("Md ") + && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) + { + params["mode"] = json!(m); + } + if let Some(depth) = get_num(nw, "Dpth") { + params["depth"] = json!(depth); + } + if let Some(fill) = get_enum(nw, "Fl ") { + params["background"] = json!(match fill.as_str() { + "Wht" => "white", + "BckC" => "backgroundColor", + "Trns" => "transparent", + _ => "white", + }); + } + Some(step("file.new", params)) +} + pub(super) fn make_from(d: &Descriptor) -> Mapped { - // Duplicate layer/group into a new document: `Mk` with a document class, a layer - // `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN` - // (the copy's name). A `Dplc` with a `T` document reference (duplicate into another - // open document) stays a kept Photoshop step: document indices mean nothing at replay. - if let Some(r) = get_ref(d, "null") - && ref_class(r).as_deref() == Some("Dcmn") - && matches!(target(r), Target::Class) - && let Some(u) = get_ref(d, "Usng") - && matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) - && let Some(mut p) = layer_target(u) - { - p.insert("document".into(), "new".into()); - if let Some(n) = get_text(d, "Nm ") { - p.insert("documentName".into(), n.into()); - } - if let Some(n) = get_text(d, "LyrN") { - p.insert("name".into(), n.into()); - } - return step("layer.duplicate", Value::Object(p)); + if let Some(mapped) = duplicate_layer_from_descriptor(d) { + return mapped; } - // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals. - if let Some(D::Class(c)) = d.get("Nw ") - && trimmed(&c.class_id) == "Chnl" - { - // The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer. - let at_mask = get_ref(d, "At ") - .is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); - return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { - Some(id) if at_mask => none(id), - _ => Mapped::Unsupported { harmless: false }, - }; + if let Some(mapped) = mask_from_descriptor(d) { + return mapped; } - if let Some(nw) = get_obj(d, "Nw ") { - // Layer via Copy / Cut (`Usng` = the selection), or a new document. - if get_enum(d, "Usng").as_deref() == Some("Slct") { - let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; - let mut v = vec![(id, json!({}))]; - if let Some(n) = get_text(nw, "Nm ") { - v.push(("layer.setProps", json!({"name": n}))); - } - return steps(v); - } - if get_text(nw, "preset").is_some() { - return none("file.newFromClipboard"); - } - if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) { - let res = get_num(nw, "Rslt").unwrap_or(72.0); - // Dimensions are in points (`#Rlt`) unless given in pixels. - let to_px = |k: &str, v: f64| match nw.get(k) { - Some(D::UnitFloat { unit: PX, .. }) => v, - _ => v * res / 72.0, - }; - let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); - if let Some(n) = get_text(nw, "Nm ") { - p["name"] = json!(n); - } - if let Some(D::Class(c)) = nw.get("Md ") - && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) - { - p["mode"] = json!(m); - } - if let Some(depth) = get_num(nw, "Dpth") { - p["depth"] = json!(depth); - } - if let Some(f) = get_enum(nw, "Fl ") { - p["background"] = json!(match f.as_str() { - "Wht" => "white", - "BckC" => "backgroundColor", - "Trns" => "transparent", - _ => "white", - }); - } - return step("file.new", p); - } - return Mapped::Unsupported { harmless: false }; + if let Some(mapped) = new_document_from_descriptor(d) { + return mapped; } let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; let using = get_obj(d, "Usng"); @@ -316,84 +326,91 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option { }) } +fn selection_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + match d.get("T ") { + Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { + "Al" => none("select.all"), + "None" => none("select.deselect"), + "Prvs" => none("select.reselect"), + _ => unsupported, + }, + Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { + (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), + // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). + (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), + (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), + _ => unsupported, + }, + Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { + let pts: Option> = get_list(t, "Pts ") + .unwrap_or(&[]) + .iter() + .map(|v| match v { + D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), + _ => None, + }) + .collect(); + match pts { + Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), + _ => unsupported, + } + } + Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { + let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) else { + return unsupported; + }; + let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); + if t.class_id.is("Elps") { + p["ellipse"] = json!(true); + } + step("select.rect", p) + } + _ => unsupported, + } +} + +fn background_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + // On an image that opened as a normal layer there is no Background to convert; + // Photoshop stops there, but the step's purpose (an editable layer) is met. + // Photoshop's `set` of another layer doesn't target it: the selected layer stays. + let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; + let mut props = Map::new(); + props.insert("layer".into(), "Layer 0".into()); + if let Some(t) = get_obj(d, "T ") { + if let Some(n) = get_text(t, "Nm ") { + props.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { + props.insert("opacity".into(), (o / 100.0).into()); + } + match get_enum(t, "Md ").as_deref() { + None | Some("Nrml") => {} + Some(m) => match blend_label(m) { + Some(label) => { + props.insert("blend".into(), label.into()); + } + None => return unsupported, + }, + } + } + if props.len() > 1 { + v.push(("layer.setProps", Value::Object(props))); + } + steps(v) +} + pub(super) fn set_from(d: &Descriptor) -> Mapped { let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; let unsupported = Mapped::Unsupported { harmless: false }; match (ref_class(r).as_deref(), target(r)) { - (Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") { - Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { - "Al" => none("select.all"), - "None" => none("select.deselect"), - "Prvs" => none("select.reselect"), - _ => unsupported, - }, - Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { - (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), - // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). - (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), - (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), - _ => unsupported, - }, - Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { - let pts: Option> = get_list(t, "Pts ") - .unwrap_or(&[]) - .iter() - .map(|v| match v { - D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), - _ => None, - }) - .collect(); - match pts { - Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), - _ => unsupported, - } - } - Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { - let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) - else { - return unsupported; - }; - let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); - if t.class_id.is("Elps") { - p["ellipse"] = json!(true); - } - step("select.rect", p) - } - _ => unsupported, - }, + (Some("Chnl"), Target::Property(p)) if p == "fsel" => selection_from(d), // Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off. (Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})), // Layer › New › Layer From Background (Photoshop records the New Layer dialog's values // as a `set` of the Background); values other than the defaults then apply to the layer. - (Some("Lyr"), Target::Property(p)) if p == "Bckg" => { - // On an image that opened as a normal layer there is no Background to convert; - // Photoshop stops there, but the step's purpose (an editable layer) is met. - // Photoshop's `set` of another layer doesn't target it: the selected layer stays. - let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; - let mut props = Map::new(); - props.insert("layer".into(), "Layer 0".into()); - if let Some(t) = get_obj(d, "T ") { - if let Some(n) = get_text(t, "Nm ") { - props.insert("name".into(), n.into()); - } - if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { - props.insert("opacity".into(), (o / 100.0).into()); - } - match get_enum(t, "Md ").as_deref() { - None | Some("Nrml") => {} - Some(m) => match blend_label(m) { - Some(label) => { - props.insert("blend".into(), label.into()); - } - None => return unsupported, - }, - } - } - if props.len() > 1 { - v.push(("layer.setProps", Value::Object(props))); - } - steps(v) - } + (Some("Lyr"), Target::Property(p)) if p == "Bckg" => background_from(d), // The toolbox colours. (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) { Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs index 0432f26ac3..0f3bc278e9 100644 --- a/crates/engine/src/cmd/atn_cmds/tables.rs +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -1,5 +1,5 @@ use super::descriptors::{Target, class, code, get_ref, target}; -use super::*; +use super::{D, Descriptor, ReferenceItem}; /// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels. const BLEND_MODES: &[(&str, &str)] = &[ diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live.rs b/crates/engine/src/cmd/brush_cmds/mixer_live.rs index acdd897fd4..3c15001553 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live.rs @@ -1,6 +1,9 @@ //! Incremental Mixer Brush transaction. Source pixels are composed before each dab; //! only the selected target changes. Dropping the transaction cancels it. -use super::*; +use super::{ + EngineError, LiveCommit, MixerSettings, Rect, Result, Session, Stroke, StrokePoint, Surface, Value, bad, check_coords, color, damage_json, doc_cmyk_space, + flag, has_paintable, json, layer_id, num, parse_points, pct, resolve_brush, +}; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::{Document, LayerId}; use photocraft_paint::dynamics::DabGenerator; diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs index 3f45b40c53..9c1d0ea6b8 100644 --- a/crates/engine/src/cmd/channel_cmds/calc.rs +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -2,7 +2,7 @@ use super::manage::gray_document; use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone}; use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec}; use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface}; -use super::*; +use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel}; // --------------------------------------------------------------------------------------------- // Apply Image / Calculations diff --git a/crates/engine/src/cmd/channel_cmds/manage.rs b/crates/engine/src/cmd/channel_cmds/manage.rs index 0aaa045cc7..9c81381bf4 100644 --- a/crates/engine/src/cmd/channel_cmds/manage.rs +++ b/crates/engine/src/cmd/channel_cmds/manage.rs @@ -3,7 +3,9 @@ use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref}; use super::selection::{uniform, unselected_surface}; use super::targeting::target; use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch}; -use super::*; +use super::{ + AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, EngineError, Layer, PixelFormat, Result, Session, Surface, Value, json, list, sel, +}; // --------------------------------------------------------------------------------------------- // Channel management diff --git a/crates/engine/src/cmd/channel_cmds/planes.rs b/crates/engine/src/cmd/channel_cmds/planes.rs index 923b90da54..e027dbb3df 100644 --- a/crates/engine/src/cmd/channel_cmds/planes.rs +++ b/crates/engine/src/cmd/channel_cmds/planes.rs @@ -1,5 +1,5 @@ use super::view::{ChannelTarget, color_names}; -use super::*; +use super::{ColorMode, DocState, Document, PixelFormat, Rect, Surface}; /// The Curves dialog's Channel popup lists only this channel when the Channels panel has a /// single non-composite target (a colour component, layer mask, saved channel or Quick Mask). diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index d18630e95d..58708475da 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -1,6 +1,6 @@ use super::planes::{color_count, edit_mode, luminosity, read_plane, tone}; use super::view::{color_names, composite_name}; -use super::*; +use super::{BlendMode, Document, EngineError, LayerContent, LayerId, Result, Session, Value, blend_channel, from_rgba, sel, to_rgba}; // --------------------------------------------------------------------------------------------- // Channel references diff --git a/crates/engine/src/cmd/channel_cmds/selection.rs b/crates/engine/src/cmd/channel_cmds/selection.rs index 9a24b9fe56..a49c551d2f 100644 --- a/crates/engine/src/cmd/channel_cmds/selection.rs +++ b/crates/engine/src/cmd/channel_cmds/selection.rs @@ -1,7 +1,7 @@ use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane}; use super::refs::{ChanRef, bad, doc_index, parse_ref, source}; use super::view::{ChannelTarget, QuickMaskOptions}; -use super::*; +use super::{AlphaChannel, ColorIndicates, Document, EngineError, PixelFormat, Rect, Result, SelectionMode, Session, Surface, Value, json, operation, sel}; pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result { let cmd = "select.saveSelection"; diff --git a/crates/engine/src/cmd/channel_cmds/spot.rs b/crates/engine/src/cmd/channel_cmds/spot.rs index b1395a3199..773089faad 100644 --- a/crates/engine/src/cmd/channel_cmds/spot.rs +++ b/crates/engine/src/cmd/channel_cmds/spot.rs @@ -2,7 +2,7 @@ use super::manage::{fix_view_now, gray_document}; use super::planes::{channel_format, edit_mode, plane_surface, read_plane, tone}; use super::refs::{ChanRef, alpha_index, bad, gray_plane, native_pixels}; use super::view::{ChannelTarget, ChannelView, color_names}; -use super::*; +use super::{AlphaChannel, ColorMode, DocState, Document, EngineError, Layer, Result, Session, Value, from_rgba, json}; /// Merge Spot Channel: flattens the image and prints the spot ink into the colour channels. pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs index d4ca22c5e5..34e1f269fb 100644 --- a/crates/engine/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine/src/cmd/channel_cmds/targeting.rs @@ -2,7 +2,7 @@ use super::manage::fix_view_now; use super::planes::{color_count, materialize}; use super::refs::{ChanRef, bad, parse_ref}; use super::view::ChannelTarget; -use super::*; +use super::{ColorMode, Document, EngineError, Layer, LayerId, Rect, Result, Session, Surface, TileCoord, Value, from_rgba, json, list}; // --------------------------------------------------------------------------------------------- // Targets for pixel commands diff --git a/crates/engine/src/cmd/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs index 12afd4e9ce..e93be8ff0a 100644 --- a/crates/engine/src/cmd/channel_cmds/view.rs +++ b/crates/engine/src/cmd/channel_cmds/view.rs @@ -1,5 +1,5 @@ use super::planes::color_count; -use super::*; +use super::{AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, Serialize}; // --------------------------------------------------------------------------------------------- // View state diff --git a/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs index e15cc6e080..928f315bdf 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Document, EngineError, Layer, LayerId, PixelFormat, Rect, Result, Session, Surface, Value, bad, bool_or, from_rgba_into, int, json, pixel_layer, + pixel_layer_id, str_or, to_rgba, writable_surface, +}; // ------------------------------------------------------------------ Content-Aware Fill diff --git a/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs index 998f30821a..e0d05742df 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs @@ -1,5 +1,7 @@ use super::content_aware::channel_mask; -use super::*; +use super::{ + Document, EngineError, LayerId, PixelFormat, Rect, Result, Session, Surface, Value, bad, bool_or, f32_or, json, pixel_layer, to_rgba, writable_surface, +}; // ------------------------------------------------------------------ Content-Aware Scale diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs index 5ab5e4455b..14f9b8365d 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/fade.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + BlendMode, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of, + surface_of_mut, to_rgba, +}; // ------------------------------------------------------------------ Fade diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs index 91f16950f1..4b9e3ace73 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value, bad, bool_or, json, layer_param, str_or}; // ------------------------------------------------------------------ Find and Replace Text diff --git a/crates/engine/src/cmd/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs index 8f26426287..abc3a61172 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/presets.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/presets.rs @@ -1,4 +1,4 @@ -use super::*; +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/src/cmd/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs index a422e82bfb..ae0a090a40 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/purge.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/purge.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Result, Session, Value, json}; // ------------------------------------------------------------------ Purge diff --git a/crates/engine/src/cmd/enabled.rs b/crates/engine/src/cmd/enabled.rs index c609b9e0ba..f7b4f00737 100644 --- a/crates/engine/src/cmd/enabled.rs +++ b/crates/engine/src/cmd/enabled.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value}; pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 05d2214186..0506b9dded 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -2,7 +2,7 @@ use super::open::import_at_raw_ppi; use super::paths::{extension, file_name, join, list_images, read_file, stem}; use super::processing::parse_steps; use super::save::{SaveOpts, save_doc}; -use super::*; +use super::{Arc, Document, EngineError, Result, Session, Value, batch_naming, json, str_param}; /// Inputs of a batch command: `"input"` is a folder or an array of files. pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index ef6ad0e056..80213dba16 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -1,6 +1,6 @@ use super::paths::{join, sanitize, stem, write_file}; use super::save::{SaveOpts, encode}; -use super::*; +use super::{ColorMode, Document, EngineError, Layer, LayerContent, LayerId, Rect, Result, Session, Surface, Value, from_rgba_into, json, str_param}; // ---------- Export ---------- diff --git a/crates/engine/src/cmd/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs index e038d0c097..3f9436349d 100644 --- a/crates/engine/src/cmd/file_cmds/info.rs +++ b/crates/engine/src/cmd/file_cmds/info.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{EngineError, Result, Session, Value, json}; // ---------- File Info (XMP) ---------- diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index ff73c338e5..efc44e880f 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -1,5 +1,8 @@ use super::paths::{file_name, read_file, stem, template_name}; -use super::*; +use super::{ + Affine, Arc, Document, EngineError, Layer, LayerContent, Resample, Result, Session, SmartObject, SmartSource, Value, f64_param, flattened_checked, json, + resize_surface, str_param, translate_surface, +}; pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { import_result(name, bytes).map(|r| r.document) diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs index d61e107237..840609d826 100644 --- a/crates/engine/src/cmd/file_cmds/paths.rs +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{EngineError, Result, Session}; // ---------- file system (native only) ---------- diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index b9718aab70..3388f4d7a9 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -2,7 +2,10 @@ use super::batch_run::{batch_inputs_tree, process_tree}; use super::open::import_opened; use super::paths::{file_name, list_images, read_file, stem}; use super::save::SaveOpts; -use super::*; +use super::{ + ColorMode, Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Surface, Value, buffer_surface, flattened_checked, json, size_param, + str_param, +}; // ---------- Automate ---------- diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index 25104a7b13..fff62dc7f4 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -1,5 +1,5 @@ use super::paths::{same_file, write_file}; -use super::*; +use super::{Document, EngineError, Layer, LayerContent, Result, Session, Value, f64_param, flattened_checked, json, str_param}; /// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone /// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" diff --git a/crates/engine/src/cmd/layer_multi_cmds/align.rs b/crates/engine/src/cmd/layer_multi_cmds/align.rs index b6a98f07a0..e7f77fc8fb 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/align.rs @@ -1,7 +1,7 @@ use super::damage::layer_bounds; use super::moves::{move_layers, with_links}; use super::selection::{selected, top_level}; -use super::*; +use super::{Document, EngineError, LayerId, Rect, Result, Session, Value, bad, json}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Edge { diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs index acc49ff88c..129dea0556 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, Layer, LayerContent, LayerId, Rect, Session, VideoData}; /// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents /// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. diff --git a/crates/engine/src/cmd/layer_multi_cmds/moves.rs b/crates/engine/src/cmd/layer_multi_cmds/moves.rs index a8f4a04918..822e0f6ad1 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/moves.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/moves.rs @@ -1,7 +1,7 @@ use super::damage::note_damage; use super::selection::{reselect, same_named_targets, selected, top_level}; use super::structure::check_group_depth; -use super::*; +use super::{Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Value, bad, int_i32, json}; /// A Layers-panel drag of the selected layer records its drop target by name (and which of /// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the diff --git a/crates/engine/src/cmd/layer_multi_cmds/selection.rs b/crates/engine/src/cmd/layer_multi_cmds/selection.rs index 9400760c8e..8f66dfab7c 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/selection.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/selection.rs @@ -1,5 +1,5 @@ use super::moves::{link_groups, recorded_move}; -use super::*; +use super::{DocState, Document, EngineError, Layer, LayerContent, LayerId, Rect, Result, Session, Value, bad, json}; // ---------- selection state ---------- diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 60d193c6d3..70aa512223 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -1,5 +1,5 @@ use super::selection::{reselect, selected, top_level}; -use super::*; +use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Result, Session, Value, bad, json}; // ---------- structural commands ---------- diff --git a/crates/engine/src/cmd/layer_params.rs b/crates/engine/src/cmd/layer_params.rs index 057be4a02c..dddac7ab62 100644 --- a/crates/engine/src/cmd/layer_params.rs +++ b/crates/engine/src/cmd/layer_params.rs @@ -1,5 +1,5 @@ use super::params::bad; -use super::*; +use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; /// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that /// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index 776f47e020..c106af6aac 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -1,6 +1,6 @@ use super::enabled::check_all_unlocked; use super::layer_params::{layer_param, mask_at_depth}; -use super::*; +use super::{Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, json, pixels}; pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { let id = layer_param(s, p)?; diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 0ed899c073..7d78bacccc 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -1,5 +1,5 @@ use super::layer_params::layer_param; -use super::*; +use super::{EngineError, LayerId, Result, Session, Value, json}; // ---------- param helpers ---------- diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index ab66a8f15c..0339c88263 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -7,7 +7,7 @@ use photocraft_paint::MAX_BRUSH_SIZE; use photocraft_paint::retouch::{Region, alpha_index}; use serde_json::{Value, json}; -use super::*; +use super::{EngineError, Result, Session, bad, blend_param, damage_json, parse_brush, run_stroke}; const CMD: &str = "paint.artHistoryBrush"; const MAX_POINTS: usize = 4096; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index 5e5ac27104..1e4ae8ca0e 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -1,6 +1,10 @@ use super::heal::history_source; use super::sampling::{SampleLayers, sample, sample_layers}; -use super::*; +use super::{ + BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, + alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, + reject_huge_stroke, run_stroke, to_rgba, +}; /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, /// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`). diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index efa63e20b2..6e01926e3f 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -34,7 +34,10 @@ use photocraft_algo::content_aware::{FillOptions, color_amount, color_level, fil use photocraft_algo::transform::{Homography, Interp}; use super::patch::{coverage, offset, selection_area, target_layer}; -use super::*; +use super::{ + Document, EngineError, LayerContent, LayerId, Rect, Region, Result, SampleLayers, Session, Surface, Value, alpha_index, bad, clamp_samples, + composite_region, damage_json, flag, has_pixel_layer, json, string, targets_pixels, +}; const CMD: &str = "paint.contentAwareMove"; diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 818c27a6f1..7ff5a600e6 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -1,5 +1,9 @@ use super::sampling::{AllLayers, sample_all_layers}; -use super::*; +use super::{ + BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect, Region, Result, + Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into, + has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, +}; // --------------------------------------------------------------------------------------------- // Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index 79e42723e6..a260443caf 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -1,6 +1,9 @@ use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample}; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; -use super::*; +use super::{ + BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, +}; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). fn pad_coverage(bounds: Rect, cov: &[f32], m: i32) -> (Rect, Vec) { diff --git a/crates/engine/src/cmd/retouch_cmds/patch.rs b/crates/engine/src/cmd/retouch_cmds/patch.rs index f3cb4765a2..557c173b4b 100644 --- a/crates/engine/src/cmd/retouch_cmds/patch.rs +++ b/crates/engine/src/cmd/retouch_cmds/patch.rs @@ -17,7 +17,10 @@ //! (3: 32 of 42 levels, 31 of 102; 10: 35 of 42, 95 of 102). It runs as a background job, like //! the move. -use super::*; +use super::{ + BlendMode, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Surface, Value, apply_coverage, bad, clamp_samples, damage_json, + flag, has_pixel_layer, heal_region, json, point, poisson, run_stroke, string, targets_pixels, +}; const CMD: &str = "paint.patch"; diff --git a/crates/engine/src/cmd/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs index f31542fb5a..242579198e 100644 --- a/crates/engine/src/cmd/retouch_cmds/periodic.rs +++ b/crates/engine/src/cmd/retouch_cmds/periodic.rs @@ -1,6 +1,6 @@ //! Bounded reads from the repeating document tile used by Pattern Preview. -use super::*; +use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, StrokePoint, Surface, alpha_index, apply_coverage, bad}; /// At most four disjoint rectangles in the document tile. Projecting the dirty area separately /// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam. diff --git a/crates/engine/src/cmd/retouch_cmds/remove.rs b/crates/engine/src/cmd/retouch_cmds/remove.rs index 7444826eba..a7283d390b 100644 --- a/crates/engine/src/cmd/retouch_cmds/remove.rs +++ b/crates/engine/src/cmd/retouch_cmds/remove.rs @@ -16,7 +16,10 @@ use super::content_aware_move::{Target, replace}; use super::patch::coverage; -use super::*; +use super::{ + Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleLayers, Session, Stroke, Surface, Value, alpha_index, bad, clamp_samples, + composite_region, damage_json, flag, json, parse_brush, reject_huge_stroke, targets_pixels, +}; use photocraft_doc::Layer; const CMD: &str = "paint.remove"; diff --git a/crates/engine/src/cmd/retouch_cmds/sampling.rs b/crates/engine/src/cmd/retouch_cmds/sampling.rs index 31ab9ae99c..253f6648ad 100644 --- a/crates/engine/src/cmd/retouch_cmds/sampling.rs +++ b/crates/engine/src/cmd/retouch_cmds/sampling.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, Surface, Value, bad, flag, from_rgba_into, string, targets_pixels}; // --------------------------------------------------------------------------------------------- // Sampling sources diff --git a/crates/engine/src/cmd/smart_cmds/contents.rs b/crates/engine/src/cmd/smart_cmds/contents.rs index 393b03e8ac..07a009bf0e 100644 --- a/crates/engine/src/cmd/smart_cmds/contents.rs +++ b/crates/engine/src/cmd/smart_cmds/contents.rs @@ -2,7 +2,10 @@ use super::filters::{smart, smart_mut}; use super::placing::detach_psd; use super::rendering::{refresh, refresh_or_fail, unapplied_filters}; use super::source::{authorized_source_bytes, source_bytes}; -use super::*; +use super::{ + Arc, DocId, Document, EngineError, LayerContent, LayerId, Metadata, Result, Session, SmartContentsId, SmartLink, SmartSource, Value, bad, base_name, + decode_source, encode_source, json, layer_param, other, +}; pub(super) fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> { p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`")) diff --git a/crates/engine/src/cmd/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs index e06cb61a48..3009ecfbc0 100644 --- a/crates/engine/src/cmd/smart_cmds/filters.rs +++ b/crates/engine/src/cmd/smart_cmds/filters.rs @@ -1,6 +1,9 @@ use super::rendering::{refresh_or_fail, refresh_or_fail_in}; use super::source::source_bytes; -use super::*; +use super::{ + BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json, + layer_param, other, +}; pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { match &doc.layer(id).ok_or(EngineError::NoLayer(id))?.content { diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs index 857cb90338..e0472e844d 100644 --- a/crates/engine/src/cmd/smart_cmds/placing.rs +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -1,5 +1,8 @@ use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes}; -use super::*; +use super::{ + Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId, + SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, translate_surface, +}; /// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so /// repeated transforms land back on exact, lossless placements. diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index b686cf3282..a5dd8e8f1b 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -1,6 +1,9 @@ use super::filters::smart; use super::source::{SourceImage, cache_get, cache_key, cache_put, source_bytes, source_image, source_surface, svg_source_image, vector_scale}; -use super::*; +use super::{ + Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject, + SmartSource, Stage, StageKey, Surface, Value, decode_source, other, stack_cache, +}; /// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the /// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode. diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs index 0e0aaee477..d7d895b28d 100644 --- a/crates/engine/src/cmd/smart_cmds/source.rs +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Arc, ColorMode, Document, Layer, LayerContent, LayerId, Metadata, Mutex, PixelFormat, Rect, Result, SampleType, Session, SmartObject, SmartSource, Surface, + base_name, decode_source, json, other, +}; /// A linked file's bytes; `None` when it is missing or its path is not followed /// ([`crate::doc_path::resolve`]). diff --git a/crates/engine/src/cmd/type_caret_cmds.rs b/crates/engine/src/cmd/type_caret_cmds.rs index 3b9b244f70..75ca3e0730 100644 --- a/crates/engine/src/cmd/type_caret_cmds.rs +++ b/crates/engine/src/cmd/type_caret_cmds.rs @@ -320,6 +320,13 @@ mod tests { #[test] fn navigate_words_lines_edges_and_keeps_a_column() { + check_word_moves(); + check_newline_moves(); + check_vertical_column_moves(); + check_navigation_queries_are_read_only(); + } + + fn check_word_moves() { let mut s = session(); let id = create(&mut s, json!({"x": 20, "y": 60, "text": "hello big world", "size": 18})); assert_eq!(go(&mut s, id, 0, "wordNext", None), 5); @@ -334,7 +341,10 @@ mod tests { assert_eq!(go(&mut s, id, 4, "end", None), 15); assert_eq!(go(&mut s, id, 4, "lineStart", None), 0); assert_eq!(go(&mut s, id, 4, "lineEnd", None), 15); + } + fn check_newline_moves() { + let mut s = session(); // A newline is not part of either word; line edges agree with type.info. let id = create(&mut s, json!({"x": 20, "y": 120, "text": "hello\nworld", "size": 18})); assert_eq!(go(&mut s, id, 0, "wordNext", None), 5); @@ -353,7 +363,10 @@ mod tests { assert!((l1s..=l1e).contains(&next), "lineNext {next} not on {l1s}..={l1e}"); assert_eq!(go(&mut s, id, 0, "linePrev", None), 0); assert_eq!(go(&mut s, id, l1e as usize, "lineNext", None), "hello\nworld".chars().count() as u64); + } + fn check_vertical_column_moves() { + let mut s = session(); // Repeated line moves keep the document x of the original column. let id = create(&mut s, json!({"x": 24, "y": 200, "text": "WWWWWW\nI", "size": 28})); let info = s.execute("type.info", json!({"layer": id})).unwrap(); @@ -366,7 +379,13 @@ mod tests { assert_eq!(go(&mut s, id, end0 as usize, "lineNext", Some(x)), start1); assert_eq!(go(&mut s, id, end0 as usize, "lineNext", None), end1); assert_eq!(go(&mut s, id, start1 as usize, "linePrev", Some(x)), lines[0]["start"].as_u64().unwrap()); + } + fn check_navigation_queries_are_read_only() { + let mut s = session(); + let id = create(&mut s, json!({"x": 24, "y": 200, "text": "WWWWWW\nI", "size": 28})); + let caret0 = s.execute("type.caret", json!({"layer": id, "index": 0})).unwrap(); + let x = caret0["segment"][0][0].as_f64().unwrap(); // Queries do not record history or a journal entry. let steps = s.active().unwrap().history.entries().len(); let rev = s.active().unwrap().revision; diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index af90faf5fa..1e103cf89f 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -244,6 +244,13 @@ fn step_char_metrics(t: &mut TextLayer, a: usize, b: usize, p: &Value) -> bool { /// Applies character-style keys from JSON. Returns true if any key was present. pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool { + let mut any = apply_font_props(s, p); + any |= apply_char_values(s, p); + any |= apply_char_features(s, p); + any +} + +fn apply_font_props(s: &mut CharStyle, p: &Value) -> bool { let mut any = false; let mut hit = |b: bool| any |= b; let font_key = ["font", "family", "fontStyle", "weight", "italic"].iter().any(|k| p.get(k).is_some()); @@ -309,6 +316,12 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool { if font_key && s.postscript_name.is_none() { s.postscript_name = installed_postscript(&s.font_family, s.weight, s.italic); } + any +} + +fn apply_char_values(s: &mut CharStyle, p: &Value) -> bool { + let mut any = false; + let mut hit = |b: bool| any |= b; if let Some(v) = f32p(p, "size") { s.size_pt = v.max(0.01); hit(true); @@ -396,6 +409,12 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool { hit(true); } } + any +} + +fn apply_char_features(s: &mut CharStyle, p: &Value) -> bool { + let mut any = false; + let mut hit = |b: bool| any |= b; if let Some(Value::Object(m)) = p.get("features") { for (tag, v) in m { let value = v.as_u64().map(|x| x as u16).or_else(|| v.as_bool().map(u16::from)).unwrap_or(1); diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index 9661877409..6deb13186a 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Color, EngineError, Fill, FillRule, GradientStyle, Knot, LayerId, LineCap, LineJoin, LiveShape, Path, PathOp, Point, Result, Session, ShapeStroke, + StrokeAlign, Subpath, Value, bad, json, +}; pub(crate) fn layer_id(s: &Session, p: &Value) -> Result { match p.get("layer").and_then(Value::as_u64) { diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index 868f2e8313..167cb9d2a6 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -1,6 +1,9 @@ use super::params::{color, f64p, layer_id, op_from, parse_path, path_json}; use super::shape::{map_path, map_shape, transform_shape, with_shape}; -use super::*; +use super::{ + Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad, + blend_from_str, json, sel, vector, +}; // --------------------------------------------------------------------------- // Document paths diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index cdd4885ae0..789fd8f40b 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -2,7 +2,10 @@ use super::params::{ f64p, fill_json, layer_id, live_from_params, live_json, nums, op_from, parse_fill, parse_path, parse_stroke, path_json, radii, stroke_json, }; use super::vector_mask::with; -use super::*; +use super::{ + Affine, Color, Document, EngineError, Fill, FillRule, Layer, LayerContent, LayerId, LiveShape, Path, PathOp, Point, Result, SHAPE_BLOCKS, Session, + ShapeLayer, Value, bad, json, sel, vector, +}; fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> { let d = s.active().ok_or("no document open")?; diff --git a/crates/engine/src/cmd/vector_cmds/vector_mask.rs b/crates/engine/src/cmd/vector_cmds/vector_mask.rs index c21b214d81..34abf1eab0 100644 --- a/crates/engine/src/cmd/vector_cmds/vector_mask.rs +++ b/crates/engine/src/cmd/vector_cmds/vector_mask.rs @@ -1,7 +1,7 @@ use super::params::{layer_id, parse_path, path_json}; use super::paths::{is_work, resolve_path}; use super::shape::with_shape; -use super::*; +use super::{EngineError, LayerContent, LayerId, Path, Result, Session, Value, VectorMask, bad, json, vector}; // --------------------------------------------------------------------------- // Vector masks diff --git a/crates/engine/src/cmd/web_cmds/assets.rs b/crates/engine/src/cmd/web_cmds/assets.rs index 23f2da990c..ff265bb4d6 100644 --- a/crates/engine/src/cmd/web_cmds/assets.rs +++ b/crates/engine/src/cmd/web_cmds/assets.rs @@ -1,6 +1,6 @@ use super::optimizer::{optimize, web_document}; use super::settings::{WebFormat, WebMetadata, WebSettings}; -use super::*; +use super::{Dither, DocId, Document, EngineError, LayerContent, LayerId, Result, Session, Value, is_windows_device_name, join, json, other, stem, write_file}; // ---------- Generate › Image Assets ---------- diff --git a/crates/engine/src/cmd/web_cmds/optimizer.rs b/crates/engine/src/cmd/web_cmds/optimizer.rs index 98116d7d37..14e5fd311d 100644 --- a/crates/engine/src/cmd/web_cmds/optimizer.rs +++ b/crates/engine/src/cmd/web_cmds/optimizer.rs @@ -1,5 +1,5 @@ use super::settings::{WebFormat, WebMetadata, WebSettings}; -use super::*; +use super::{Dither, Document, EngineError, Forced, PaletteKind, Rect, Result, Session, Value, json, other, quantize}; // ---------- the image ---------- diff --git a/crates/engine/src/cmd/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs index c017eb3d2f..916a06f8d2 100644 --- a/crates/engine/src/cmd/web_cmds/quick.rs +++ b/crates/engine/src/cmd/web_cmds/quick.rs @@ -1,6 +1,6 @@ use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; use super::settings::WebSettings; -use super::*; +use super::{EngineError, Result, Session, Value, bad, join, json, other, stem, write_file}; // ---------- Export Preferences / Quick Export ---------- diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs index eeca746754..1e263c2c25 100644 --- a/crates/engine/src/cmd/web_cmds/save_web.rs +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -1,7 +1,7 @@ use super::assets::{asset_output_path, asset_path_components}; use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; use super::settings::{WebSettings, rgb_hex}; -use super::*; +use super::{EngineError, Rect, ResolvedSlice, Result, Session, SliceKind, Value, bad, join, json, other, portable_device_name, slices, stem, write_file}; /// A file-name-safe slice name. fn slice_file(name: &str) -> String { diff --git a/crates/engine/src/cmd/web_cmds/settings.rs b/crates/engine/src/cmd/web_cmds/settings.rs index 19314673c0..a819cf6864 100644 --- a/crates/engine/src/cmd/web_cmds/settings.rs +++ b/crates/engine/src/cmd/web_cmds/settings.rs @@ -1,5 +1,5 @@ use super::optimizer::to8; -use super::*; +use super::{Dither, PaletteKind, Result, Value, bad, json}; // ---------- settings ---------- diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index ef7c9445e4..a3a4af7327 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, layer_multi_cmds, symmetry_cmds}; /// Per-document editing state. #[derive(Clone, Debug)] diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index e033d8db93..635089f7a2 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,4 +1,4 @@ -use super::*; +use super::LayerId; #[derive(Debug, thiserror::Error)] pub enum EngineError { diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 7d0e337d34..e1a7f3755c 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -610,248 +610,260 @@ fn overlay_gradient(g: &mut Gradient, p: &Value) { /// parameter units. Absent (or unparseable) keys leave the effect unchanged, so /// a dialog round trip never touches what it doesn't model: an imported /// gradient stroke keeps its gradient while its opacity is edited. +fn overlay_color(p: &Value, k: &str, c: &mut Color) { + if let Some(x) = color_of(p, k) { + *c = x; + } +} + +fn overlay_contour(p: &Value, key: &str, c: &mut Contour) { + if let Some(x) = p.get(key).and_then(contour_from_param) { + *c = x; + } +} + +fn overlay_bool(p: &Value, key: &str, b: &mut bool) { + if let Some(x) = b_of(p, key) { + *b = x; + } +} + +fn overlay_common(c: &mut FxCommon, p: &Value) { + if let Some(x) = b_of(p, "enabled") { + c.enabled = x; + } + if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) { + c.blend = x; + } + if let Some(x) = f_of(p, "opacity") { + c.opacity = (x / 100.0).clamp(0.0, 1.0); + } +} + +fn overlay_shadow(s: &mut Shadow, p: &Value, inner: bool) { + overlay_common(&mut s.common, p); + overlay_color(p, "color", &mut s.color); + if let Some(x) = f_of(p, "angle") { + s.angle = x; + } + if let Some(x) = b_of(p, "useGlobalLight") { + s.use_global_light = x; + } + if let Some(x) = f_of(p, "distance") { + s.distance = x; + } + if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) { + s.spread = (x / 100.0).clamp(0.0, 1.0); + } + if let Some(x) = f_of(p, "size") { + s.size = x; + } + overlay_contour(p, "contour", &mut s.contour); + overlay_bool(p, "antiAlias", &mut s.anti_alias); + if let Some(x) = f_of(p, "noise") { + s.noise = (x / 100.0).clamp(0.0, 1.0); + } + if !inner && let Some(x) = b_of(p, "knocksOut") { + s.knocks_out = x; + } +} + +fn overlay_glow(g: &mut Glow, p: &Value, inner: bool) { + overlay_common(&mut g.common, p); + if let Some(c) = color_of(p, "color") { + g.paint = FxPaint::Color(c); + } + if let Some(t) = p.get("technique").and_then(Value::as_str) { + g.technique = if t == "precise" { GlowTechnique::Precise } else { GlowTechnique::Softer }; + } + if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) { + g.spread = (x / 100.0).clamp(0.0, 1.0); + } + if let Some(x) = f_of(p, "size") { + g.size = x; + } + overlay_contour(p, "contour", &mut g.contour); + overlay_bool(p, "antiAlias", &mut g.anti_alias); + if let Some(x) = f_of(p, "range") { + g.range = (x / 100.0).clamp(0.01, 1.0); + } + if let Some(x) = f_of(p, "noise") { + g.noise = (x / 100.0).clamp(0.0, 1.0); + } + if inner && let Some(s) = p.get("source").and_then(Value::as_str) { + g.source = if s == "center" { GlowSource::Center } else { GlowSource::Edge }; + } +} + +fn overlay_stroke(s: &mut StrokeFx, p: &Value) { + overlay_common(&mut s.common, p); + if let Some(x) = f_of(p, "size") { + s.size = x; + } + if let Some(pos) = p.get("position").and_then(Value::as_str) { + s.position = match pos { + "inside" => StrokePosition::Inside, + "center" => StrokePosition::Center, + _ => StrokePosition::Outside, + }; + } + overlay_bool(p, "overprint", &mut s.overprint); + if p.get("from").is_some() { + s.paint = FxPaint::Gradient(gradient(p)); + } else if let Some(c) = color_of(p, "color") { + s.paint = FxPaint::Color(c); + } +} + +fn overlay_pattern(fx: &mut Effect, p: &Value) { + let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = fx else { return }; + overlay_common(common, p); + if let Some(x) = p.get("pattern").and_then(Value::as_str) { + *name = x.to_string(); + *id = String::new(); + } + if let Some(x) = f_of(p, "scale") { + *scale = (x / 100.0).clamp(0.01, 10.0); + } + if let Some(x) = f_of(p, "angle") { + *angle = x; + } + if let Some(x) = b_of(p, "link") { + *link = x; + } + if let Some(x) = f_of(p, "phaseX") { + phase.0 = x; + } + if let Some(x) = f_of(p, "phaseY") { + phase.1 = x; + } +} + +fn overlay_satin(s: &mut Satin, p: &Value) { + overlay_common(&mut s.common, p); + overlay_color(p, "color", &mut s.color); + if let Some(x) = f_of(p, "angle") { + s.angle = x; + } + if let Some(x) = f_of(p, "distance") { + s.distance = x; + } + if let Some(x) = f_of(p, "size") { + s.size = x; + } + if let Some(x) = b_of(p, "invert") { + s.invert = x; + } + overlay_contour(p, "contour", &mut s.contour); + overlay_bool(p, "antiAlias", &mut s.anti_alias); +} + +fn overlay_bevel(bv: &mut Bevel, p: &Value) { + if let Some(x) = b_of(p, "enabled") { + bv.enabled = x; + } + if let Some(s) = p.get("style").and_then(Value::as_str) { + bv.style = match s { + "outer" => BevelStyle::OuterBevel, + "emboss" => BevelStyle::Emboss, + "pillow" => BevelStyle::PillowEmboss, + "stroke" => BevelStyle::StrokeEmboss, + _ => BevelStyle::InnerBevel, + }; + } + if let Some(t) = p.get("technique").and_then(Value::as_str) { + bv.technique = match t { + "chiselHard" => BevelTechnique::ChiselHard, + "chiselSoft" => BevelTechnique::ChiselSoft, + _ => BevelTechnique::Smooth, + }; + } + if let Some(x) = f_of(p, "depth") { + bv.depth = x / 100.0; + } + if let Some(d) = p.get("direction").and_then(Value::as_str) { + bv.up = d != "down"; + } + if let Some(x) = f_of(p, "size") { + bv.size = x; + } + if let Some(x) = f_of(p, "soften") { + bv.soften = x; + } + if let Some(x) = f_of(p, "angle") { + bv.angle = x; + } + if let Some(x) = f_of(p, "altitude") { + bv.altitude = x; + } + if let Some(x) = b_of(p, "useGlobalLight") { + bv.use_global_light = x; + } + overlay_contour(p, "glossContour", &mut bv.gloss_contour); + overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias); + if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) { + bv.highlight.blend = blend; + } + if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) { + bv.shadow.blend = blend; + } + overlay_color(p, "highlightColor", &mut bv.highlight_color); + overlay_color(p, "shadowColor", &mut bv.shadow_color); + if let Some(x) = f_of(p, "highlightOpacity") { + bv.highlight.opacity = (x / 100.0).clamp(0.0, 1.0); + } + if let Some(x) = f_of(p, "shadowOpacity") { + bv.shadow.opacity = (x / 100.0).clamp(0.0, 1.0); + } + match b_of(p, "contour") { + Some(false) => bv.contour = None, + Some(true) if bv.contour.is_none() => bv.contour = Some(photocraft_doc::BevelContour::default()), + _ => {} + } + if let Some(c) = &mut bv.contour { + overlay_contour(p, "contourName", &mut c.contour); + if let Some(x) = f_of(p, "contourRange") { + c.range = (x / 100.0).clamp(0.01, 1.0); + } + overlay_bool(p, "contourAntiAlias", &mut c.anti_alias); + } + if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) { + bv.texture = Some(photocraft_doc::BevelTexture { + name: t.to_string(), + id: t.to_string(), + scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0), + depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0), + invert: b(p, "textureInvert", false), + link: b(p, "textureLink", true), + phase: (0.0, 0.0), + }); + } +} + pub fn overlay_effect(fx: &mut Effect, p: &Value) { if crate::commands::check_f32_values("layer.layerStyle", p).is_err() { return; } - fn set_color(p: &Value, k: &str, c: &mut Color) { - if let Some(x) = color_of(p, k) { - *c = x; - } - } - fn set_contour(p: &Value, key: &str, c: &mut Contour) { - if let Some(x) = p.get(key).and_then(contour_from_param) { - *c = x; - } - } - fn set_bool(p: &Value, key: &str, b: &mut bool) { - if let Some(x) = b_of(p, key) { - *b = x; - } - } - fn common(c: &mut FxCommon, p: &Value) { - if let Some(x) = b_of(p, "enabled") { - c.enabled = x; - } - if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) { - c.blend = x; - } - if let Some(x) = f_of(p, "opacity") { - c.opacity = (x / 100.0).clamp(0.0, 1.0); - } - } - let inner_shadow = matches!(fx, Effect::InnerShadow(_)); - let inner_glow = matches!(fx, Effect::InnerGlow(_)); match fx { - Effect::DropShadow(s) | Effect::InnerShadow(s) => { - let inner = inner_shadow; - common(&mut s.common, p); - set_color(p, "color", &mut s.color); - if let Some(x) = f_of(p, "angle") { - s.angle = x; - } - if let Some(x) = b_of(p, "useGlobalLight") { - s.use_global_light = x; - } - if let Some(x) = f_of(p, "distance") { - s.distance = x; - } - if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) { - s.spread = (x / 100.0).clamp(0.0, 1.0); - } - if let Some(x) = f_of(p, "size") { - s.size = x; - } - set_contour(p, "contour", &mut s.contour); - set_bool(p, "antiAlias", &mut s.anti_alias); - if let Some(x) = f_of(p, "noise") { - s.noise = (x / 100.0).clamp(0.0, 1.0); - } - if !inner && let Some(x) = b_of(p, "knocksOut") { - s.knocks_out = x; - } + Effect::DropShadow(s) => overlay_shadow(s, p, false), + Effect::InnerShadow(s) => overlay_shadow(s, p, true), + Effect::OuterGlow(g) => overlay_glow(g, p, false), + Effect::InnerGlow(g) => overlay_glow(g, p, true), + Effect::Stroke(s) => overlay_stroke(s, p), + Effect::ColorOverlay { common, color } => { + overlay_common(common, p); + overlay_color(p, "color", color); } - Effect::OuterGlow(g) | Effect::InnerGlow(g) => { - let inner = inner_glow; - common(&mut g.common, p); - if let Some(c) = color_of(p, "color") { - g.paint = FxPaint::Color(c); - } - if let Some(t) = p.get("technique").and_then(Value::as_str) { - g.technique = if t == "precise" { GlowTechnique::Precise } else { GlowTechnique::Softer }; - } - if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) { - g.spread = (x / 100.0).clamp(0.0, 1.0); - } - if let Some(x) = f_of(p, "size") { - g.size = x; - } - set_contour(p, "contour", &mut g.contour); - set_bool(p, "antiAlias", &mut g.anti_alias); - if let Some(x) = f_of(p, "range") { - g.range = (x / 100.0).clamp(0.01, 1.0); - } - if let Some(x) = f_of(p, "noise") { - g.noise = (x / 100.0).clamp(0.0, 1.0); - } - if inner && let Some(s) = p.get("source").and_then(Value::as_str) { - g.source = if s == "center" { GlowSource::Center } else { GlowSource::Edge }; - } - } - Effect::Stroke(s) => { - common(&mut s.common, p); - if let Some(x) = f_of(p, "size") { - s.size = x; - } - if let Some(pos) = p.get("position").and_then(Value::as_str) { - s.position = match pos { - "inside" => StrokePosition::Inside, - "center" => StrokePosition::Center, - _ => StrokePosition::Outside, - }; - } - set_bool(p, "overprint", &mut s.overprint); - if p.get("from").is_some() { - s.paint = FxPaint::Gradient(gradient(p)); - } else if let Some(c) = color_of(p, "color") { - s.paint = FxPaint::Color(c); - } - } - Effect::ColorOverlay { common: c, color } => { - common(c, p); - set_color(p, "color", color); - } - Effect::GradientOverlay { common: c, gradient: g, dither, interpolation } => { - common(c, p); - gradient_overlay::overlay(g, interpolation, p); + Effect::GradientOverlay { common, gradient, dither, interpolation } => { + overlay_common(common, p); + gradient_overlay::overlay(gradient, interpolation, p); if let Some(x) = b_of(p, "dither") { *dither = x; } } - Effect::PatternOverlay { common: c, name, id, scale, angle, link, phase } => { - common(c, p); - if let Some(x) = p.get("pattern").and_then(Value::as_str) { - *name = x.to_string(); - *id = String::new(); - } - if let Some(x) = f_of(p, "scale") { - *scale = (x / 100.0).clamp(0.01, 10.0); - } - if let Some(x) = f_of(p, "angle") { - *angle = x; - } - if let Some(x) = b_of(p, "link") { - *link = x; - } - if let Some(x) = f_of(p, "phaseX") { - phase.0 = x; - } - if let Some(x) = f_of(p, "phaseY") { - phase.1 = x; - } - } - Effect::Satin(s) => { - common(&mut s.common, p); - set_color(p, "color", &mut s.color); - if let Some(x) = f_of(p, "angle") { - s.angle = x; - } - if let Some(x) = f_of(p, "distance") { - s.distance = x; - } - if let Some(x) = f_of(p, "size") { - s.size = x; - } - if let Some(x) = b_of(p, "invert") { - s.invert = x; - } - set_contour(p, "contour", &mut s.contour); - set_bool(p, "antiAlias", &mut s.anti_alias); - } - Effect::BevelEmboss(bv) => { - if let Some(x) = b_of(p, "enabled") { - bv.enabled = x; - } - if let Some(s) = p.get("style").and_then(Value::as_str) { - bv.style = match s { - "outer" => BevelStyle::OuterBevel, - "emboss" => BevelStyle::Emboss, - "pillow" => BevelStyle::PillowEmboss, - "stroke" => BevelStyle::StrokeEmboss, - _ => BevelStyle::InnerBevel, - }; - } - if let Some(t) = p.get("technique").and_then(Value::as_str) { - bv.technique = match t { - "chiselHard" => BevelTechnique::ChiselHard, - "chiselSoft" => BevelTechnique::ChiselSoft, - _ => BevelTechnique::Smooth, - }; - } - if let Some(x) = f_of(p, "depth") { - bv.depth = x / 100.0; - } - if let Some(d) = p.get("direction").and_then(Value::as_str) { - bv.up = d != "down"; - } - if let Some(x) = f_of(p, "size") { - bv.size = x; - } - if let Some(x) = f_of(p, "soften") { - bv.soften = x; - } - if let Some(x) = f_of(p, "angle") { - bv.angle = x; - } - if let Some(x) = f_of(p, "altitude") { - bv.altitude = x; - } - if let Some(x) = b_of(p, "useGlobalLight") { - bv.use_global_light = x; - } - set_contour(p, "glossContour", &mut bv.gloss_contour); - set_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias); - // Keep imported PSD shading settings when a command edits other bevel fields. - if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) { - bv.highlight.blend = blend; - } - if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) { - bv.shadow.blend = blend; - } - set_color(p, "highlightColor", &mut bv.highlight_color); - set_color(p, "shadowColor", &mut bv.shadow_color); - if let Some(x) = f_of(p, "highlightOpacity") { - bv.highlight.opacity = (x / 100.0).clamp(0.0, 1.0); - } - if let Some(x) = f_of(p, "shadowOpacity") { - bv.shadow.opacity = (x / 100.0).clamp(0.0, 1.0); - } - // The Contour element: `contour` turns it on/off; its curve, Range and - // Anti-aliased edit the element in place, so an imported curve survives. - match b_of(p, "contour") { - Some(false) => bv.contour = None, - Some(true) if bv.contour.is_none() => bv.contour = Some(photocraft_doc::BevelContour::default()), - _ => {} - } - if let Some(c) = &mut bv.contour { - set_contour(p, "contourName", &mut c.contour); - if let Some(x) = f_of(p, "contourRange") { - c.range = (x / 100.0).clamp(0.01, 1.0); - } - set_bool(p, "contourAntiAlias", &mut c.anti_alias); - } - if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) { - bv.texture = Some(photocraft_doc::BevelTexture { - name: t.to_string(), - id: t.to_string(), - scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0), - depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0), - invert: b(p, "textureInvert", false), - link: b(p, "textureLink", true), - phase: (0.0, 0.0), - }); - } - } + Effect::PatternOverlay { .. } => overlay_pattern(fx, p), + Effect::Satin(s) => overlay_satin(s, p), + Effect::BevelEmboss(bv) => overlay_bevel(bv, p), } } diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs index b8f92356da..982bf209ab 100644 --- a/crates/engine/src/prefs/cmds.rs +++ b/crates/engine/src/prefs/cmds.rs @@ -1,6 +1,6 @@ use super::customize::{keyboard_shortcuts, menus}; use super::validate::{SECTIONS, get_path, keyed}; -use super::*; +use super::{CommandSpec, EngineError, Map, Result, Session, ToolbarCustomization, Value, json}; // ------------------------------------------------------------------ commands diff --git a/crates/engine/src/prefs/customize.rs b/crates/engine/src/prefs/customize.rs index e6d76723c8..bfad131ba1 100644 --- a/crates/engine/src/prefs/customize.rs +++ b/crates/engine/src/prefs/customize.rs @@ -1,7 +1,7 @@ use super::cmds::bad; use super::files::{file_target, read_text_file, rename_path, writable, write_files_atomically}; use super::shortcuts::{BindKind, alternate_keys, bindable, bindable_items, conflicts, default_alternates, is_tool, normalize_shortcut, reserved_shortcut}; -use super::*; +use super::{MenuCustomization, Preferences, Result, Session, Value, json}; /// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts. pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { @@ -108,65 +108,7 @@ pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => &empty, Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?, }; - if !set.is_empty() || !alts.is_empty() { - let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); - changed = true; - // Reserved system keys can't be bound, by hand or from a file. - let reserved = |v: &Value| -> Option { - let keys = match v { - Value::String(s) => vec![s.clone()], - other => alternate_keys(other).unwrap_or_default(), - }; - keys.into_iter().find(|k| reserved_shortcut(k)) - }; - if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { - return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); - } - for (id, v) in set { - if !bindable().any(|(b, _)| b == id) && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - for (id, v) in alts { - if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - // Like Photoshop, a shortcut moved to a new command is taken away from the old one, - // whether the old one held it as its main key or as an alternate (#3665). - if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { - let assigned: Vec<(&str, String)> = set - .iter() - .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) - .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) - .collect(); - for (id, sc) in assigned { - for (c, def) in bindable() { - // Tools may share a key: they cycle with Shift, as Photoshop's groups do. - if is_tool(id) && is_tool(c) { - continue; - } - // Never strip a command that this same call is assigning: - // two entries for one key are a clash inside the call, which - // the returned conflicts list reports (#719). Stripping - // each other here unbound both silently. - if c == id || set.contains_key(c) || alts.contains_key(c) { - continue; - } - let main = next.shortcut(c, def).map(str::to_string); - if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { - next.shortcuts.insert(c.to_string(), String::new()); - } - let held = next.alternates(c, main.as_deref()); - if held.contains(&sc) { - next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); - } - } - } - } - } + changed |= apply_shortcut_changes(&mut next, p, set, alts, cmd)?; // Then the sets are saved, deleted or switched, from the bindings as they now stand. changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?; // The reply and the exports read the bindings as they will be; they are committed only once @@ -262,6 +204,75 @@ pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { Ok(out) } +fn apply_shortcut_changes( + next: &mut Preferences, + p: &Value, + set: &serde_json::Map, + alts: &serde_json::Map, + cmd: &str, +) -> Result { + if set.is_empty() && alts.is_empty() { + return Ok(false); + } + let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); + // Reserved system keys can't be bound, by hand or from a file. + let reserved = |v: &Value| -> Option { + let keys = match v { + Value::String(s) => vec![s.clone()], + other => alternate_keys(other).unwrap_or_default(), + }; + keys.into_iter().find(|k| reserved_shortcut(k)) + }; + if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { + return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); + } + for (id, v) in set { + if !bindable().any(|(b, _)| b == id) && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + for (id, v) in alts { + if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + // Like Photoshop, a shortcut moved to a new command is taken away from the old one, + // whether the old one held it as its main key or as an alternate (#3665). + if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { + let assigned: Vec<(&str, String)> = set + .iter() + .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) + .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) + .collect(); + for (id, sc) in assigned { + for (c, def) in bindable() { + // Tools may share a key: they cycle with Shift, as Photoshop's groups do. + if is_tool(id) && is_tool(c) { + continue; + } + // Never strip a command that this same call is assigning: + // two entries for one key are a clash inside the call, which + // the returned conflicts list reports (#719). Stripping + // each other here unbound both silently. + if c == id || set.contains_key(c) || alts.contains_key(c) { + continue; + } + let main = next.shortcut(c, def).map(str::to_string); + if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { + next.shortcuts.insert(c.to_string(), String::new()); + } + let held = next.alternates(c, main.as_deref()); + if held.contains(&sc) { + next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); + } + } + } + } + Ok(true) +} + /// Edit › Menus: hide/show items and give them colours. pub(super) fn menus(s: &mut Session, p: &Value) -> Result { let ids = |k: &str| -> Vec { diff --git a/crates/engine/src/prefs/files.rs b/crates/engine/src/prefs/files.rs index d24205228a..c58604e71d 100644 --- a/crates/engine/src/prefs/files.rs +++ b/crates/engine/src/prefs/files.rs @@ -1,5 +1,5 @@ use super::cmds::bad; -use super::*; +use super::{Result, Value}; /// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object /// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` → diff --git a/crates/engine/src/prefs/shortcuts.rs b/crates/engine/src/prefs/shortcuts.rs index 47ba5a5f83..337c8e3754 100644 --- a/crates/engine/src/prefs/shortcuts.rs +++ b/crates/engine/src/prefs/shortcuts.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{BTreeMap, Value}; /// Most further keys one command may hold; Photoshop's own defaults use one. pub const MAX_ALTERNATES: usize = 8; diff --git a/crates/engine/src/prefs/store.rs b/crates/engine/src/prefs/store.rs index 2e0c3e7576..6ed7aa4a7c 100644 --- a/crates/engine/src/prefs/store.rs +++ b/crates/engine/src/prefs/store.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Deserialize, Map, Preferences, Serialize, Value}; // ------------------------------------------------------------------ store diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index af637f90d9..37d0fdf022 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -1,5 +1,10 @@ use super::shortcuts::normalize_shortcut; -use super::*; +use super::{ + AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, DarkTheme, ExportLocation, ExportMetadata, FontPreview, + GpuBackend, Interpolation, LightTheme, LineStyle, LinuxDisplayServer, LogDestination, LogDetail, OtherCursor, PaintingCursor, PointSize, PressureCurve, + QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TextEngine, Theme, TypeUnit, UiFontSize, UiScale, + Unit, Value, +}; /// Preferences dialog sections in Photoshop's order: (id, title). pub const SECTIONS: [(&str, &str); 18] = [ diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 90b7883f0b..d1f360e573 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,6 +1,9 @@ use super::doc_state::DocState; use super::error::{EngineError, Result}; -use super::*; +use super::{ + Arc, Document, LayerId, LayerTarget, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds, smart_cmds, + type_cmds, +}; mod documents; mod execute; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 668bb36e07..1ae07b35a8 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -1,5 +1,5 @@ use super::history::fix_selection; -use super::*; +use super::{DocState, Document, Session, channel_cmds, smart_cmds}; /// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when /// `i` is out of range. diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index d0f7071fc9..69c389f0c6 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -1,5 +1,8 @@ -use super::history::fix_selection; -use super::*; +use super::history::{fix_selection, visibility_changes}; +use super::{ + Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds, + smart_cmds, +}; impl Session { /// Run a command by id with JSON params. Returns a JSON result. diff --git a/crates/engine/src/session/history.rs b/crates/engine/src/session/history.rs index a4e91eaf6a..b6e81e64bc 100644 --- a/crates/engine/src/session/history.rs +++ b/crates/engine/src/session/history.rs @@ -1,5 +1,5 @@ use super::documents::fix_active; -use super::*; +use super::{Arc, DocState, Document, LayerId, LayerTarget, Session, channel_cmds, layer_multi_cmds}; impl Session { pub fn undo(&mut self) -> bool { diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index b6e5d1c688..b8ea5ea89d 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -1,5 +1,5 @@ use super::history::fix_selection; -use super::*; +use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, type_cmds}; impl Session { /// Replace the active document's active layer without creating a history step. diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs index 3f8a2d9e55..94b7bc4014 100644 --- a/crates/io/src/psd_export/merged.rs +++ b/crates/io/src/psd_export/merged.rs @@ -196,6 +196,8 @@ pub(super) fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { #[cfg(test)] mod tests { use super::*; + use photocraft_doc::{Layer, LayerContent}; + use photocraft_raster::Surface; fn previous_merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool) -> (Vec, bool, bool) { if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, &Interrupt::NONE) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2ce599e30e..df7389c890 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,5 +1,13 @@ use super::services::{ExportSettings, FormatChoices, SAVE_OPTIONS_OPEN, SaveKind, Services, plain_raster, saved_revision_after_write}; -use super::*; +use super::{ + ControlRequest, DocId, Document, HashMap, PhotocraftApp, Receiver, Session, SyntheticTarget, Tool, UiState, Value, actions, analysis_ui, brush_panel, + brush_picker, camera_raw_ui, canvas, dds_options_ui, delete_layer_prompt, dialogs, discard_ui, distort_ui, dock, field_wheel, file_open, + filter_preview_worker, gpu_canvas, gpu_status, gradient_ui, histogram_panel, i18n, jobs_ui, jpeg_options_ui, json, kys_import, last_brush, layers_panel_ui, + mask_thumbs_ui, mask_trash_prompt, monitor_status, native_menu, notices, open_prompt, paint_mouse, palette, panel_docking, panels, prefs_ui, + preset_files_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, single_line_drag, state, stroke_trace, stylus, + targa_options_ui, text_field_menu, theme, tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool, + type_transform, updates_ui, vector_ui, view_cmds, wheel_nav, wide_angle_ui, widgets, work_area, workspace_ui, +}; mod clipboard; mod commands; diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 0b268f2b9b..5a3cad5012 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -1,4 +1,4 @@ -use super::*; +use super::PhotocraftApp; fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { let mut sig = (w as u64) << 32 | h as u64; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1ae200be26..9e7e986d69 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + DocId, PhotocraftApp, Tool, Value, actions, canvas, delete_layer_prompt, dock, gpu_canvas, jobs_ui, json, mask_trash_prompt, notices, panel_docking, state, + transform_tool, type_transform, vector_ui, +}; impl PhotocraftApp { /// Run an engine command, reporting errors in the status bar. @@ -115,82 +118,7 @@ impl PhotocraftApp { jobs_ui::run(self, id, params) }; let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer."); - if r.is_ok() && ADDS_LAYER_MASK.contains(&id) { - // Adding an explicit mask targets it, as in Photoshop (#2166). - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - self.ui.properties_layer = None; - } else if r.is_ok() && creates_adjustment_or_fill { - // Panel Options may suppress a fill layer's default mask. Never target a - // nonexistent mask; an active path creates a vector mask instead. - let masks = self - .session - .active() - .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) - .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) - .unwrap_or((false, false)); - self.ui.mask_target = masks.0; - self.ui.vector_mask_target = !masks.0 && masks.1; - // Keep Properties on the new layer contents, as on main (#3369). - self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); - } - if r.is_ok() && creates_adjustment_or_fill { - // Properties comes to the front, shown and expanded, so the new layer's settings can - // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. - if self.ui.docking.is_some() { - let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); - } else { - self.ui.dock_tabs.properties = 0; - dock::reveal(self, dock::Group::Properties); - } - } - // Making a new selection reveals its outline after View > Extras was hidden (#5597). - // These interactive selection commands complete inline; a failed command, deselection, - // or painting inside an existing selection must leave the user's view choice alone. - if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) - && matches!( - id, - "select.rect" - | "select.lasso" - | "select.magneticLasso" - | "select.magicWand" - | "select.quick" - | "select.object" - | "select.loadSelection" - | "select.loadLuminosity" - | "path.toSelection" - ) - && self.session.active().is_some_and(|st| st.doc.selection.is_some()) - { - self.ui.view.extras = true; - } - if r.is_ok() && id == "select.toWorkPath" { - // Make Work Path selects the new work path in the Paths panel, as in Photoshop. - self.ui.selected_path = Some("work".into()); - } - if r.is_ok() && path_mask { - // The new layer's vector mask becomes the active path, as in Photoshop: the path it - // was made from is no longer selected, so the next fill layer isn't masked by it too. - self.ui.selected_path = Some("layer".into()); - } - if r.is_ok() && creates_active_mask { - // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - } - if r.is_ok() && creates_active_vector_mask { - // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a - // mask made from a path becomes the active path. - self.ui.vector_mask_target = true; - self.ui.mask_target = false; - if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { - self.ui.selected_path = Some("layer".into()); - } - } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { - self.clip_external = false; - self.export_os_clipboard(); - } + self.sync_command_side_effects(id, &r, creates_active_mask, creates_active_vector_mask, creates_adjustment_or_fill, path_mask); self.perf.last_command = id.to_string(); self.perf.command_ms = gpu_canvas::now_ms() - t0; match &r { @@ -227,6 +155,93 @@ impl PhotocraftApp { self.tool_override.unwrap_or(self.ui.tool) } + fn sync_command_side_effects( + &mut self, + id: &str, + result: &Result, + creates_active_mask: bool, + creates_active_vector_mask: bool, + creates_adjustment_or_fill: bool, + path_mask: bool, + ) { + if result.is_ok() && ADDS_LAYER_MASK.contains(&id) { + // Adding an explicit mask targets it, as in Photoshop (#2166). + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + self.ui.properties_layer = None; + } else if result.is_ok() && creates_adjustment_or_fill { + // Panel Options may suppress a fill layer's default mask. Never target a + // nonexistent mask; an active path creates a vector mask instead. + let masks = self + .session + .active() + .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) + .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) + .unwrap_or((false, false)); + self.ui.mask_target = masks.0; + self.ui.vector_mask_target = !masks.0 && masks.1; + // Keep Properties on the new layer contents, as on main (#3369). + self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + if result.is_ok() && creates_adjustment_or_fill { + // Properties comes to the front, shown and expanded, so the new layer's settings can + // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. + if self.ui.docking.is_some() { + let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); + } else { + self.ui.dock_tabs.properties = 0; + dock::reveal(self, dock::Group::Properties); + } + } + // Making a new selection reveals its outline after View > Extras was hidden (#5597). + // These interactive selection commands complete inline; a failed command, deselection, + // or painting inside an existing selection must leave the user's view choice alone. + if result.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) + && matches!( + id, + "select.rect" + | "select.lasso" + | "select.magneticLasso" + | "select.magicWand" + | "select.quick" + | "select.object" + | "select.loadSelection" + | "select.loadLuminosity" + | "path.toSelection" + ) + && self.session.active().is_some_and(|st| st.doc.selection.is_some()) + { + self.ui.view.extras = true; + } + if result.is_ok() && id == "select.toWorkPath" { + // Make Work Path selects the new work path in the Paths panel, as in Photoshop. + self.ui.selected_path = Some("work".into()); + } + if result.is_ok() && path_mask { + // The new layer's vector mask becomes the active path, as in Photoshop: the path it + // was made from is no longer selected, so the next fill layer isn't masked by it too. + self.ui.selected_path = Some("layer".into()); + } + if result.is_ok() && creates_active_mask { + // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + } + if result.is_ok() && creates_active_vector_mask { + // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a + // mask made from a path becomes the active path. + self.ui.vector_mask_target = true; + self.ui.mask_target = false; + if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { + self.ui.selected_path = Some("layer".into()); + } + } + if result.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { + self.clip_external = false; + self.export_os_clipboard(); + } + } + pub fn sync_views(&mut self) { type_transform::cancel_stale(self); crate::cam_transform::cancel_stale(self); diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index e6005b6782..425742d519 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{ControlRequest, PhotocraftApp, Receiver}; impl PhotocraftApp { /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ebd30492de..97b25ddb40 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + DocId, ExportSettings, FormatChoices, PhotocraftApp, SAVE_OPTIONS_OPEN, SaveKind, Value, camera_raw_ui, dds_options_ui, file_open, jobs_ui, + jpeg_options_ui, json, notices, open_prompt, plain_raster, preset_files_ui, saved_revision_after_write, targa_options_ui, tiff_options_ui, +}; impl PhotocraftApp { /// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 6969db33c1..566a37ad11 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,4 +1,10 @@ -use super::*; +use super::{ + PhotocraftApp, analysis_ui, brush_panel, brush_picker, camera_raw_ui, canvas, dds_options_ui, dialogs, discard_ui, distort_ui, field_wheel, file_open, + filter_preview_worker, gpu_canvas, gpu_status, gradient_ui, i18n, jobs_ui, jpeg_options_ui, kys_import, last_brush, layers_panel_ui, monitor_status, + native_menu, notices, paint_mouse, palette, panels, prefs_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, targa_options_ui, + text_field_menu, theme, tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool, updates_ui, vector_ui, + view_cmds, wide_angle_ui, work_area, workspace_ui, +}; impl PhotocraftApp { /// Wait out the rest of [`Self::min_frame_ms`] since the last frame started. diff --git a/crates/ui-egui/src/app/gpu.rs b/crates/ui-egui/src/app/gpu.rs index 73c08338ed..055a85e0fd 100644 --- a/crates/ui-egui/src/app/gpu.rs +++ b/crates/ui-egui/src/app/gpu.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, gpu_canvas, gpu_status}; impl PhotocraftApp { /// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures. diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs index a0fa5b193f..3200f15869 100644 --- a/crates/ui-egui/src/app/ime.rs +++ b/crates/ui-egui/src/app/ime.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, type_tool}; impl PhotocraftApp { /// Install the callback-mode markers in an app creator, before the first `run_ui` on this diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 9b26957e58..7897e3a655 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, SyntheticTarget}; /// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic /// input). A no-op when the run is not present. diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 0e19c3a88e..f1a111f190 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, dock, panel_docking, single_line_drag, text_field_menu, theme, tool_cursor, wheel_nav}; impl PhotocraftApp { /// Records a picked type family for the font menu's Recent group, capped by diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs index 41ff5feff4..d46a1878e0 100644 --- a/crates/ui-egui/src/app/screenshot.rs +++ b/crates/ui-egui/src/app/screenshot.rs @@ -1,4 +1,4 @@ -use super::*; +use super::PhotocraftApp; impl PhotocraftApp { /// Issue due screenshot requests. UI phase only: settling counts real layout passes, and the diff --git a/crates/ui-egui/src/app/targets.rs b/crates/ui-egui/src/app/targets.rs index 8a22273b69..fbdc91c8a7 100644 --- a/crates/ui-egui/src/app/targets.rs +++ b/crates/ui-egui/src/app/targets.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, Value, mask_thumbs_ui}; /// The active layer is an adjustment layer. It has no pixels, so painting and filling it edit its /// mask even when its icon thumbnail, not the mask, is the Layers panel's target, as in diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index a5a52ccffc..7ba8fb1db6 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{DocId, Document, PhotocraftApp, mask_thumbs_ui}; impl PhotocraftApp { pub(super) fn prune_thumbs(&mut self) { diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1505677b94..4fb44c26c8 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -1,4 +1,4 @@ -use super::*; +use super::PhotocraftApp; impl PhotocraftApp { /// Zoom of the active document's main view: screen (device) pixels per document pixel, the diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs index 0379f77d20..49ecfc6b36 100644 --- a/crates/ui-egui/src/app/window.rs +++ b/crates/ui-egui/src/app/window.rs @@ -1,4 +1,4 @@ -use super::*; +use super::PhotocraftApp; impl PhotocraftApp { /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 6912a149e6..c715ac4d46 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -201,6 +201,558 @@ pub fn mode_label(doc: &Document) -> &'static str { } /// Draw one canvas view and handle its input. `primary` = main window (tools active). +struct CanvasPaintInput<'a> { + ctx: &'a egui::Context, + rect: Rect, + painter: &'a egui::Painter, + ppp: f32, + border: photocraft_engine::prefs::CanvasBorder, + doc: &'a std::sync::Arc, + idx: usize, + output: Option, + size: [u32; 2], + primary: bool, + flip: bool, + aspect: f32, + render_zoom: f32, + target_xf: ViewXform, + pixel_grid: bool, +} + +struct SelectionPaintInput<'a> { + ctx: &'a egui::Context, + painter: &'a egui::Painter, + ui: &'a egui::Ui, + view: &'a View, + xf: ViewXform, + rect: Rect, + doc: &'a Document, + idx: usize, +} + +fn paint_selection_outline(app: &mut PhotocraftApp, input: SelectionPaintInput<'_>) { + // Select and Mask outlines its refined selection (on its preview proxy, reduced by `k`) in + // the Marching Ants view and hides the ants in the others. + let refined = crate::select_mask_view::ants(app, input.idx); + // A floating piece's ants hug the pixels being moved. + let floated = floating_outline(app, input.idx); + let (outlined, k) = match &refined { + None => (floated.as_ref().or(input.doc.selection.as_ref()), 1), + Some(None) => (None, 1), + Some(Some((proxy, k))) => (proxy.selection.as_ref(), (*k).max(1)), + }; + // Selection outline: true boundary, animated marching ants (cached per revision). + if let Some(sel) = outlined.filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) { + // Trace at display resolution over the visible part only; key by the mask's tile identity + // (not the document revision) so unrelated edits don't re-trace it. The step is in + // device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px + // selection still traces at 100% on a scaled display. + let step = (1.0 / (input.view.zoom * k as f32).max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32; + let corners = [input.rect.min, pos2(input.rect.max.x, input.rect.min.y), input.rect.max, pos2(input.rect.min.x, input.rect.max.y)]; + let docs = [input.xf.to_doc(corners[0]), input.xf.to_doc(corners[1]), input.xf.to_doc(corners[2]), input.xf.to_doc(corners[3])]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } + let (x0, y0, x1, y1) = (x0 / f64::from(k), y0 / f64::from(k), x1 / f64::from(k), y1 / f64::from(k)); + let q = 256 * step as i32; // quantise the region so small pans reuse the cache + // The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document + // to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there. + let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; + // A Free Transform carries the selection to wherever its box goes (#5297), so all of + // it is outlined: the part now in view may have started out of it. + let carried = app.session.active_index() == Some(input.idx) && crate::transform_tool::carries_selection_of(app, input.doc.id); + let vis = if carried { + photocraft_geom::Rect::new(-(1 << 30), -(1 << 30), 1 << 30, 1 << 30) + } else { + photocraft_geom::Rect::new( + px(x0.floor()).div_euclid(q) * q - q, + px(y0.floor()).div_euclid(q) * q - q, + (px(x1.ceil()).div_euclid(q) + 2) * q, + (px(y1.ceil()).div_euclid(q) + 2) * q, + ) + }; + let bounds_key = if k > 1 { u64::MAX / 2 - input.doc.id.0 } else { u64::MAX - input.doc.id.0 }; + let carried_bounds = carried.then(|| app.cached_bounds(bounds_key, sel).intersect(&vis)); + let step = carried_bounds.map_or(step, |b| crate::outline::bounded_step(b, step)); + let key = crate::surface_fingerprint(sel) + ^ u64::from(step).rotate_left(56) + ^ input.doc.id.0.rotate_left(17) + ^ (vis.x0 as u64) << 8 + ^ (vis.y0 as u64) << 24 + ^ (vis.x1 as u64) << 36 + ^ (vis.y1 as u64) << 48 + ^ u64::from(k).rotate_left(5); + let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == input.doc.id && *k == key); + if !fresh { + let t0 = crate::gpu_canvas::now_ms(); + let b = carried_bounds.unwrap_or_else(|| app.cached_bounds(bounds_key, sel).intersect(&vis)); + // Filters can occupy every worker in Rayon's global pool. A parallel scan here would + // block the UI thread waiting for those workers, preventing job cancellation (#1554). + let mut segs = + if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) }; + if k > 1 { + let s = i32::try_from(k).unwrap_or(1); + let up = |p: [i32; 2]| [p[0].saturating_mul(s), p[1].saturating_mul(s)]; + segs.iter_mut().for_each(|(a, b)| (*a, *b) = (up(*a), up(*b))); + } + app.perf.span("outline", crate::gpu_canvas::now_ms() - t0); + app.outline_cache = Some((input.doc.id, key, std::sync::Arc::new(segs))); + } + // Under Content-Aware Move's Transform On Drop box the ants are drawn where it puts them. + if let Some((_, _, segs)) = app.outline_cache.as_ref().filter(|_| !crate::cam_transform::active(app)) { + let time = input.ui.input(|i| i.time); + // A floating piece (and a selection being dragged) draws its ants where it is shown. + let mut shown = input.xf; + if let Some((dx, dy)) = selection_shown_offset(app) { + shown.center = [input.xf.center[0] - dx as f32, input.xf.center[1] - dy as f32]; + } + // Under a Free Transform box they are where the box puts them (#5297). + if !(carried && crate::transform_tool::draw_selection(app, input.painter, &input.xf, input.doc.id, segs, time)) { + marching_ants_segments(input.painter, &shown, segs, time); + } + input.ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } +} + +fn paint_canvas(app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXform, input: &CanvasPaintInput<'_>) -> (bool, egui::layers::ShapeIdx, Rect) { + let ctx = input.ctx; + let rect = input.rect; + let painter = input.painter; + let ppp = input.ppp; + let border = input.border; + let doc = input.doc; + let idx = input.idx; + let output = input.output; + let size = input.size; + let primary = input.primary; + let flip = input.flip; + let aspect = input.aspect; + let render_zoom = input.render_zoom; + let target_xf = input.target_xf; + let pixel_grid = input.pixel_grid; + + let point_zoom = view.zoom / ppp; + let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow; + // Drop shadow, checkerboard, document image. + let img_rect = xf.doc_rect(doc.bounds()); + // The canvas edge the Line border outlines: a size-changing preview's own (CPU canvas). + let mut edge_rect = img_rect; + // The document area the image is drawn over: a size-changing preview's own on the CPU + // canvas (Image › Rotation). Overlays drawn from the same preview follow it. + let mut shown_area = doc.bounds(); + // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas + // (whose edge blends into them) and without its shadow. + let beyond = draw_beyond_canvas(app, painter, &xf, idx, output); + // View › Pattern Preview (#1067): copies of the document around it, from the same texture. + let pattern = if app.ui.view.pattern_preview { + let v = visible_doc_rect(&xf); + crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), size) + } else { + Vec::new() + }; + let drop_shadow = drop_shadow && !beyond && !app.ui.view.pattern_preview; + // Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless + // Preferences › Performance › Low Resolution Previews is off. + let mut on_gpu = false; + // A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader + // has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform. + let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect); + if app.gpu.is_some() + && gpu_ok + && let Some((k, key, preview_size)) = + ensure_adjust_proxy(app, idx, render_zoom).or_else(|| ensure_filter_preview(app, idx, ctx)).or_else(|| ensure_proxy_preview(app, idx, render_zoom)) + { + on_gpu = true; + app.navigator_gpu.remove(&doc.id); + let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)]; + let shown = filter_preview_display_doc(app, doc, key); + let params = crate::gpu_canvas::ViewParams { + doc: key, + doc_size: preview_size, + zoom: view.zoom * k as f32 / ppp, + // A size-changing preview grows around the old image center; keep the view's pan. + center: [ + xf.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0, + xf.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0, + ], + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, + shadow: { + let t = crate::theme::Tokens::get(ctx); + !t.bevel && !t.pro && drop_shadow + }, + pixel_grid: false, + view_key: egui::Id::unique(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(), + display: sync_display_lut(app, &shown, key, output), + output: output.unwrap_or(0), + hdr: hdr_preview(app, doc), + offset: [0.0, 0.0], + }; + paint_gpu_view(painter, rect, params, &pattern); + } else if gpu_ok && ensure_gpu(app, ctx, idx, redraw_focus(&target_xf, &xf)) { + on_gpu = true; + app.perf.gpu = true; + // Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs). + let params = crate::gpu_canvas::ViewParams { + doc: doc.id.0, + doc_size: [doc.size.width, doc.size.height], + zoom: point_zoom, + center: xf.center, + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, + shadow: { + let t = crate::theme::Tokens::get(ctx); + !t.bevel && !t.pro && drop_shadow + }, + pixel_grid, + view_key: egui::Id::unique(("pc-canvas", ctx.viewport_id(), idx)).value(), + display: sync_display_lut(app, doc, doc.id.0, output), + output: output.unwrap_or(0), + hdr: hdr_preview(app, doc), + offset: [0.0, 0.0], + }; + if app.navigator_plain.contains(&doc.id) { + app.navigator_gpu.insert(doc.id, params); + } else { + app.navigator_gpu.remove(&doc.id); + } + paint_gpu_view(painter, rect, params, &pattern); + } else { + app.navigator_gpu.remove(&doc.id); + // A document too large for one full-resolution texture also gets the part in view at + // the screen's resolution, drawn over the reduced whole (#7568). + let in_view = + InView { visible: visible_doc_rect(&xf), zoom: view.zoom, key: egui::Id::unique(("pc-canvas-detail", ctx.viewport_id(), idx, primary)).value() }; + let textures = ensure_texture_in_view(app, ctx, idx, output, Some(in_view)); + let tex = textures.as_ref().map(|t| t.texture); + // The area the image covers: a size-changing preview's own (Image › Rotation). + let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds); + shown_area = area; + if area != doc.bounds() { + edge_rect = xf.doc_rect(area); + } + if !crate::theme::Tokens::get(ctx).bevel && drop_shadow { + let shadow_rect = edge_rect; + painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(shadow_rect, 0)); + } + let rotated = view.rotation.abs() > 0.05; + let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, ctx), square)); + // Repeated-quad coverage is not proven identical on all Pattern Preview adapters. + // Retain its legacy checker submissions, including the central document's. + let opaque = !app.ui.view.pattern_preview && app.canvases.get(&cache_key(doc.id, output)).is_some_and(|c| c.texture_opaque) && tex.is_some(); + paint_cpu_document(painter, &xf, area, rotated, checkerboard, tex, opaque); + if let Some((detail, area)) = textures.and_then(|t| t.detail) { + paint_cpu_detail(painter, &xf, doc.bounds(), rotated, checkerboard, detail, area); + } + // Pattern Preview tiles what is shown: a size-changing preview's area, from its origin. + let (tile, copies) = if area == doc.bounds() || !app.ui.view.pattern_preview { + (size, pattern.clone()) + } else { + let tile = [area.width(), area.height()]; + let v = visible_doc_rect(&xf).translate(-area.x0, -area.y0); + (tile, crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), tile)) + }; + for &c in &copies { + paint_cpu_document(painter, &pattern_xf(&xf, c, tile), area, rotated, checkerboard, tex, opaque); + } + } + // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). + if let Some(tex) = crate::channel_view::ensure(app, ctx, idx) { + // Rendered from the live preview, so over the area the preview is shown in. + let a = shown_area; + if view.rotation.abs() > 0.05 { + paint_mapped_image_at( + painter, + &xf, + tex, + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + [a.x0 as f32, a.y0 as f32], + [a.width() as f32, a.height() as f32], + Color32::WHITE, + ); + } else { + let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE); + } + } + crate::color_range_ui::paint_selection_preview(app, ctx, painter, doc.id, img_rect, flip); + // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). + if doc.has_artboards() { + let t = crate::theme::Tokens::get(ctx); + let pasteboard = crate::prefs_ui::pasteboard_color(app); + let dot_tex = dots(ctx, &t); + // Cut around the layers as they are shown, so a loose layer dragged with the Move tool + // (or otherwise previewed) is not covered where it now draws. + let shown = display_doc(app, idx).0; + // Each piece is painted as its own quad (the painter clips to the canvas), so a + // rotated view does not paint a piece's bounding box over the boards or loose work. + let fill = |q: &[Pos2; 4], tex: Option, color: Color32| { + let mut mesh = tex.map_or_else(egui::Mesh::default, egui::Mesh::with_texture); + for &p in q { + // Same phase as the dots around the document. + let uv = if tex.is_some() { ((p - rect.min) / 22.0).to_pos2() } else { egui::epaint::WHITE_UV }; + mesh.vertices.push(egui::epaint::Vertex { pos: p, uv, color }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(mesh); + }; + for q in crate::artboard_ui::pasteboard_quads(&xf, &shown) { + if !Rect::from_points(&q).intersects(rect) { + continue; + } + match pasteboard { + Some(c) => fill(&q, None, c), + None => { + fill(&q, None, t.canvas); + if let Some(id) = dot_tex { + fill(&q, Some(id), Color32::WHITE); + } + } + } + } + if primary { + crate::artboard_ui::draw_frames(app, painter, &xf); + } + } + + // Pixel grid at high zoom, over pixels with content only (the GPU path draws its own). + if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) { + crate::pixel_grid::paint(app, painter, &xf, idx, output, visible_doc_rect(&xf)); + } + + // Developer tile grid (`ui.set {"tileGrid": true}`): the active layer's storage tiles. + // Not tied to View › Extras (⌘H), which hides only the View › Show overlays. + if app.ui.view.tile_grid { + crate::tile_overlay::paint(app, ctx, painter, &xf, idx, visible_doc_rect(&xf)); + } + + // View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are + // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer. + let layer_edges = painter.add(egui::Shape::Noop); + + paint_selection_outline(app, SelectionPaintInput { ctx, painter, ui, view, xf, rect, doc, idx }); + + (beyond, layer_edges, edge_rect) +} + +struct CanvasNavigationInput<'a> { + ctx: &'a egui::Context, + response: &'a egui::Response, + free_hover: bool, + wheel_owner: egui::Id, + xf: ViewXform, + ppp: f32, + idx: usize, +} + +fn update_canvas_navigation(app: &mut PhotocraftApp, view: &mut View, input: CanvasNavigationInput<'_>) { + // Navigation (wheel_nav.rs): scroll pans (⇧ or ⌘/Ctrl sideways); pinch and ⌥-scroll zoom around the pointer. + // The wheel also scrolls over the scrollbars drawn on top of the canvas (last frame's hover). + let bars_id = egui::Id::unique(("pc-canvas-bars-hover", input.idx)); + let over_bars = input.ctx.data(|d| d.get_temp::(bars_id)).unwrap_or(false); + let nav_hovered = input.response.hovered() || input.free_hover || over_bars; + // Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721). + // General › Animated Zoom: the wheel zoom eases over the frames of a notch, or is one instant step. + // Enhanced Controls › Enable Gestures off: two fingers on a touch screen neither zoom nor + // turn the view (#204); the mouse and trackpad are unaffected. + let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; + let wheel = crate::wheel_nav::read_with( + input.ctx, + app.session.prefs().general.zoom_with_scroll_wheel, + app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch, + app.session.prefs().general.animated_zoom, + input.wheel_owner, + nav_hovered, + app.session.prefs().interface.enable_animations, + touch_gestures, + ); + if nav_hovered { + let pointer = input.ctx.input(|i| i.pointer.hover_pos()); + match (wheel, pointer) { + (Some(crate::wheel_nav::Wheel::Zoom(f)), Some(p)) => { + // At a limit the view stays put, as in Photoshop: a notch past 12800 % neither + // zooms nor slides the image towards the pointer. + let nz = crate::zoom_levels::clamp(view.zoom * f, view.doc_size); + if nz != view.zoom * f { + crate::wheel_nav::settle(input.ctx, input.wheel_owner); + } + if nz != view.zoom { + // Over the pasteboard the anchor is the image's nearest point (#3720). + let at = wheel_anchor(&input.xf, p, view.doc_size); + zoom_about(view, &input.xf, at, nz, false, input.ppp); + } + } + (Some(crate::wheel_nav::Wheel::SnapZoom(n)), Some(p)) => { + let dir = if n > 0 { 1 } else { -1 }; + let mut nz = view.zoom; + for _ in 0..n.unsigned_abs() { + nz = crate::zoom_levels::step(nz, dir, view.doc_size); + } + if nz != view.zoom { + zoom_about(view, &input.xf, p, nz, false, input.ppp); + } + } + (Some(crate::wheel_nav::Wheel::Pan(scroll)), _) => { + let d = input.xf.unmap_vec(scroll) / (view.zoom / input.ppp); + view.center[0] -= d.x; + view.center[1] -= d.y; + } + _ => {} + } + let rotate_trackpad = app.session.prefs().enhanced_controls.rotate_view_with_trackpad; + if let Some(delta) = crate::rotate_view::trackpad_delta(input.ctx, rotate_trackpad, touch_gestures) { + view.zoom_animating = false; + view.zoom_anchor = None; + let next = view.rotation + crate::rotate_view::screen_delta(delta, input.xf.flip); + if next.is_finite() { + view.rotation = crate::rotate_view::wrap_deg(next); + } + } + } +} + +struct DialogCanvasInput<'a> { + ctx: &'a egui::Context, + view: &'a mut View, + xf: &'a ViewXform, + rect: Rect, + painter: &'a egui::Painter, + ppp: f32, + primary: bool, + middle: bool, + space_pan: bool, + temporary: Option, + free_hover: bool, + img_rect: Rect, +} + +fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput<'_>) { + let sticky_alt = app.ui.shell.sticky_alt; + let zoom_out = |alt: bool| match input.temporary { + Some(crate::hold_keys::Temporary::ZoomOut) => true, + Some(crate::hold_keys::Temporary::ZoomIn) => false, + _ => alt || sticky_alt, + }; + + // With a colour dialog picker armed the image is its eyedropper, whatever the tool; Space + // and the middle button still pan. Curves and Replace Color use the same merged-composite + // sampler as the Color Picker, never the reduced adjustment preview. + let curves_picking = crate::adjust_dialog::picker_armed(app); + let replace_picking = crate::filter_dialog::color_eyedropper_armed(app); + let picking = input.primary && (crate::color_picker_ui::top(app).is_some() || curves_picking || replace_picking); + let range_picking = + input.primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling); + // Select and Mask's Refine Edge Brush paints on the image. + let refine_brushing = + input.primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields)); + // Field Blur's pins are placed and dragged on the image (`blur_pins`). + let pinning = input.primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields)); + // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). + let shadow_drag = + !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); + // ⌘/Ctrl-click with Curves open: a point at the pixel's tone (#7325), whatever the tool. The + // press's own modifiers decide, and only the press adds: a drag would add one per frame. + let curve_point_press = (input.primary && !input.middle && crate::adjust_dialog::curves_on_top(app)) + .then(|| { + input.ctx.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { button: PointerButton::Primary, pressed: true, modifiers, .. } => Some(*modifiers), + _ => None, + }) + }) + }) + .flatten() + .map(|m| crate::workspace_ui::sticky_mods(app, m)) + .filter(|m| m.command); + let dialog_hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag && curve_point_press.is_none(); + // ⌘Space / ⌥Space zoom under the dialog as they do without one, before Space pans (#6460). + // With the Hand tool, ⌘ alone is Zoom In (#6434); under Curves that press is the dialog's + // point (#7325), not a zoom. + let curve_point_with_hand = curve_point_press.is_some() && app.ui.tool == Tool::Hand; + let held_zoom = + !input.middle && !curve_point_with_hand && matches!(input.temporary, Some(crate::hold_keys::Temporary::ZoomIn | crate::hold_keys::Temporary::ZoomOut)); + if held_zoom { + let alt = input.ctx.input(|i| i.modifiers.alt); + if input.free_hover { + input.ctx.set_cursor_icon(crate::tool_cursor::zoom(input.ctx, zoom_out(alt))); + } + let b = crate::dialogs::free_buttons(input.ctx, input.rect); + let pointer = input.ctx.input(|i| i.pointer.latest_pos()); + crate::zoom_tool::drag(app, input.ctx, input.view, input.xf, &b, pointer); + if b.clicked + && let Some(p) = pointer + { + let nz = crate::zoom_levels::step(input.view.zoom, if zoom_out(alt) { -1 } else { 1 }, input.view.doc_size); + zoom_about(input.view, input.xf, p, nz, app.session.prefs().tools.zoom_clicked_point_to_center, input.ppp); + } + } else if let Some(d) = crate::dialogs::pan_delta(input.ctx, input.rect, dialog_hand) { + let d = input.xf.unmap_vec(d) / (input.view.zoom / input.ppp); + input.view.center[0] -= d.x; + input.view.center[1] -= d.y; + input.ctx.set_cursor_icon(crate::tool_cursor::hand(input.ctx, true)); + } else if input.free_hover && (input.space_pan || dialog_hand) { + input.ctx.set_cursor_icon(crate::tool_cursor::hand(input.ctx, false)); + } else if shadow_drag && !input.middle && crate::dialogs::free_pointer_over(input.ctx, input.rect).is_some() { + input.ctx.set_cursor_icon(egui::CursorIcon::Move); + if let Some(p) = crate::dialogs::free_press(input.ctx, input.rect) { + let (start, origin) = input.ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.press_origin().unwrap_or(p))); + let total = input.xf.unmap_vec(p - origin) / (input.view.zoom / input.ppp); + if let Some(d) = app.ui.dialogs.last_mut() { + crate::layer_style::drag_shadow(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)]); + } + } + } else if picking && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) { + if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { + input.ctx.set_cursor_icon(egui::CursorIcon::Crosshair); + } else { + input.ctx.set_cursor_icon(pipette_cursor(input.ctx, p)); + } + if let Some(p) = crate::dialogs::free_press(input.ctx, input.rect) { + let d = input.xf.to_doc(p); + if curves_picking { + crate::adjust_dialog::sample_at(app, d[0], d[1]); + } else if replace_picking { + crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]); + } else { + crate::color_picker_ui::sample_at(app, d[0], d[1]); + } + } + } else if pinning + && !input.middle + && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) + { + let press = crate::dialogs::free_press(input.ctx, input.rect); + crate::blur_pins::canvas(app, input.ctx, input.xf, p, press); + } else if refine_brushing + && !input.middle + && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) + { + let press = crate::dialogs::free_press(input.ctx, input.rect).map(|q| input.xf.to_doc(q)); + crate::select_mask_view::canvas_brush(app, input.painter, p, press, input.xf.zoom_x()); + } else if let Some(mods) = curve_point_press + && let Some(p) = crate::dialogs::free_press(input.ctx, input.rect) + { + let d = input.xf.to_doc(p); + crate::adjust_dialog::add_point_at(app, input.ctx, d[0], d[1], mods.shift); + } else if input.primary + && !input.middle + && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect).filter(|p| input.img_rect.contains(*p)) + { + // Color Range samples colours with its eyedropper on the image itself. + let press = crate::dialogs::free_press(input.ctx, input.rect) + .filter(|p| input.img_rect.contains(*p) && input.ctx.input(|i| i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO)) + .map(|q| input.xf.to_doc(q)); + crate::color_range_ui::canvas_eyedropper(app, input.ctx, p, press); + } +} + pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { let ctx = ui.ctx().clone(); // The camera as the app holds it before this frame's input. The canvas works on its own copy @@ -305,302 +857,24 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Default-mode Crop changes its camera during input. Defer its image until the new camera // is known; other tools keep their existing paint order and texture/outline snapshots. let crop_camera = primary && crate::crop_mode::moves_image(app); - let paint_canvas = |app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXform| { - let point_zoom = view.zoom / ppp; - let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow; - // Drop shadow, checkerboard, document image. - let img_rect = xf.doc_rect(doc.bounds()); - // The canvas edge the Line border outlines: a size-changing preview's own (CPU canvas). - let mut edge_rect = img_rect; - // The document area the image is drawn over: a size-changing preview's own on the CPU - // canvas (Image › Rotation). Overlays drawn from the same preview follow it. - let mut shown_area = doc.bounds(); - // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas - // (whose edge blends into them) and without its shadow. - let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output); - // View › Pattern Preview (#1067): copies of the document around it, from the same texture. - let pattern = if app.ui.view.pattern_preview { - let v = visible_doc_rect(&xf); - crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), size) - } else { - Vec::new() - }; - let drop_shadow = drop_shadow && !beyond && !app.ui.view.pattern_preview; - // Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless - // Preferences › Performance › Low Resolution Previews is off. - let mut on_gpu = false; - // A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader - // has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform. - let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect); - if app.gpu.is_some() - && gpu_ok - && let Some((k, key, preview_size)) = ensure_adjust_proxy(app, idx, render_zoom) - .or_else(|| ensure_filter_preview(app, idx, &ctx)) - .or_else(|| ensure_proxy_preview(app, idx, render_zoom)) - { - on_gpu = true; - app.navigator_gpu.remove(&doc.id); - let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)]; - let shown = filter_preview_display_doc(app, &doc, key); - let params = crate::gpu_canvas::ViewParams { - doc: key, - doc_size: preview_size, - zoom: view.zoom * k as f32 / ppp, - // A size-changing preview grows around the old image center; keep the view's pan. - center: [ - xf.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0, - xf.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0, - ], - rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, - shadow: { - let t = crate::theme::Tokens::get(&ctx); - !t.bevel && !t.pro && drop_shadow - }, - pixel_grid: false, - view_key: egui::Id::unique(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(), - display: sync_display_lut(app, &shown, key, output), - output: output.unwrap_or(0), - hdr: hdr_preview(app, &doc), - offset: [0.0, 0.0], - }; - paint_gpu_view(&painter, rect, params, &pattern); - } else if gpu_ok && ensure_gpu(app, &ctx, idx, redraw_focus(&target_xf, &xf)) { - on_gpu = true; - app.perf.gpu = true; - // Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs). - let params = crate::gpu_canvas::ViewParams { - doc: doc.id.0, - doc_size: [doc.size.width, doc.size.height], - zoom: point_zoom, - center: xf.center, - rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, - shadow: { - let t = crate::theme::Tokens::get(&ctx); - !t.bevel && !t.pro && drop_shadow - }, - pixel_grid, - view_key: egui::Id::unique(("pc-canvas", ctx.viewport_id(), idx)).value(), - display: sync_display_lut(app, &doc, doc.id.0, output), - output: output.unwrap_or(0), - hdr: hdr_preview(app, &doc), - offset: [0.0, 0.0], - }; - if app.navigator_plain.contains(&doc.id) { - app.navigator_gpu.insert(doc.id, params); - } else { - app.navigator_gpu.remove(&doc.id); - } - paint_gpu_view(&painter, rect, params, &pattern); - } else { - app.navigator_gpu.remove(&doc.id); - // A document too large for one full-resolution texture also gets the part in view at - // the screen's resolution, drawn over the reduced whole (#7568). - let in_view = InView { - visible: visible_doc_rect(&xf), - zoom: view.zoom, - key: egui::Id::unique(("pc-canvas-detail", ctx.viewport_id(), idx, primary)).value(), - }; - let textures = ensure_texture_in_view(app, &ctx, idx, output, Some(in_view)); - let tex = textures.as_ref().map(|t| t.texture); - // The area the image covers: a size-changing preview's own (Image › Rotation). - let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds); - shown_area = area; - if area != doc.bounds() { - edge_rect = xf.doc_rect(area); - } - if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { - let shadow_rect = edge_rect; - painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(shadow_rect, 0)); - } - let rotated = view.rotation.abs() > 0.05; - let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, &ctx), square)); - // Repeated-quad coverage is not proven identical on all Pattern Preview adapters. - // Retain its legacy checker submissions, including the central document's. - let opaque = !app.ui.view.pattern_preview && app.canvases.get(&cache_key(doc.id, output)).is_some_and(|c| c.texture_opaque) && tex.is_some(); - paint_cpu_document(&painter, &xf, area, rotated, checkerboard, tex, opaque); - if let Some((detail, area)) = textures.and_then(|t| t.detail) { - paint_cpu_detail(&painter, &xf, doc.bounds(), rotated, checkerboard, detail, area); - } - // Pattern Preview tiles what is shown: a size-changing preview's area, from its origin. - let (tile, copies) = if area == doc.bounds() || !app.ui.view.pattern_preview { - (size, pattern.clone()) - } else { - let tile = [area.width(), area.height()]; - let v = visible_doc_rect(&xf).translate(-area.x0, -area.y0); - (tile, crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), tile)) - }; - for &c in &copies { - paint_cpu_document(&painter, &pattern_xf(&xf, c, tile), area, rotated, checkerboard, tex, opaque); - } - } - // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). - if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) { - // Rendered from the live preview, so over the area the preview is shown in. - let a = shown_area; - if view.rotation.abs() > 0.05 { - paint_mapped_image_at( - &painter, - &xf, - tex, - Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), - [a.x0 as f32, a.y0 as f32], - [a.width() as f32, a.height() as f32], - Color32::WHITE, - ); - } else { - let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE); - } - } - crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); - // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). - if doc.has_artboards() { - let t = crate::theme::Tokens::get(&ctx); - let pasteboard = crate::prefs_ui::pasteboard_color(app); - let dot_tex = dots(&ctx, &t); - // Cut around the layers as they are shown, so a loose layer dragged with the Move tool - // (or otherwise previewed) is not covered where it now draws. - let shown = display_doc(app, idx).0; - // Each piece is painted as its own quad (the painter clips to the canvas), so a - // rotated view does not paint a piece's bounding box over the boards or loose work. - let fill = |q: &[Pos2; 4], tex: Option, color: Color32| { - let mut mesh = tex.map_or_else(egui::Mesh::default, egui::Mesh::with_texture); - for &p in q { - // Same phase as the dots around the document. - let uv = if tex.is_some() { ((p - rect.min) / 22.0).to_pos2() } else { egui::epaint::WHITE_UV }; - mesh.vertices.push(egui::epaint::Vertex { pos: p, uv, color }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(mesh); - }; - for q in crate::artboard_ui::pasteboard_quads(&xf, &shown) { - if !Rect::from_points(&q).intersects(rect) { - continue; - } - match pasteboard { - Some(c) => fill(&q, None, c), - None => { - fill(&q, None, t.canvas); - if let Some(id) = dot_tex { - fill(&q, Some(id), Color32::WHITE); - } - } - } - } - if primary { - crate::artboard_ui::draw_frames(app, &painter, &xf); - } - } - - // Pixel grid at high zoom, over pixels with content only (the GPU path draws its own). - if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) { - crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf)); - } - - // Developer tile grid (`ui.set {"tileGrid": true}`): the active layer's storage tiles. - // Not tied to View › Extras (⌘H), which hides only the View › Show overlays. - if app.ui.view.tile_grid { - crate::tile_overlay::paint(app, &ctx, &painter, &xf, idx, visible_doc_rect(&xf)); - } - - // View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are - // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer. - let layer_edges = painter.add(egui::Shape::Noop); - - // Select and Mask outlines its refined selection (on its preview proxy, reduced by `k`) in - // the Marching Ants view and hides the ants in the others. - let refined = crate::select_mask_view::ants(app, idx); - // A floating piece's ants hug the pixels being moved. - let floated = floating_outline(app, idx); - let (outlined, k) = match &refined { - None => (floated.as_ref().or(doc.selection.as_ref()), 1), - Some(None) => (None, 1), - Some(Some((proxy, k))) => (proxy.selection.as_ref(), (*k).max(1)), - }; - // Selection outline: true boundary, animated marching ants (cached per revision). - if let Some(sel) = outlined.filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) { - // Trace at display resolution over the visible part only; key by the mask's tile identity - // (not the document revision) so unrelated edits don't re-trace it. The step is in - // device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px - // selection still traces at 100% on a scaled display. - let step = (1.0 / (view.zoom * k as f32).max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32; - let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)]; - let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])]; - let mut x0 = docs[0][0]; - let mut y0 = docs[0][1]; - let mut x1 = x0; - let mut y1 = y0; - for d in docs { - x0 = x0.min(d[0]); - y0 = y0.min(d[1]); - x1 = x1.max(d[0]); - y1 = y1.max(d[1]); - } - let (x0, y0, x1, y1) = (x0 / f64::from(k), y0 / f64::from(k), x1 / f64::from(k), y1 / f64::from(k)); - let q = 256 * step as i32; // quantise the region so small pans reuse the cache - // The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document - // to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there. - let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; - // A Free Transform carries the selection to wherever its box goes (#5297), so all of - // it is outlined: the part now in view may have started out of it. - let carried = app.session.active_index() == Some(idx) && crate::transform_tool::carries_selection_of(app, doc.id); - let vis = if carried { - photocraft_geom::Rect::new(-(1 << 30), -(1 << 30), 1 << 30, 1 << 30) - } else { - photocraft_geom::Rect::new( - px(x0.floor()).div_euclid(q) * q - q, - px(y0.floor()).div_euclid(q) * q - q, - (px(x1.ceil()).div_euclid(q) + 2) * q, - (px(y1.ceil()).div_euclid(q) + 2) * q, - ) - }; - let bounds_key = if k > 1 { u64::MAX / 2 - doc.id.0 } else { u64::MAX - doc.id.0 }; - let carried_bounds = carried.then(|| app.cached_bounds(bounds_key, sel).intersect(&vis)); - let step = carried_bounds.map_or(step, |b| crate::outline::bounded_step(b, step)); - let key = crate::surface_fingerprint(sel) - ^ u64::from(step).rotate_left(56) - ^ doc.id.0.rotate_left(17) - ^ (vis.x0 as u64) << 8 - ^ (vis.y0 as u64) << 24 - ^ (vis.x1 as u64) << 36 - ^ (vis.y1 as u64) << 48 - ^ u64::from(k).rotate_left(5); - let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key); - if !fresh { - let t0 = crate::gpu_canvas::now_ms(); - let b = carried_bounds.unwrap_or_else(|| app.cached_bounds(bounds_key, sel).intersect(&vis)); - // Filters can occupy every worker in Rayon's global pool. A parallel scan here would - // block the UI thread waiting for those workers, preventing job cancellation (#1554). - let mut segs = - if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) }; - if k > 1 { - let s = i32::try_from(k).unwrap_or(1); - let up = |p: [i32; 2]| [p[0].saturating_mul(s), p[1].saturating_mul(s)]; - segs.iter_mut().for_each(|(a, b)| (*a, *b) = (up(*a), up(*b))); - } - app.perf.span("outline", crate::gpu_canvas::now_ms() - t0); - app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs))); - } - // Under Content-Aware Move's Transform On Drop box the ants are drawn where it puts them. - if let Some((_, _, segs)) = app.outline_cache.as_ref().filter(|_| !crate::cam_transform::active(app)) { - let time = ui.input(|i| i.time); - // A floating piece (and a selection being dragged) draws its ants where it is shown. - let mut shown = xf; - if let Some((dx, dy)) = selection_shown_offset(app) { - shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32]; - } - // Under a Free Transform box they are where the box puts them (#5297). - if !(carried && crate::transform_tool::draw_selection(app, &painter, &xf, doc.id, segs, time)) { - marching_ants_segments(&painter, &shown, segs, time); - } - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } - } - - (beyond, layer_edges, edge_rect) + let paint_input = CanvasPaintInput { + ctx: &ctx, + rect, + painter: &painter, + ppp, + border, + doc: &doc, + idx, + output, + size, + primary, + flip, + aspect, + render_zoom, + target_xf, + pixel_grid, }; - let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &display_view, xf)) }; + let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &display_view, xf, &paint_input)) }; let img_rect = xf.doc_rect(doc.bounds()); // Under an open dialog the canvas widget is inert, but the image still pans and zooms. @@ -610,69 +884,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if !under_dialog && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| rect.contains(p))) { crate::spring_tools::note_canvas_press(app); } - // Navigation (wheel_nav.rs): scroll pans (⇧ or ⌘/Ctrl sideways); pinch and ⌥-scroll zoom around the pointer. - // The wheel also scrolls over the scrollbars drawn on top of the canvas (last frame's hover). let bars_id = egui::Id::unique(("pc-canvas-bars-hover", idx)); - let over_bars = ctx.data(|d| d.get_temp::(bars_id)).unwrap_or(false); - let nav_hovered = response.hovered() || free_hover || over_bars; - // Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721). - // General › Animated Zoom: the wheel zoom eases over the frames of a notch, or is one instant step. - // Enhanced Controls › Enable Gestures off: two fingers on a touch screen neither zoom nor - // turn the view (#204); the mouse and trackpad are unaffected. - let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; - let wheel = crate::wheel_nav::read_with( - &ctx, - app.session.prefs().general.zoom_with_scroll_wheel, - app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch, - app.session.prefs().general.animated_zoom, - wheel_owner, - nav_hovered, - app.session.prefs().interface.enable_animations, - touch_gestures, - ); - if nav_hovered { - let pointer = ui.input(|i| i.pointer.hover_pos()); - match (wheel, pointer) { - (Some(crate::wheel_nav::Wheel::Zoom(f)), Some(p)) => { - // At a limit the view stays put, as in Photoshop: a notch past 12800 % neither - // zooms nor slides the image towards the pointer. - let nz = crate::zoom_levels::clamp(view.zoom * f, view.doc_size); - if nz != view.zoom * f { - crate::wheel_nav::settle(&ctx, wheel_owner); - } - if nz != view.zoom { - // Over the pasteboard the anchor is the image's nearest point (#3720). - let at = wheel_anchor(&xf, p, view.doc_size); - zoom_about(&mut view, &xf, at, nz, false, ppp); - } - } - (Some(crate::wheel_nav::Wheel::SnapZoom(n)), Some(p)) => { - let dir = if n > 0 { 1 } else { -1 }; - let mut nz = view.zoom; - for _ in 0..n.unsigned_abs() { - nz = crate::zoom_levels::step(nz, dir, view.doc_size); - } - if nz != view.zoom { - zoom_about(&mut view, &xf, p, nz, false, ppp); - } - } - (Some(crate::wheel_nav::Wheel::Pan(scroll)), _) => { - let d = xf.unmap_vec(scroll) / (view.zoom / ppp); - view.center[0] -= d.x; - view.center[1] -= d.y; - } - _ => {} - } - let rotate_trackpad = app.session.prefs().enhanced_controls.rotate_view_with_trackpad; - if let Some(delta) = crate::rotate_view::trackpad_delta(&ctx, rotate_trackpad, touch_gestures) { - view.zoom_animating = false; - view.zoom_anchor = None; - let next = view.rotation + crate::rotate_view::screen_delta(delta, xf.flip); - if next.is_finite() { - view.rotation = crate::rotate_view::wrap_deg(next); - } - } - } + update_canvas_navigation(app, &mut view, CanvasNavigationInput { ctx: &ctx, response: &response, free_hover, wheel_owner, xf, ppp, idx }); // Pen pressure/tilt for this frame's tool events (mouse = 1.0), unless Preferences › Tools › // Use Tablet Pressure is off; the pen's eraser end selects the Eraser. @@ -722,117 +935,25 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: }; if under_dialog { - // With a colour dialog picker armed the image is its eyedropper, whatever the tool; Space - // and the middle button still pan. Curves and Replace Color use the same merged-composite - // sampler as the Color Picker, never the reduced adjustment preview. - let curves_picking = crate::adjust_dialog::picker_armed(app); - let replace_picking = crate::filter_dialog::color_eyedropper_armed(app); - let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking || replace_picking); - let range_picking = - primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling); - // Select and Mask's Refine Edge Brush paints on the image. - let refine_brushing = - primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields)); - // Field Blur's pins are placed and dragged on the image (`blur_pins`). - let pinning = primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields)); - // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). - let shadow_drag = - !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); - // ⌘/Ctrl-click with Curves open: a point at the pixel's tone (#7325), whatever the tool. The - // press's own modifiers decide, and only the press adds: a drag would add one per frame. - let curve_point_press = (primary && !middle && crate::adjust_dialog::curves_on_top(app)) - .then(|| { - ctx.input(|i| { - i.events.iter().rev().find_map(|e| match e { - egui::Event::PointerButton { button: PointerButton::Primary, pressed: true, modifiers, .. } => Some(*modifiers), - _ => None, - }) - }) - }) - .flatten() - .map(|m| crate::workspace_ui::sticky_mods(app, m)) - .filter(|m| m.command); - let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag && curve_point_press.is_none(); - // ⌘Space / ⌥Space zoom under the dialog as they do without one, before Space pans (#6460). - // With the Hand tool, ⌘ alone is Zoom In (#6434); under Curves that press is the dialog's - // point (#7325), not a zoom. - let curve_point_with_hand = curve_point_press.is_some() && app.ui.tool == Tool::Hand; - let held_zoom = - !middle && !curve_point_with_hand && matches!(temporary, Some(crate::hold_keys::Temporary::ZoomIn | crate::hold_keys::Temporary::ZoomOut)); - if held_zoom { - let alt = ctx.input(|i| i.modifiers.alt); - if free_hover { - ctx.set_cursor_icon(crate::tool_cursor::zoom(&ctx, zoom_out(alt))); - } - let b = crate::dialogs::free_buttons(&ctx, rect); - let pointer = ctx.input(|i| i.pointer.latest_pos()); - crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &b, pointer); - if b.clicked - && let Some(p) = pointer - { - let nz = crate::zoom_levels::step(view.zoom, if zoom_out(alt) { -1 } else { 1 }, view.doc_size); - zoom_about(&mut view, &xf, p, nz, app.session.prefs().tools.zoom_clicked_point_to_center, ppp); - } - } else if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) { - let d = xf.unmap_vec(d) / (view.zoom / ppp); - view.center[0] -= d.x; - view.center[1] -= d.y; - ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true)); - } else if free_hover && (space_pan || hand) { - ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, false)); - } else if shadow_drag && !middle && crate::dialogs::free_pointer_over(&ctx, rect).is_some() { - ctx.set_cursor_icon(egui::CursorIcon::Move); - if let Some(p) = crate::dialogs::free_press(&ctx, rect) { - let (start, origin) = ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.press_origin().unwrap_or(p))); - let total = xf.unmap_vec(p - origin) / (view.zoom / ppp); - if let Some(d) = app.ui.dialogs.last_mut() { - crate::layer_style::drag_shadow(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)]); - } - } - } else if picking && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) { - if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - ctx.set_cursor_icon(egui::CursorIcon::Crosshair); - } else { - ctx.set_cursor_icon(pipette_cursor(&ctx, p)); - } - if let Some(p) = crate::dialogs::free_press(&ctx, rect) { - let d = xf.to_doc(p); - if curves_picking { - crate::adjust_dialog::sample_at(app, d[0], d[1]); - } else if replace_picking { - crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]); - } else { - crate::color_picker_ui::sample_at(app, d[0], d[1]); - } - } - } else if pinning - && !middle - && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) - { - let press = crate::dialogs::free_press(&ctx, rect); - crate::blur_pins::canvas(app, &ctx, &xf, p, press); - } else if refine_brushing - && !middle - && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) - { - let press = crate::dialogs::free_press(&ctx, rect).map(|q| xf.to_doc(q)); - crate::select_mask_view::canvas_brush(app, &painter, p, press, xf.zoom_x()); - } else if let Some(mods) = curve_point_press - && let Some(p) = crate::dialogs::free_press(&ctx, rect) - { - let d = xf.to_doc(p); - crate::adjust_dialog::add_point_at(app, &ctx, d[0], d[1], mods.shift); - } else if primary - && !middle - && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect).filter(|p| img_rect.contains(*p)) - { - // Color Range samples colours with its eyedropper on the image itself. - let press = crate::dialogs::free_press(&ctx, rect) - .filter(|p| img_rect.contains(*p) && ctx.input(|i| i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO)) - .map(|q| xf.to_doc(q)); - crate::color_range_ui::canvas_eyedropper(app, &ctx, p, press); - } + handle_dialog_canvas_input( + app, + DialogCanvasInput { + ctx: &ctx, + view: &mut view, + xf: &xf, + rect, + painter: &painter, + ppp, + primary, + middle, + space_pan, + temporary, + free_hover, + img_rect, + }, + ); } + // The selected Hand yields to an open Free Transform box in this (primary) window: the box // owns the pointer, so the tool behind it cannot steal the resize drag (#2302). The held Hand // (Space) and a middle-button drag still pan, and a secondary window's Hand never stops, as the @@ -1001,7 +1122,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // it owns the press: no scrub, and its release is no click step. if tool == Tool::Zoom && !transform_owns_pointer { let out = zoom_out(ui.input(|i| i.modifiers.alt)); - let on_canvas = !under_dialog && !over_compass && response.is_pointer_button_down_on(); + let on_canvas = false; let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(&ctx, &mut view, &xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); @@ -1274,7 +1395,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } else { xf }; - let (beyond, layer_edges, edge_rect) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf)); + let (beyond, layer_edges, edge_rect) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf, &paint_input)); // A Hand drag (the tool, Space or the middle button) keeps every overlay on screen, as in // Photoshop: the Pen path being drawn, paths, guides, grid, transform box (#6592). Only the // tool cursors below give way to the fist. diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index a7048ea3c5..06819c5ea1 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -1,6 +1,6 @@ use super::tool_input::ToolEvent; use super::view_xform::ViewXform; -use super::*; +use super::{Color32, PhotocraftApp, Pos2, Rect, Stroke, Tool, json, pos2, vec2}; /// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many /// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs index 1cfae7a46d..3b111232bd 100644 --- a/crates/ui-egui/src/canvas/display.rs +++ b/crates/ui-egui/src/canvas/display.rs @@ -1,5 +1,5 @@ use super::strokes::live_stroke; -use super::*; +use super::{Color32, Document, LayerContent, PhotocraftApp, TextureOptions}; pub(super) fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId { // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change). diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index a58e8db11b..6083756416 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -1,5 +1,5 @@ use super::view_xform::ViewXform; -use super::*; +use super::{PhotocraftApp, Pos2, Rect, Stroke, Tool, vec2}; /// An in-progress pointer gesture on the canvas. #[derive(Clone, Debug)] diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 6940b7b720..436d25ec24 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -1,6 +1,6 @@ use super::display::canvas_display; use super::textures::texture_buffer; -use super::*; +use super::{Document, LayerContent, PhotocraftApp}; /// The proxy factor of a live preview of filter `cmd` with `params` on `doc`, the active document: /// reduced on a large document (Preferences › Performance › Low Resolution Previews), except for diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 81c0b231a4..251b6c9205 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -4,7 +4,7 @@ use super::strokes::{ EngineStroke, commit_brush_stroke, feed_live_stroke, live_retouch_command, offer_live_retouch, paint_target, snap_aliased_tip, stroke_params, }; use super::textures::shown_as_document; -use super::*; +use super::{PhotocraftApp, Tool, json}; pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { // Control can select a different tool and release before the next frame cancels the drag. diff --git a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs index c735918576..9f5df3ebd6 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs @@ -1,5 +1,5 @@ use super::doc_textures::mip_count; -use super::*; +use super::wgpu; /// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers. pub const MIN_GPU_BUDGET: u64 = 512 << 20; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/callback.rs b/crates/ui-egui/src/canvas/gpu_canvas/callback.rs index c128a8f297..23e11399b0 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/callback.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/callback.rs @@ -1,5 +1,5 @@ use super::resources::{CanvasStyle, Resources, ViewGpu, f32_bytes}; -use super::*; +use super::{CallbackResources, CallbackTrait, ScreenDescriptor, VIEW_FLOATS, VIEW_UNIFORM_SIZE, ViewParams, wgpu}; // --------------------------------------------------------------------------------------------- // Per-frame callback diff --git a/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs b/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs index 05a40faa1a..fb09f08e14 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs @@ -1,7 +1,7 @@ use super::budget::canvas_texture_bytes; use super::resources::{DocTextures, Resources, Tile, f32_bytes}; use super::texels::texel_bytes; -use super::*; +use super::{Ordering, WHOLE_MIP_SIDE, wgpu}; pub(super) fn mip_count(w: u32, h: u32) -> u32 { 32 - w.max(h).max(1).leading_zeros() diff --git a/crates/ui-egui/src/canvas/gpu_canvas/perf.rs b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs index 8c22dfbf89..4e9068ebeb 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/perf.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs @@ -1,7 +1,7 @@ use super::budget::video_memory; use super::setup::Refresh; use super::texels::LayerFit; -use super::*; +use super::wgpu; /// Milliseconds since the process (or page) started, from a monotonic clock. /// diff --git a/crates/ui-egui/src/canvas/gpu_canvas/resources.rs b/crates/ui-egui/src/canvas/gpu_canvas/resources.rs index 27606b7c05..721377e928 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/resources.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/resources.rs @@ -2,7 +2,7 @@ use super::budget::{canvas_budget, physical_memory}; use super::doc_textures::init_buffer; use super::shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; use super::texels::LayerFit; -use super::*; +use super::{FORMAT, FORMAT_HIGH, HashMap, NonZeroU64, TILE_UNIFORM_SIZE, VIEW_FLOATS, VIEW_UNIFORM_SIZE, wgpu}; pub(super) struct Resources { pub(super) view_bgl: wgpu::BindGroupLayout, diff --git a/crates/ui-egui/src/canvas/gpu_canvas/setup.rs b/crates/ui-egui/src/canvas/gpu_canvas/setup.rs index 8195148a45..d36b97df82 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/setup.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/setup.rs @@ -1,5 +1,5 @@ use super::texels::texels; -use super::*; +use super::{egui_wgpu, wgpu}; /// A CPU composite as the canvas texture stores it (`display`'s encoding; as is without one). pub(super) fn texture_buffer<'a>( diff --git a/crates/ui-egui/src/canvas/gpu_canvas/texels.rs b/crates/ui-egui/src/canvas/gpu_canvas/texels.rs index 966b23c40c..5350ea5fae 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/texels.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/texels.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{FORMAT, FORMAT_HIGH, wgpu}; /// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA8, split across threads on native. pub fn premultiply_rgba8(px: &[[f32; 4]]) -> Vec { diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs index d95c9a20ec..413bf82686 100644 --- a/crates/ui-egui/src/canvas/navigator.rs +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -1,7 +1,7 @@ use super::display::{canvas_display, display_doc, display_image}; use super::strokes::live_stroke; use super::textures::{effect_reach, ensure_texture}; -use super::*; +use super::{Document, PhotocraftApp, Rect, TextureOptions}; /// Longest side of the Navigator panel's image (about twice the panel's width, for HiDPI). pub const NAVIGATOR_SIDE: u32 = 512; diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs index b9a040257e..415bb071a7 100644 --- a/crates/ui-egui/src/canvas/paint.rs +++ b/crates/ui-egui/src/canvas/paint.rs @@ -6,7 +6,7 @@ use super::gesture::constrained_polygon_point; use super::strokes::{EngineStroke, SPOT_HEALING_TRAIL, draw_smoothing_string, strokes_live}; use super::textures::texture_side; use super::view_xform::ViewXform; -use super::*; +use super::{Color32, DRect, Document, Mesh, PhotocraftApp, Pos2, Rect, Stroke, TextureOptions, Tool, json, pos2, vec2}; /// A texture mapped over the `size` document area starting at `origin` (follows a rotated view). pub(super) fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index fe096f1159..67577e2a27 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -1,5 +1,5 @@ use super::tool_input::selection_drag_kind; -use super::*; +use super::{PhotocraftApp, Tool, json}; /// Photoshop's cursor over a selection: what a press (or the drag under way) would do. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/ui-egui/src/canvas/start_screen.rs b/crates/ui-egui/src/canvas/start_screen.rs index d22295886c..e8b6633e5a 100644 --- a/crates/ui-egui/src/canvas/start_screen.rs +++ b/crates/ui-egui/src/canvas/start_screen.rs @@ -1,5 +1,5 @@ use super::tabs::{open_on_double_click, paint_dots}; -use super::*; +use super::{PhotocraftApp, Rect, Sense}; /// The Home screen's card is this wide when the canvas has room, and as wide as the canvas when it doesn't. const HOME_CARD_WIDTH: f32 = 460.0; diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index c970c39a20..11a288eb6a 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -2,7 +2,7 @@ use super::display::{canvas_display, display_image}; use super::drag::Drag; use super::textures::{canvas_texture_options, shown_as_document}; use super::view_xform::ViewXform; -use super::*; +use super::{Color32, DRect, PhotocraftApp, Pos2, Stroke, Tool, json, pos2}; pub(crate) struct ClonePreviewCache { pub(super) key: String, diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 5f59f3c028..82a1e2089f 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -1,6 +1,6 @@ use super::start_screen::start_screen; use super::textures::retain_gpu_documents; -use super::*; +use super::{Color32, PhotocraftApp, Pos2, Rect, Sense, Stroke, TextureOptions, canvas_view, fmt_zoom, json, mode_label, pos2}; /// Tabs + canvas for the active document, or the start screen; then drops layers dragged onto /// another document (`layer_transfer`). diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 17b6f1bf26..5c6ad3f12a 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -3,7 +3,7 @@ use super::filter_preview::filter_channel_preview; use super::navigator::navigator_waits_for_drag; use super::strokes::live_stroke; use super::view_xform::ViewXform; -use super::*; +use super::{CanvasCache, CpuTextures, DRect, DetailTexture, Document, InView, LayerContent, PhotocraftApp, TextureOptions, pos2}; /// Largest texture side we upload; bigger documents are uploaded downsampled, with the part in /// view added at the screen's resolution when zoomed in (`detail_plan`). diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index a58555037a..d193bf6e00 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -3,7 +3,7 @@ use super::drag::Drag; use super::gesture::{finish_gesture, polygon_click, selection_mode}; use super::selection::finish_selection_drag; use super::strokes::{HOLD_REPEAT_MS, begin_live_stroke, feed_live_stroke, paint_target, snap_aliased_tip, stroke_params, strokes_live}; -use super::*; +use super::{PhotocraftApp, Tool, json}; /// Abstract tool event, produced by the mouse or by automation (`ui.pointer`). #[derive(Clone, Copy, Debug, PartialEq)] @@ -52,8 +52,7 @@ fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui: } } -/// Tool state machine. Shared by mouse input and automation. -pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { +fn preflight_tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> Option<(bool, egui::Modifiers)> { // A press anywhere but on a guide deselects the selected guide (`guide_select`). if let ToolEvent::Down { x, y, .. } = ev && app.ui.selected_guide.is_some() @@ -62,7 +61,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) crate::guide_select::clear(app); } if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { - return; + return None; } // An Alt+right-drag armed for this press (`paint_mouse`): taken before anything else can // consume the event, so it never outlives the press it was armed for (#297). @@ -70,11 +69,11 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) crate::transform_tool::end_if_left(app); let mods = crate::workspace_ui::sticky_mods(app, mods); if app.ui.transform.is_none() && crate::type_transform::pointer(app, ev, mods) { - return; + return None; } // Content-Aware Move's Transform On Drop box takes every press until ↩ or Esc. if crate::cam_transform::pointer(app, ev, mods) { - return; + return None; } // A Mixer Brush press that loaded paint stays a sample press until it is released, with ⌥ // let go or not (`mixer_sampling`; `canvas_view` holds back egui's later drag start too). @@ -82,9 +81,9 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ToolEvent::Down { .. } => app.mixer_sampling = false, ToolEvent::Up { .. } if app.mixer_sampling => { app.mixer_sampling = false; - return; + return None; } - _ if app.mixer_sampling => return, + _ if app.mixer_sampling => return None, _ => {} } // The tool in use, so a held temporary tool (⌘ = Move) with ⌥ doesn't load paint. @@ -98,13 +97,17 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) app.ui.status_error = true; } } - return; + return None; } + Some((armed, mods)) +} + +fn filter_event_before_tool(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers, armed: bool) -> Option<(ToolEvent, ToolEvent, egui::Modifiers)> { // View › Snap / Snap To and smart guides (snap_ui.rs). let raw = ev; // The Move tool's marquee selecting layers takes its moves and release unsnapped (move_box.rs). if crate::move_box::pointer(app, raw) { - return; + return None; } // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first; the // Move tool (⌘ with a painting tool too, `event_tool`) drags it from anywhere. @@ -120,29 +123,29 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) // can land outside the corner's grab area and turn a corner drag into a move of the whole box. let transform_ev = if matches!(raw, ToolEvent::Down { .. }) { raw } else { ev }; if crate::transform_tool::pointer(app, transform_ev, mods) { - return; + return None; } if crate::distort_ui::pointer(app, ev, mods) { - return; + return None; } if crate::perspective_crop_ui::pointer(app, ev) { - return; + return None; } // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys. let mods = crate::workspace_ui::sticky_mods(app, mods); // ⌘⌥⌃-click with any tool selects the topmost layer with pixels there (quick_pick.rs); it // must run before the ⌃⌥ brush resize below, which the same keys would trigger. if crate::quick_pick::pointer(app, ev, mods) { - return; + return None; } // Control+Alt-drag or Alt+right-drag with a painting tool resizes the brush instead of // painting (#231, #297). if crate::brush_resize::pointer(app, ev, mods, armed) { - return; + return None; } // ⌥ (Alt) with a painting tool is the Eyedropper for that press. if alt_eyedropper(app, ev, mods) { - return; + return None; } // Move tool: ⇧ locks the axis, ⌥ duplicates (move_mods.rs). let ev = crate::move_mods::filter_event(app, ev, mods); @@ -150,39 +153,39 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) // transform controls). Unsnapped, as Free Transform's handles: snapping would pull the press // off a widget onto a nearby vertex or guide, and the shape tool would draw a new shape. if crate::corner_radius::pointer(app, raw, mods) { - return; + return None; } // Direct Selection, and the Pen's ⌘ (Direct Selection) and ⌥ (Convert Point) modes (#790). if crate::direct_select::pointer(app, ev, mods) { - return; + return None; } // Add / Delete Anchor Point tools (#1044). if crate::anchor_tools::pointer(app, ev, mods) { - return; + return None; } // Ruler, Count and Note tools. if crate::analysis_ui::pointer(app, ev, mods) { - return; + return None; } // Slice and Slice Select tools. if crate::slice_ui::pointer(app, ev, mods) { - return; + return None; } // Frame tool: draw rectangular and elliptical frames. if crate::frame_tool::pointer(app, ev, mods) { - return; + return None; } // Artboard tool: draw, select, move and resize boards. if crate::artboard_tool::pointer(app, ev, mods) { - return; + return None; } // Crop tool: draw, move and resize the frame. if crate::crop_ui::pointer(app, ev, mods) { - return; + return None; } // Gradient tool, live mode: draw and edit Gradient Fill layers. if crate::gradient_ui::pointer(app, ev, mods) { - return; + return None; } // ⌘ over a guide takes the guide (#2690, #6288); the guide drag below moves it. if let ToolEvent::Down { x, y, .. } = raw @@ -190,15 +193,107 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); crate::snap_ui::begin_guide(app, [x, y]); - return; + return None; } if crate::lasso_ui::pointer(app, ev, mods) { - return; + return None; } // Magnetic Lasso: fastening points and the border following the pointer. if crate::magnetic_lasso_ui::pointer(app, ev, mods) { - return; + return None; } + Some((raw, ev, mods)) +} + +fn handle_move_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tool: Tool, mods: egui::Modifiers) -> bool { + match ev { + ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { + if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) { + // ⌥-click turns the guide, through the point clicked, as in Photoshop. + if mods.alt && !mods.shift && !mods.command { + crate::guide_select::flip(app, vertical, i, [x, y]); + return true; + } + app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + return true; + } + // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first + // (not when the selected pixels move: those are the active layer's). + if !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.command { + let target = app.ui.tool_options.move_target.clone(); + let mode = if mods.shift { "add" } else { "replace" }; + let before = app.session.active().map(|st| st.selected_layers()); + // A locked layer under the pointer (the Background) can't move. Photoshop draws + // the layer marquee instead of reporting the lock (#4058). Probe without + // selecting so a locked hit doesn't become the selection first. + let probe = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "select": false})); + let locked_hit = probe.as_ref().ok().and_then(|v| v["layer"].as_u64()).is_some_and(|id| { + app.session.active().is_some_and(|st| { + let id = photocraft_doc::LayerId(id); + let locks = st.doc.effective_locks(id); + locks.position || locks.all || st.doc.is_background(id) + }) + }); + if locked_hit || (probe.as_ref().is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y])) { + if locked_hit { + // A click still selects the locked layer, as in Photoshop; a drag's + // marquee then replaces that selection on release. + let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + } + crate::move_box::begin(app, [x, y], mods.shift); + return true; + } + let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + // No pixels there at all (an empty spot, or off the canvas): drag a marquee that + // selects the layers it touches instead (move_box.rs). + if picked.is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y]) { + crate::move_box::begin(app, [x, y], mods.shift); + return true; + } + // Snapping (and the drag's box) started before the pick: point it at what moves. + if app.session.active().map(|st| st.selected_layers()) != before { + crate::snap_ui::retarget_move(app, [x, y], mods); + } + } + // A locked layer: no drag, and Photoshop's message once the pointer moves (`move_lock`). + if crate::move_lock::blocked(app, tool, [x, y], mods) { + app.move_blocked = true; + return true; + } + // With a selection: cut the selected pixels (⌥ copies them) and drag them as a floating + // piece, from anywhere, as a marquee ⌘-drag does. + if crate::move_ui::moves_selected_pixels_with(app, tool) { + if crate::move_ui::float_selected(app, mods.alt, 0.0, 0.0) { + let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); + d.sel_move = Some(true); + app.drag = Some(d); + } + return true; + } + } + ToolEvent::Move { x, y, .. } => { + if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { + d.pos = if d.vertical { x } else { y }; + return true; + } + } + ToolEvent::Up { x, y } => { + if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { + app.guide_drag = None; + d.pos = if d.vertical { x } else { y }; + crate::rulers::finish_drag(app, d); + return true; + } + } + _ => {} + } + false +} + +/// Tool state machine. Shared by mouse input and automation. +pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + let Some((armed, mods)) = preflight_tool_event(app, ev, mods) else { return }; + let Some((raw, ev, mods)) = filter_event_before_tool(app, ev, mods, armed) else { return }; let tool = event_tool(app, mods); if tool == Tool::Eyedropper { match ev { @@ -228,88 +323,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) } _ => {} } - // Move tool over a guide drags the guide (off the canvas deletes it). - match ev { - ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { - if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) { - // ⌥-click turns the guide, through the point clicked, as in Photoshop. - if mods.alt && !mods.shift && !mods.command { - crate::guide_select::flip(app, vertical, i, [x, y]); - return; - } - app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); - return; - } - // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first - // (not when the selected pixels move: those are the active layer's). - if !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.command { - let target = app.ui.tool_options.move_target.clone(); - let mode = if mods.shift { "add" } else { "replace" }; - let before = app.session.active().map(|st| st.selected_layers()); - // A locked layer under the pointer (the Background) can't move. Photoshop draws - // the layer marquee instead of reporting the lock (#4058). Probe without - // selecting so a locked hit doesn't become the selection first. - let probe = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "select": false})); - let locked_hit = probe.as_ref().ok().and_then(|v| v["layer"].as_u64()).is_some_and(|id| { - app.session.active().is_some_and(|st| { - let id = photocraft_doc::LayerId(id); - let locks = st.doc.effective_locks(id); - locks.position || locks.all || st.doc.is_background(id) - }) - }); - if locked_hit || (probe.as_ref().is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y])) { - if locked_hit { - // A click still selects the locked layer, as in Photoshop; a drag's - // marquee then replaces that selection on release. - let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); - } - crate::move_box::begin(app, [x, y], mods.shift); - return; - } - let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); - // No pixels there at all (an empty spot, or off the canvas): drag a marquee that - // selects the layers it touches instead (move_box.rs). - if picked.is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y]) { - crate::move_box::begin(app, [x, y], mods.shift); - return; - } - // Snapping (and the drag's box) started before the pick: point it at what moves. - if app.session.active().map(|st| st.selected_layers()) != before { - crate::snap_ui::retarget_move(app, [x, y], mods); - } - } - // A locked layer: no drag, and Photoshop's message once the pointer moves (`move_lock`). - if crate::move_lock::blocked(app, tool, [x, y], mods) { - app.move_blocked = true; - return; - } - // With a selection: cut the selected pixels (⌥ copies them) and drag them as a floating - // piece, from anywhere, as a marquee ⌘-drag does. - if crate::move_ui::moves_selected_pixels_with(app, tool) { - if crate::move_ui::float_selected(app, mods.alt, 0.0, 0.0) { - let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); - d.sel_move = Some(true); - app.drag = Some(d); - } - return; - } - } - ToolEvent::Move { x, y, .. } => { - if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { - d.pos = if d.vertical { x } else { y }; - return; - } - } - ToolEvent::Up { x, y } => { - if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { - app.guide_drag = None; - d.pos = if d.vertical { x } else { y }; - crate::rulers::finish_drag(app, d); - return; - } - } - _ => {} + if handle_move_pointer(app, ev, tool, mods) { + return; } + match ev { ToolEvent::Down { x, y, pressure } => { // Painting a type, shape, Smart Object or fill layer asks to rasterize it first diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs index 9d583cd604..fccc2c9751 100644 --- a/crates/ui-egui/src/canvas/transform_controls.rs +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -1,6 +1,6 @@ use super::selection::floating_outline; use super::view_xform::ViewXform; -use super::*; +use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, pos2, vec2}; /// View › Show › Layer Edges: the colour of the active layer's outline. pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb); diff --git a/crates/ui-egui/src/canvas/view_xform.rs b/crates/ui-egui/src/canvas/view_xform.rs index ec3df91d13..3a0b42ca4e 100644 --- a/crates/ui-egui/src/canvas/view_xform.rs +++ b/crates/ui-egui/src/canvas/view_xform.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{DRect, Document, PhotocraftApp, Pos2, Rect, Vec2, View, pos2, vec2}; /// Document ↔ screen mapping for a canvas rect and a view. #[derive(Clone, Copy, Debug)] diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 7057d35f55..f7b87f6e9c 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -3,7 +3,7 @@ use super::params::{ BUTTONS, KEY_MODIFIERS, MAX_CLICKS, POINTER_MODIFIERS, UI_SET_FIELDS, bool_field, err, f32_field, f32_range, input_choice, input_modifiers, input_number, input_object, merged_object, modifiers_from, num_field, ok, screen_point, uint_field, whole_object, }; -use super::*; +use super::{ControlRequest, DialogKind, Outcome, PhotocraftApp, SHELL_DIALOG, Tool, ToolEvent, Value, json, run_waiting, tool_event, wrap}; pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; diff --git a/crates/ui-egui/src/control/params.rs b/crates/ui-egui/src/control/params.rs index 0d9fbd6a49..b2d8668ecb 100644 --- a/crates/ui-egui/src/control/params.rs +++ b/crates/ui-egui/src/control/params.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Outcome, PhotocraftApp, Value, json}; /// The fields `ui.set` reads. Anything else is rejected before a field is applied, and every /// field's value is validated before the first one is applied, so a typo, an unknown field, a diff --git a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs index 00b940cdbd..18c740ab80 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs @@ -1,5 +1,8 @@ use super::hue_saturation::RANGE_LABELS; -use super::*; +use super::{ + Color32, Edit, EditorCx, HUE_RANGES, PHOTO_FILTERS, RichText, Sense, Stroke, StrokeKind, Tokens, Value, adjust_params, color_button, flag, json, label, + num, nums, pos2, rgb_of, round, tone, vec2, widgets, +}; /// Labelled slider rows over top-level keys: (key, label, min, max, default, unit). /// A row of [`sliders`]: params key, label, range, default, unit, and its decimal places (None: diff --git a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs index 7a3f4ea510..4b1867e83b 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Color32, CurveUi, Edit, EditorCx, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, ToneSpace, Value, adjust_params, curve_edit, json, label, pos2, + space_of, tone, vec2, widgets, +}; // --------------------------------------------------------------------------------------------- // Channels of Levels / Curves diff --git a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs index 99750230f1..74dc454bb7 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs @@ -1,5 +1,8 @@ use super::hue_saturation::spectrum_bar; -use super::*; +use super::{ + Color32, Edit, EditorCx, GradientPreset, Group, PhotocraftApp, Pos2, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, Value, adjust_params, color_button, + color32, flag, json, label, pos2, rgb_of, round, vec2, widgets, +}; // --------------------------------------------------------------------------------------------- // Gradient Map diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs index 042f398619..b1c61947fa 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs @@ -1,7 +1,10 @@ use super::basic::{sliders, track_stops}; use super::curves::gradient_bar; use super::levels::nearest; -use super::*; +use super::{ + Color32, Edit, EditorCx, HUE_RANGES, HueRange, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, Value, color32, flag, hue_color, json, num, nums, pos2, + vec2, widgets, +}; // --------------------------------------------------------------------------------------------- // Hue/Saturation diff --git a/crates/ui-egui/src/dialogs/adjust_editors/levels.rs b/crates/ui-egui/src/dialogs/adjust_editors/levels.rs index 8963e438e2..f1eac2a075 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/levels.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/levels.rs @@ -1,5 +1,5 @@ use super::curves::{ToneChannel, bar_color, channel_picker, gradient_bar, hist_color, tone_channels}; -use super::*; +use super::{Color32, Edit, EditorCx, Sense, Stroke, StrokeKind, Tokens, Value, json, label, pos2, round, space_of, tone, vec2, widgets}; // --------------------------------------------------------------------------------------------- // Levels diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index bb3eeeebbc..12eb73b470 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -1,6 +1,6 @@ use super::basic::reset_color_balance; use super::gradient_map::{gradient_presets, is_gray, swatches}; -use super::*; +use super::{Adjustment, EditorCx, HistSource, LayerId, PhotocraftApp, RichText, Tokens, Value, adjust_params, editor, json, needs_histogram, space_of, tone}; /// Root of an adjustment layer's Properties editor view state in egui memory. pub fn layer_mem(id: LayerId) -> egui::Id { diff --git a/crates/ui-egui/src/dialogs/caf_ui/controls.rs b/crates/ui-egui/src/dialogs/caf_ui/controls.rs index f01d4d6852..edb3087d00 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/controls.rs @@ -1,6 +1,6 @@ use super::lifecycle::{apply, cancel, close, fill_edit, redo, report, reset, set_sampling, undo}; use super::preview::{rebase, wait_preview}; -use super::*; +use super::{CafTool, CafWorkspace, LASSO_OPS, PhotocraftApp, ToolEvent, Value, json}; /// Control channel: `edit.contentAwareFill {"ui": {...}}` while the workspace is open. pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 5bc21da079..fc3cb922f1 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -1,5 +1,5 @@ use super::preview::{Base, Preview, cancel_preview, compute_base, plan_params, points_limit, rebase, refresh}; -use super::*; +use super::{CMD, CafOpts, CafTool, CafWorkspace, MAX_CAF_EDITS, MAX_CAF_POINTS, PROXY_SIDE, PhotocraftApp, REMEMBERED, Rect, Step, Value}; /// Opens the workspace on the active layer and its selection. pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { diff --git a/crates/ui-egui/src/dialogs/caf_ui/preview.rs b/crates/ui-egui/src/dialogs/caf_ui/preview.rs index 628893bf1b..cf17506e3d 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/preview.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/preview.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{CMD, CafWorkspace, Color32, LayerId, MAX_CAF_POINTS, MAX_OUTLINE_EDGES, PhotocraftApp, Rect, TextureHandle, Value, json, stroke_json}; /// What the plan (without the brush strokes) says: the window, the fill area and the sampling /// option's area, over `rect`. diff --git a/crates/ui-egui/src/dialogs/caf_ui/view.rs b/crates/ui-egui/src/dialogs/caf_ui/view.rs index f9987ff822..68d1eeeb5d 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/view.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/view.rs @@ -1,7 +1,10 @@ use super::controls::{pointer, tool_icon, tool_tip}; use super::lifecycle::{apply, bounds, cancel, commit, fill_edit, report, reset, set_sampling}; use super::preview::{drive_preview, rebase, refresh}; -use super::*; +use super::{ + Align2, BAR_H, CafTool, CafWorkspace, Color32, ERect, FontId, LEFT_W, PANEL_W, PREVIEW_W, PhotocraftApp, Pos2, Rect, Sense, Stroke, Tokens, ToolEvent, Value, json, pos2, + vec2, widgets, +}; /// A view: screen px per document px and the document point at the centre of `area`. #[derive(Clone, Copy)] @@ -26,6 +29,52 @@ impl View { } /// Upload what changed: the document proxy, the overlay, a finished preview. +/// The options bar of the Content-Aware Fill workspace, for the active tool. +fn caf_options_bar(bui: &mut egui::Ui, w: &mut CafWorkspace, fill_btn: &mut Option, reset_what: &mut Option<&str>) { + match w.tool { + CafTool::Brush => { + if crate::icons::button(bui, "plus", 26.0, w.brush_add, tl!("Add")).clicked() { + w.brush_add = true; + } + if crate::icons::button(bui, "minus", 26.0, !w.brush_add, tl!("Subtract")).clicked() { + w.brush_add = false; + } + bui.add_space(8.0); + bui.label(tl!("Size:")); + let mut size = w.brush_size as f32; + if widgets::value_field(bui, &mut size, 1.0..=5000.0, " px", 64.0).accessible_name(tl!("Size:")).changed() { + w.brush_size = f64::from(size); + } + } + CafTool::Lasso => { + // The selection tools' mode buttons (the lasso here edits the fill area). + let tips = [ + tl!("New selection").to_string(), + crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))]), + crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))]), + crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), + ]; + for (i, (icon, tip)) in ["square", "plus", "minus", "squares-subtract"].into_iter().zip(tips.iter()).enumerate() { + if crate::icons::button(bui, icon, 26.0, w.lasso_op == i, tip).clicked() { + w.lasso_op = i; + } + } + bui.add_space(8.0); + if widgets::secondary_button(bui, tl!("Expand"), 70.0).clicked() { + *fill_btn = Some(json!({"op": "expand", "by": w.expand_by})); + } + if widgets::secondary_button(bui, tl!("Contract"), 70.0).clicked() { + *fill_btn = Some(json!({"op": "contract", "by": w.expand_by})); + } + widgets::value_field(bui, &mut w.expand_by, 1.0..=100.0, " px", 56.0).accessible_name(tl!("Expand")); + if crate::icons::button(bui, "undo-2", 26.0, false, tl!("Reset")).clicked() { + *reset_what = Some("lasso"); + } + } + _ => {} + } +} + fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { let need_image = app.distort.caf.as_ref().is_some_and(|w| w.image_tex.is_none()); if need_image { @@ -108,48 +157,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { painter.line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.separator)); let mut bui = ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(LEFT_W + 8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); - match w.tool { - CafTool::Brush => { - if crate::icons::button(&mut bui, "plus", 26.0, w.brush_add, tl!("Add")).clicked() { - w.brush_add = true; - } - if crate::icons::button(&mut bui, "minus", 26.0, !w.brush_add, tl!("Subtract")).clicked() { - w.brush_add = false; - } - bui.add_space(8.0); - bui.label(tl!("Size:")); - let mut size = w.brush_size as f32; - if widgets::value_field(&mut bui, &mut size, 1.0..=5000.0, " px", 64.0).accessible_name(tl!("Size:")).changed() { - w.brush_size = f64::from(size); - } - } - CafTool::Lasso => { - // The selection tools' mode buttons (the lasso here edits the fill area). - let tips = [ - tl!("New selection").to_string(), - crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))]), - crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))]), - crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), - ]; - for (i, (icon, tip)) in ["square", "plus", "minus", "squares-subtract"].into_iter().zip(tips.iter()).enumerate() { - if crate::icons::button(&mut bui, icon, 26.0, w.lasso_op == i, tip).clicked() { - w.lasso_op = i; - } - } - bui.add_space(8.0); - if widgets::secondary_button(&mut bui, tl!("Expand"), 70.0).clicked() { - fill_btn = Some(json!({"op": "expand", "by": w.expand_by})); - } - if widgets::secondary_button(&mut bui, tl!("Contract"), 70.0).clicked() { - fill_btn = Some(json!({"op": "contract", "by": w.expand_by})); - } - widgets::value_field(&mut bui, &mut w.expand_by, 1.0..=100.0, " px", 56.0).accessible_name(tl!("Expand")); - if crate::icons::button(&mut bui, "undo-2", 26.0, false, tl!("Reset")).clicked() { - reset_what = Some("lasso"); - } - } - _ => {} - } + caf_options_bar(&mut bui, w, &mut fill_btn, &mut reset_what); + let body = ERect::from_min_max(pos2(full.left(), bar.bottom()), full.max); // Left tool strip. let left = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(LEFT_W, full.height() - title.height())); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs index 8af538511d..389af64d96 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs @@ -1,6 +1,9 @@ use super::open::{Target, cancel, commit_open_raw, open_raw, raw_stage}; use super::sidecar::{load_settings, report_file_error, save_settings}; -use super::*; +use super::{ + Align2, BANDS, CameraRaw, CameraRawDialog, Color32, ERect, FontId, PANEL_W, PhotocraftApp, Pos2, Sense, Stroke, Tokens, ToneZone, Value, Wheel, curve_lut, + json, pos2, vec2, widgets, +}; const RAW_UNDO_LIMIT: usize = 40; 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 873db1a826..908f01e1f1 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs @@ -1,5 +1,5 @@ use super::open::{Coverage, Target}; -use super::*; +use super::{CameraRaw, CameraRawDialog, LayerId, MAX_SAMPLERS, PROXY_SIDE, PhotocraftApp, Rect, RgbHistogram, Value, json}; /// Camera Raw Defaults › Sharpen For: output sharpening, folded into the Camera Raw step `rest` /// as the workflow's Sharpen For is. Returns what it applied. diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs index 91b938e14c..ead69eba2b 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs @@ -1,7 +1,7 @@ use super::controls::{commit, redo_edit, remember_edit, undo_edit}; use super::open::{cancel, open, open_smart_filter}; use super::sidecar::{load_settings, save_settings}; -use super::*; +use super::{CameraRaw, LayerId, PhotocraftApp, Value, json}; /// Menu / control-channel entry point. `None` when the call isn't for this dialog. pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { 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 429e245eb0..87e1035a85 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -1,6 +1,6 @@ use super::convert::{apply_raw_conversions, open_pixels, output_sharpening, raw_conversions}; use super::sidecar::{read_sidecar, write_sidecar}; -use super::*; +use super::{CameraRaw, LayerId, PhotocraftApp, Rect, Value, json}; /// Opens the dialog on the active layer. /// Where OK writes: a new filter on the layer, or an existing smart filter (by index). diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs index 93e00960b0..46a82b140f 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs @@ -1,5 +1,5 @@ use super::open::raw_stage; -use super::*; +use super::{CameraRaw, CameraRawDialog, PARALLEL_MIN_PIXELS, RgbHistogram}; /// Everything one develop of the proxy reads, owned, so it can run off the UI thread. pub(super) struct ProxyJob { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs index 1b5b6c9a3d..dfb03a13b9 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs @@ -1,6 +1,6 @@ use super::controls::remember_edit; use super::open::RawOpen; -use super::*; +use super::{CameraRaw, PhotocraftApp, Value, json}; /// The sidecar beside a raw file: `IMG_0001.xmp` for `IMG_0001.CR2`, as Camera Raw names it. pub fn sidecar_path(path: &str) -> String { diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 0a596a307b..c077259f92 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Arc, DialogKind, Map, PhotocraftApp, Tokens, Value, b, check, dropdown_str, json, n, number, params, s}; /// Print's Printer menu: the default printer (value ""), then every printer `file.printers` /// listed. A saved name the spooler no longer lists stays selectable rather than vanishing. diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index a2d45fa2f3..a370da2003 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Arc, DialogKind, Map, PhotocraftApp, Tokens, Value, WebSettings, b, check, dropdown_str, json, n, number, params, s, web_cmds, web_preview}; const WEB_FORMATS: [(&str, &str); 5] = [("gif", "GIF"), ("png8", "PNG-8"), ("png24", "PNG-24"), ("jpeg", "JPEG"), ("wbmp", "WBMP")]; diff --git a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs index 44399b7d52..ef2a6a5475 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web_preview.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs @@ -1,5 +1,5 @@ //! Save for Web navigation and indexed palette UI. Draft state is serialized in dialog fields. -use super::*; +use super::{Arc, Map, Optimized, PhotocraftApp, Tokens, Value, WebSettings, json, n, params, s, web_cmds}; /// Export dimensions, using the same percent/width/height precedence as web_document. pub fn dimensions(doc: &photocraft_doc::Document, p: &Value) -> Result<(f64, f64), String> { diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index 5d4da05bff..8caea3cd7b 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -885,6 +885,60 @@ fn backdrop_layering(backdrop: Option, mode: BackdropMode, opacity: } /// Draws the dialog (a full-window layer over the app). +fn draw_tool_strip(ui: &mut egui::Ui, painter: &egui::Painter, t: &Tokens, d: &mut LiquifyDialog, body: ERect) -> ERect { + // Left tool strip. + let left = ERect::from_min_size(body.min, vec2(LEFT_W, body.height())); + painter.rect_filled(left, 0.0, t.dock); + painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); + let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); + strip.spacing_mut().item_spacing.y = 4.0; + for tool in LiquifyTool::ALL { + let tip = match tool { + // The lasso works on the same freeze mask as Freeze/Thaw. + LiquifyTool::LassoMask => tl!("Freeze Lasso: drag to freeze an area, Alt-drag to thaw it (L)").to_string(), + _ => format!("{} ({})", tl!(tool.label()), shortcut(tool)), + }; + if crate::icons::button(&mut strip, tool_icon(tool), 34.0, d.opts.tool == tool, &tip).clicked() { + d.opts.tool = tool; + } + if matches!(tool, LiquifyTool::Smooth | LiquifyTool::PushLeft | LiquifyTool::Thaw) { + strip.add_space(6.0); + } + } + left +} + +/// The preview's wheel and trackpad input: zoom about the pointer, or pan. +fn apply_preview_wheel(ctx: &egui::Context, d: &mut LiquifyDialog, area: ERect, resp: &egui::Response, wheel_id: egui::Id, pinch_zooms: bool, animated_zoom: bool) { + let wheel = crate::wheel_nav::read(ctx, true, pinch_zooms, animated_zoom, wheel_id, resp.hovered()); + if let Some(hp) = resp.hover_pos() { + let zoom = match wheel { + Some(crate::wheel_nav::Wheel::Zoom(f)) => { + let z = d.zoom * f; + // At a limit, drop the rest of an eased notch, or it would swallow the first notch back. + if z != z.clamp(ZOOM_MIN, ZOOM_MAX) { + crate::wheel_nav::settle(ctx, wheel_id); + } + Some(z.clamp(ZOOM_MIN, ZOOM_MAX)) + } + Some(crate::wheel_nav::Wheel::SnapZoom(n)) => { + Some((0..n.unsigned_abs()).fold(d.zoom, |z, _| crate::zoom_levels::step_in_range(z, n.signum(), ZOOM_MIN, ZOOM_MAX))) + } + Some(crate::wheel_nav::Wheel::Pan(v)) => { + d.center = [d.center[0] - f64::from(v.x / d.zoom), d.center[1] - f64::from(v.y / d.zoom)]; + None + } + None => None, + }; + if let Some(z) = zoom { + let before = to_doc(d, area, hp); + d.zoom = z; + let after = to_doc(d, area, hp); + d.center = [d.center[0] + before[0] - after[0], d.center[1] + before[1] - after[1]]; + } + } +} + pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let screen = ctx.content_rect(); @@ -924,25 +978,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { t.text, ); let body = ERect::from_min_max(pos2(full.left(), title.bottom()), full.max); - // Left tool strip. - let left = ERect::from_min_size(body.min, vec2(LEFT_W, body.height())); - painter.rect_filled(left, 0.0, t.dock); - painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); - let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); - strip.spacing_mut().item_spacing.y = 4.0; - for tool in LiquifyTool::ALL { - let tip = match tool { - // The lasso works on the same freeze mask as Freeze/Thaw. - LiquifyTool::LassoMask => tl!("Freeze Lasso: drag to freeze an area, Alt-drag to thaw it (L)").to_string(), - _ => format!("{} ({})", tl!(tool.label()), shortcut(tool)), - }; - if crate::icons::button(&mut strip, tool_icon(tool), 34.0, d.opts.tool == tool, &tip).clicked() { - d.opts.tool = tool; - } - if matches!(tool, LiquifyTool::Smooth | LiquifyTool::PushLeft | LiquifyTool::Thaw) { - strip.add_space(6.0); - } - } + let left = draw_tool_strip(ui, &painter, &t, d, body); // Right properties panel. let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height())); painter.rect_filled(right, 0.0, t.dock); @@ -1047,33 +1083,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // Preferences › Enhanced Controls › Zoom with Trackpad Pinch is off); a sideways scroll // pans (#7210). Read every frame, as `wheel_nav` asks, so its modifier state follows. let wheel_id = egui::Id::unique("liquify-preview-wheel"); - let wheel = crate::wheel_nav::read(ctx, true, pinch_zooms, animated_zoom, wheel_id, resp.hovered()); - if let Some(hp) = resp.hover_pos() { - let zoom = match wheel { - Some(crate::wheel_nav::Wheel::Zoom(f)) => { - let z = d.zoom * f; - // At a limit, drop the rest of an eased notch, or it would swallow the first notch back. - if z != z.clamp(ZOOM_MIN, ZOOM_MAX) { - crate::wheel_nav::settle(ctx, wheel_id); - } - Some(z.clamp(ZOOM_MIN, ZOOM_MAX)) - } - Some(crate::wheel_nav::Wheel::SnapZoom(n)) => { - Some((0..n.unsigned_abs()).fold(d.zoom, |z, _| crate::zoom_levels::step_in_range(z, n.signum(), ZOOM_MIN, ZOOM_MAX))) - } - Some(crate::wheel_nav::Wheel::Pan(v)) => { - d.center = [d.center[0] - f64::from(v.x / d.zoom), d.center[1] - f64::from(v.y / d.zoom)]; - None - } - None => None, - }; - if let Some(z) = zoom { - let before = to_doc(d, area, hp); - d.zoom = z; - let after = to_doc(d, area, hp); - d.center = [d.center[0] + before[0] - after[0], d.center[1] + before[1] - after[1]]; - } - } + apply_preview_wheel(ctx, d, area, &resp, wheel_id, pinch_zooms, animated_zoom); d.update_view_preview(ctx, area); let img = ERect::from_min_max( to_screen(d, area, [f64::from(d.canvas.x0), f64::from(d.canvas.y0)]), diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index cca640fbba..a8497bb5ec 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -54,6 +54,11 @@ fn picker_lists_english_first_then_names_alphabetically() { #[test] fn tags_map_to_languages() { + western_and_legacy_tags_resolve(); + chinese_tags_resolve_by_region_and_script(); +} + +fn western_and_legacy_tags_resolve() { assert_eq!(lang_from_tag("ja_JP.UTF-8"), Some(JA())); assert_eq!(lang_from_tag("ja-JP"), Some(JA())); assert_eq!(lang_from_tag("en_US.UTF-8"), Some(Lang::EN)); @@ -73,6 +78,9 @@ fn tags_map_to_languages() { assert_eq!(lang_from_tag("tr_TR.UTF-8"), Lang::from_code("tr")); assert_eq!(lang_from_tag("tr-TR"), Lang::from_code("tr")); assert_eq!(lang_from_tag("tr"), Lang::from_code("tr")); +} + +fn chinese_tags_resolve_by_region_and_script() { // Traditional Chinese: by region, by script, and with a region after the script. assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH())); assert_eq!(lang_from_tag("zh-TW"), Some(ZH())); diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 807f748a49..d53185d12a 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -479,11 +479,11 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) { } } -fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { +fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { // A held tool letter released: a temporary tool gives the previous one back (#2672). crate::spring_tools::tick(app, ctx); if crate::canvas::cancel_mixer_on_context_change(app, ctx) { - return; + return false; } // However the tool was picked (toolbar, flyout, shortcut, automation), its group's key brings // it back later (#2608). @@ -492,12 +492,12 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // tools) runs beneath it, and it handles its own keys (Y, U, O, S). Unlike the other dialogs // below it covers the canvas, so canvas zoom keys are blocked too. if app.camera_raw.is_some() { - return; + return false; } // A foreground save (Save in Background off, #6207) blocks the app until the file is written; // only Esc reaches it, to cancel while it still encodes (see `jobs_ui::tick`). if crate::jobs_ui::foreground_save(app).is_some() { - return; + return false; } // An open menu owns the keyboard (arrows, ↩, Esc), like a native menu; so does the menu bar // once Alt or F10 put the keyboard on it (#4988), and an open dropdown list, whose letters @@ -505,7 +505,7 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // off the bar first and runs, as with a native menu bar (#6573). crate::menu_keys::leave_for_shortcut(ctx); if crate::menu_nav::is_open(ctx) || crate::menu_keys::is_focused(ctx) || crate::widgets::dropdown_list_open(ctx) { - return; + return false; } // ⌘Z in a filter or adjustment dialog steps the dialog's settings, not the document (#4697). crate::edit_history::keys(app, ctx); @@ -514,18 +514,18 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // the editor's explicit state; otherwise Escape deselects or commits a pending Pen path. // Modified commands such as Undo still follow the ordinary dispatch below. if app.ui.stroke_editor.is_some() && !ctx.input(|i| i.modifiers.command || i.modifiers.ctrl) { - return; + return false; } // So does the right-click menu of text being edited: Esc closes only it, and keys typed while // it is open don't reach the text beneath. The crop menu's likewise: Esc and ↵ don't cancel or // commit the crop under it (#6561). if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text || m.crop.is_some()) { - return; + return false; } let symmetry_editing = app.ui.symmetry_transform.is_some(); crate::symmetry_ui::track(app, ctx); if symmetry_editing && (app.ui.symmetry_transform.is_none() || egui::Popup::is_any_open(ctx)) { - return; + return false; } // Before any key handler: per-layout symbol keys and the bracket fallback (#3102, #3109). if !ctx.text_edit_focused() { @@ -552,8 +552,11 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { if app.distort.caf.is_some() && !ctx.text_edit_focused() { crate::caf_ui::keys(app, ctx); } + true +} + +fn handle_modal_canvas_keys(app: &mut PhotocraftApp, ctx: &egui::Context, focus: crate::shortcut_dispatch::Focus) -> bool { use crate::shortcut_dispatch::{Focus, dispatch_pressed}; - let focus = Focus::of(ctx); // Dialogs (and Liquify's panel while one of its controls has focus) keep canvas zoom; a // focused text field keeps its keys. let liquify_focus = (app.distort.liquify.is_some() || app.distort.caf.is_some()) && focus != Focus::None; @@ -561,57 +564,57 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { if focus != Focus::Text { nav_keys(app, ctx); } - return; + return true; } if focus == Focus::Text { // A focused field keeps its typing and editing keys; menu shortcuts (⌘J, ⌘S, F7…) still // fire, as in Photoshop. dispatch_pressed(app, ctx, focus, false); - return; + return true; } // Liquify / Puppet Warp / Perspective Warp: ↩ commits, Esc cancels. if crate::distort_ui::keys(app, ctx) { - return; + return true; } // Free Transform: ↩ commits, Esc cancels. if app.ui.transform.is_some() { if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { crate::transform_tool::commit(app); - return; + return true; } if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { crate::transform_tool::cancel(app); - return; + return true; } } // Content-Aware Move's Transform On Drop box: ↩ computes the move, Esc drops it. if crate::cam_transform::active(app) { if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { crate::cam_transform::commit(app); - return; + return true; } if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { crate::cam_transform::cancel(app); - return; + return true; } } // A Properties Levels/Curves eyedropper: Esc disarms it. if crate::layer_picker::armed(app).is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { crate::layer_picker::cancel(app); - return; + return true; } // Crop tool with a pending frame: arrows nudge it (⇧ ×10) and X swaps its orientation, before // the selection / layer nudge and the X colour swap (#1919). if focus == Focus::None && crate::crop_ui::keys(app, ctx) { - return; + return true; } // Perspective Crop with a pending quad: ↵ commits, Esc cancels. if focus == Focus::None && crate::perspective_crop_ui::keys(app, ctx) { - return; + return true; } // Move tool / Free Transform: arrows nudge (⇧ ×10, ⌥ duplicates first). if focus == Focus::None && crate::move_mods::arrow_keys(app, ctx) { - return; + return true; } // Moved pixels still floating: ↩ drops them. if focus == Focus::None @@ -622,8 +625,50 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { app.ui.status = e; app.ui.status_error = true; } + return true; + } + false +} + +fn handle_lasso_vertex_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + // While placing polygonal lasso vertices, Backspace/Delete retracts the last point; + // it must win over the regular Edit › Clear shortcut, which edits document pixels. + if crate::lasso_ui::waiting_for_vertex(app) { + let mods = ctx.input(|i| i.modifiers); + if !mods.command && !mods.ctrl && !mods.shift && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { + crate::lasso_ui::undo_last_vertex(app); + return true; + } + } + // The Polygonal Lasso tool likewise: ⌫/Delete removes the last vertex (#1229), and never + // reaches Edit › Clear while a polygon is being drawn. + if !app.ui.polygon.is_empty() { + let mods = ctx.input(|i| i.modifiers); + if !mods.command && !mods.ctrl && !mods.shift && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { + crate::canvas::polygon_retract(app); + return true; + } + } + false +} + +fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + if !preflight_keys(app, ctx) { return; } + let focus = crate::shortcut_dispatch::Focus::of(ctx); + if handle_modal_canvas_keys(app, ctx, focus) || handle_pen_and_work_path_keys(app, ctx, focus) || handle_object_tool_keys(app, ctx) { + return; + } + if handle_registry_and_tool_keys(app, ctx, focus) { + return; + } + handle_escape_and_view_keys(app, ctx); +} + +/// Pen path keys (#1466, #1769), the work-path delete key (#5702), and in-progress lasso state. +/// Returns true when one of them consumed the key. +fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, focus: crate::shortcut_dispatch::Focus) -> bool { // A Pen path's points are uncommitted gesture state, not History entries (#1466). // Intercept Cmd/Ctrl+Z before the normal Edit › Undo shortcut, as well as unmodified // Backspace/Delete. Once the last anchor is removed, regular Undo works again. @@ -639,97 +684,80 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)); if command_undo || remove { crate::vector_ui::pen_undo_last_point(app); - return; + return true; } } // Pen path in progress: ↩ and Esc both end it as an open path and keep it, as in Photoshop (#1769). if app.ui.pen.is_some() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter) || i.consume_key(Modifiers::NONE, Key::Escape)) { crate::vector_ui::pen_commit(app, false); - return; + return true; } // A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in // Photoshop (#5702), never Edit › Clear on the pixels under it. - if focus != Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { + if focus != crate::shortcut_dispatch::Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { let mods = ctx.input(|i| i.modifiers); - if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) - { + if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { if let Err(e) = app.run("path.delete", json!({"name": "work"})) { app.ui.status = e; app.ui.status_error = true; } - return; + return true; } } + false +} + +/// Magnetic Lasso, lasso vertices, guides, slices and smart-filter rows: each owns ⌫/Delete (and ↩/Esc) +/// in its own context, so none of them reaches Edit › Clear. Returns true when one consumed the key. +fn handle_object_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { // Magnetic Lasso: ↩ closes, Esc cancels, ⌫ removes a fastening point (not Edit › Clear), // [ ] change the detection width (not the brush size). - if crate::magnetic_lasso_ui::keys(app, ctx) { - return; - } - // While placing polygonal lasso vertices, Backspace/Delete retracts the last point; - // it must win over the regular Edit › Clear shortcut, which edits document pixels. - if crate::lasso_ui::waiting_for_vertex(app) { - let mods = ctx.input(|i| i.modifiers); - if !mods.command && !mods.ctrl && !mods.shift && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { - crate::lasso_ui::undo_last_vertex(app); - return; - } - } - // The Polygonal Lasso tool likewise: ⌫/Delete removes the last vertex (#1229), and never - // reaches Edit › Clear while a polygon is being drawn. - if !app.ui.polygon.is_empty() { - let mods = ctx.input(|i| i.modifiers); - if !mods.command && !mods.ctrl && !mods.shift && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { - crate::canvas::polygon_retract(app); - return; - } + if crate::magnetic_lasso_ui::keys(app, ctx) || handle_lasso_vertex_keys(app, ctx) { + return true; } // A selected guide: ⌫/Delete removes it (`guide_select`), never Edit › Clear's pixels. if crate::guide_select::keys(app, ctx) { - return; + return true; } // A slice selected with Slice Select: ⌫/Delete deletes the slice, not the layer (#7862). if crate::slice_ui::keys(app, ctx) { - return; + return true; } // A selected smart filter row: ⌫/Delete removes the filter, not its smart object (#4751). - if crate::smart_ui::keys(app, ctx) { - return; - } + crate::smart_ui::keys(app, ctx) +} + +/// Registry shortcuts, inline type, and the crop-tool and single-key tool shortcuts. Returns true +/// when one consumed the key. +fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, focus: crate::shortcut_dispatch::Focus) -> bool { // Space+F (⇧Space+F backwards) cycles the pasteboard colour, as in Photoshop: F while the // Hand key is held, before F's own Cycle Screen Mode. - if !matches!(focus, Focus::Text) && app.ui.text_edit.is_none() && crate::hold_keys::reposition_held(app, ctx) { + if !matches!(focus, crate::shortcut_dispatch::Focus::Text) && app.ui.text_edit.is_none() && crate::hold_keys::reposition_held(app, ctx) { let back = ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::F)); if back || ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F)) { if let Err(e) = crate::canvas_tool_menu::cycle_canvas_color(app, back) { app.ui.status = e; } - return; + return true; } } // Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus. let editing = crate::type_tool::handle_keys(app, ctx); // ⌥⇧⌘N: a new layer at once, without the New Layer dialog ⇧⌘N opens (#4794). if new_layer_without_dialog(app, ctx) { - return; + return true; } // Registry, UI and menu-catalogue shortcuts (see [`crate::shortcut_dispatch::bindings`]). - if dispatch_pressed(app, ctx, focus, editing) { - return; + if crate::shortcut_dispatch::dispatch_pressed(app, ctx, focus, editing) { + return true; } if editing { - return; + return true; } // Crop tool showing a box: O cycles its overlay, ⇧O the overlay's orientation (#1919). - if crate::crop_overlay::keys(app, ctx) { - return; - } - // ... and H toggles Show Cropped Area. - if crate::crop_shield::keys(app, ctx) { - return; - } - // ... and I fills W x H x Resolution from the document (Front Image, #2443). - if crate::crop_size::keys(app, ctx) { - return; + // ... and H toggles Show Cropped Area, and I fills W x H x Resolution from the document (#2443). + if crate::crop_overlay::keys(app, ctx) || crate::crop_shield::keys(app, ctx) || crate::crop_size::keys(app, ctx) { + return true; } // Single-key tools (no modifiers). D and X (`tools.defaultColors` / `tools.swapColors`) and the // brush keys [ ] ⇧[ ⇧] (`tools.decreaseBrushSize`…) are commands, dispatched above with any @@ -739,11 +767,11 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { if !app.remove_pending.is_empty() { if pressed(Key::Enter) { crate::retouch_ui::remove_pending_commit(app); - return; + return true; } if pressed(Key::Escape) { crate::retouch_ui::remove_pending_cancel(app); - return; + return true; } } // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop). @@ -751,11 +779,11 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { let mods = ctx.input(|i| i.modifiers); if ctx.input_mut(|i| i.consume_key(mods, Key::Escape)) { app.drag = None; - return; + return true; } if ctx.input_mut(|i| i.consume_key(mods, Key::Enter)) { crate::lasso_ui::commit(app); - return; + return true; } } // An open options bar popup (the Crop Ratio list, the overlay and gear menus) takes the keys @@ -768,7 +796,7 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } else { crate::canvas::commit_crop(app); } - return; + return true; } // In a full screen mode, the Crop tool's untouched default frame (Straighten off) has nothing to cancel: cancelling only // makes the next one, so Esc goes on to leave full screen (#7315). @@ -777,9 +805,16 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { app.ui.polygon.clear(); app.ui.polygon_mode.clear(); crate::crop_ui::cancel(app); - return; + return true; } } + false +} + +/// Esc (leave full screen, else deselect), the tool-letter keys, Page/Home/End scrolling and the +/// opacity keys. Runs last, so every state that owns Esc has already had its chance. +fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); // Esc with no active operation leaves a full screen mode, else deselects (#2674), like ⌘D. // The key is never taken from a state that handles Esc itself: menus, dialogs, text fields // and inline type returned above, transform, pen, lasso and crop consumed it, and these own @@ -822,6 +857,20 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // A held tool letter is a spring-loaded tool (#2672), not a burst of presses: its key // repeats are dropped rather than cycling the group. ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, repeat: true, .. } if crate::spring_tools::is_tool_key(*key)))); + if select_tool_by_key(app, ctx, &pressed) { + return; + } + // Page Up / Page Down (⌘ sideways, ⇧ a small step), Home and End scroll the canvas (#8057). + if crate::page_keys::handle(app, ctx) { + return; + } + // 1–0 set opacity, ⇧1–0 flow or fill (`opacity_keys`). + crate::opacity_keys::handle(app, ctx); +} + +/// Selects a tool from its letter key. Pressing the key of the current group cycles within it; with +/// the Shift-switch preference only ⇧+key cycles. Returns true when a tool key was handled. +fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &impl Fn(Key) -> bool) -> bool { let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch; for t in Tool::ALL { if !crate::tool_shortcuts::uses_default(app, t) { @@ -844,15 +893,10 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // Permanent key choices own the tool; held-key switches keep the pen marker. app.stylus.tool_before_eraser = None; } - return; + return true; } } - // Page Up / Page Down (⌘ sideways, ⇧ a small step), Home and End scroll the canvas (#8057). - if crate::page_keys::handle(app, ctx) { - return; - } - // 1–0 set opacity, ⇧1–0 flow or fill (`opacity_keys`). - crate::opacity_keys::handle(app, ctx); + false } #[cfg(test)] diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index f146390e06..db9e8aeac3 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -2,7 +2,7 @@ use super::invoke::invoke; use super::items::{ItemCache, MenuItem, menu_items}; use super::render::{alt_click, render_level, render_level_rows}; use super::search::help_search; -use super::*; +use super::{PhotocraftApp, TOP_MENUS, Value, json}; /// Draws the menu bar; returns the inner edge of the menu titles, facing the rest of the title bar /// (the right edge of the last title, or its left edge in a right-to-left UI, where File is at the diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7ae1d8dea4..a9119bd549 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{DOCUMENT_ITEM, DialogKind, PhotocraftApp, Value, json}; /// Photoshop's Window › ids for the panels the shell already has, as `window.toggle.*`. pub(crate) fn panel_alias(id: &str) -> Option<&'static str> { @@ -57,114 +57,117 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va } /// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. -pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { +fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if let Some(tool) = crate::tool_shortcuts::tool(id) { crate::tool_memory::select(app, tool); - return Ok(json!({"tool": tool})); + return Some(Ok(json!({"tool": tool}))); } if id == "help.checkForUpdates" { - return crate::updates_ui::check(app, ctx, params); + return Some(crate::updates_ui::check(app, ctx, params.clone())); } if id == "ui.symmetryTransform" { - return crate::symmetry_ui::begin(app).map(|_| Value::Null); + return Some(crate::symmetry_ui::begin(app).map(|_| Value::Null)); } - if let Some(r) = crate::tool_reset::invoke(app, id, ¶ms) { - return r; + if let Some(r) = crate::tool_reset::invoke(app, id, params) { + return Some(r); } // A filter on a type layer asks to rasterize it first (#4303). - if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, ¶ms) { - return r; + if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, params) { + return Some(r); } // A pending Pen anchor is gesture state; Edit › Undo must match the keyboard. if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) { - return Ok(Value::Null); + return Some(Ok(Value::Null)); } // Image › Crop while the Crop tool has a pending frame commits that frame (#1918). if id == "image.crop" && crate::crop_ui::pending(app) { crate::canvas::commit_crop(app); - return Ok(json!({"committed": true})); + return Some(Ok(json!({"committed": true}))); } - if let Some(result) = crate::panel_docking::command(app, id, ¶ms) { - return result; + if let Some(result) = crate::panel_docking::command(app, id, params) { + return Some(result); } // Help › Discord, website, GitHub, Report an Issue. if let Some(url) = crate::links::url_for(id) { - return Ok(crate::links::open(app, ctx, url)); + return Some(Ok(crate::links::open(app, ctx, url))); } if id == "view.proofSetup.custom" { - return Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")})); + return Some(Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")}))); } // Image › Analysis tools/dialogs, Measurement Log and Notes panels, File › Import › Notes. - if let Some(r) = crate::analysis_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::analysis_ui::menu(app, id, params) { + return Some(r); } // Workspace New/Delete/Lock, Modifier Keys, custom pixel aspect, Extras/32-bit options. - if let Some(r) = crate::workspace_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::workspace_ui::menu(app, id, params) { + return Some(r); } // Window › Gradients, Patterns, Styles, Shapes, Tool Presets, Clone Source. - if let Some(r) = crate::preset_panels::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::preset_panels::menu(app, id, params) { + return Some(r); } // Character/Paragraph Styles, Glyphs, Edit › Check Spelling dialog. - if let Some(r) = crate::type_panels_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::type_panels_ui::menu(app, id, params) { + return Some(r); } // Image > Variables (Define / Data Sets), Apply Data Set. - if let Some(r) = crate::variables_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::variables_ui::menu(app, id, params) { + return Some(r); } // Window > Timeline panel. - if let Some(r) = crate::timeline_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::timeline_ui::menu(app, id, params) { + return Some(r); } // Filter › Plug-ins (installed WebAssembly plug-ins, Install Plug-in…). - if let Some(r) = crate::plugin_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::plugin_ui::menu(app, id, params) { + return Some(r); } // History panel menu › History Options… (without params: its dialog). - if let Some(r) = crate::history_options_ui::menu(app, id, ¶ms) { - return r; + if let Some(r) = crate::history_options_ui::menu(app, id, params) { + return Some(r); } + None +} + +fn invoke_shell_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if id == "window.panel.brushSettings" { app.ui.brush_tab = 0; } // View/Window/Type shell items, and dialogs/pickers in front of File commands. // Edit › Preferences, Keyboard Shortcuts, Color Settings and other Edit dialogs. - if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, params) { + return Some(r); } // Save for Web's dialog would export the committed document, not the open Free Transform (#6737). if id == crate::transform_tool::SAVE_FOR_WEB && let Some(r) = crate::transform_tool::intercept(app, id) { - return r; + return Some(r); } // Save for Web, Print and the other File-menu dialogs added with slices. - if let Some(r) = crate::file_ui::invoke(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::file_ui::invoke(app, ctx, id, params) { + return Some(r); } - if let Some(r) = crate::view_cmds::invoke(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::view_cmds::invoke(app, ctx, id, params) { + return Some(r); } // Liquify dialog, Puppet Warp and Perspective Warp modes (and their control params). - if let Some(r) = crate::distort_ui::menu(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::distort_ui::menu(app, ctx, id, params) { + return Some(r); } // Camera Raw Filter dialog (and its control params). - if let Some(r) = crate::camera_raw_ui::menu(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::camera_raw_ui::menu(app, ctx, id, params) { + return Some(r); } - if let Some(r) = crate::wide_angle_ui::menu(app, ctx, id, ¶ms) { - return r; + if let Some(r) = crate::wide_angle_ui::menu(app, ctx, id, params) { + return Some(r); } if let Some(profile) = proof_preset(id) { // View › Proof Setup presets: set the proof profile and turn Proof Colors on. - app.run("view.proofSetup", json!({"profile": profile}))?; - return app.run("view.proofColors", json!({"on": true})); + return Some(app.run("view.proofSetup", json!({"profile": profile})).and_then(|_| app.run("view.proofColors", json!({"on": true})))); } if let Some(alias) = panel_alias(id) { - return invoke(app, ctx, alias, params); + return Some(invoke(app, ctx, alias, params.clone())); } if let Some(ws) = workspace_name(id) { // Reset re-applies the current workspace; Essentials is the default layout. @@ -174,12 +177,14 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: (name, _) => app.ui.workspace = name.into(), } apply_workspace(app); - return Ok(json!({"workspace": app.ui.workspace})); + return Some(Ok(json!({"workspace": app.ui.workspace}))); } - match id { - // ⌘↩ / Ctrl+Enter (#306): load the path selected in the Paths panel (or the one being - // drawn) as a selection. - "path.toSelection" if params.get("name").is_none() => crate::vector_ui::path_to_selection(app, params), + None +} + +fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Result, String> { + let result = match id { + "path.toSelection" if params.get("name").is_none() => crate::vector_ui::path_to_selection(app, params.clone()), // Layer › Rename Layer from a menu starts in-place renaming in the Layers panel. "layer.renameLayer" if params.get("name").is_none() => { let st = app.session.active().ok_or("no document")?; @@ -210,7 +215,7 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "file.save" => { // Writes back only to a layered file that holds the whole document; anything else // goes through Save As, so the original is never overwritten with less (#3806). - let choices = crate::FormatChoices::from_params(¶ms, id)?; + let choices = crate::FormatChoices::from_params(params, id)?; match params.get("path").and_then(Value::as_str) { Some(path) => app.save_as_with(Some(path.to_string()), choices), None => { @@ -268,9 +273,25 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } } "file.saveAs" => { - let choices = crate::FormatChoices::from_params(¶ms, id)?; + let choices = crate::FormatChoices::from_params(params, id)?; app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices) } + _ => return Ok(None), + }; + result.map(Some) +} + +pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if let Some(result) = invoke_early_commands(app, ctx, id, ¶ms) { + return result; + } + if let Some(result) = invoke_shell_commands(app, ctx, id, ¶ms) { + return result; + } + if let Some(result) = invoke_file_commands(app, ctx, id, ¶ms)? { + return Ok(result); + } + match id { "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), "window.newWindowForDocument" => { let doc = app.session.active_index().ok_or("no document")?; diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index e5b029136d..37944cca5f 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -1,6 +1,6 @@ use super::invoke::{panel_alias, proof_preset, workspace_name}; use super::state::{checked, is_enabled, reveal_label}; -use super::*; +use super::{DOCUMENT_ITEM, PhotocraftApp, UI_COMMANDS}; /// Menu tree entry for rendering and for `ui.inspect`. #[derive(Clone, Debug, serde::Serialize)] diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 754f14d8ce..7baa0b9bf6 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -1,6 +1,6 @@ use super::invoke::{panel_alias, proof_preset, workspace_name}; use super::items::MenuItem; -use super::*; +use super::{DOCUMENT_ITEM, PhotocraftApp, Value}; pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { if crate::tool_shortcuts::tool(id).is_some() { diff --git a/crates/ui-egui/src/menus/view_cmds/arrange.rs b/crates/ui-egui/src/menus/view_cmds/arrange.rs index 209d743252..0759cf4b56 100644 --- a/crates/ui-egui/src/menus/view_cmds/arrange.rs +++ b/crates/ui-egui/src/menus/view_cmds/arrange.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{LAYOUTS, PhotocraftApp, Value, json}; /// View › Fit Layer(s) on Screen: zoom and centre on the selected layers' bounds. pub(super) fn fit_layers(app: &mut PhotocraftApp) -> Result { diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index dd280efed0..f4bcd87542 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1,5 +1,5 @@ use super::dispatch::no_params; -use super::*; +use super::{DialogKind, Map, PhotocraftApp, Value, json}; // ---------- dialogs and pickers in front of engine commands ---------- diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index 6667f83283..4a9884c6c0 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -1,7 +1,7 @@ use super::arrange::{arrange, fit_layers}; use super::dialogs::front; use super::options::{panel_state, panel_tab, pixel_aspect_ratio, screen_mode_commands, show_slot, snap_slot, was_maximized_id}; -use super::*; +use super::{FONT_PREVIEW, LANGUAGE, LAYOUTS, PIXEL_ASPECTS, PhotocraftApp, SCREEN_MODES, Show, SnapTo, Value, json}; /// Ids handled here (live menu items). pub fn handles(id: &str) -> bool { diff --git a/crates/ui-egui/src/menus/view_cmds/options.rs b/crates/ui-egui/src/menus/view_cmds/options.rs index 07aefac75b..8f0c9df909 100644 --- a/crates/ui-egui/src/menus/view_cmds/options.rs +++ b/crates/ui-egui/src/menus/view_cmds/options.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Map, PhotocraftApp, Show, SnapTo, Value, ViewOptions}; /// Whether the window was maximized when a screen mode took it full screen (egui temp data). pub(super) fn was_maximized_id() -> egui::Id { diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index a4a5969544..d22098e24d 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -10,6 +10,7 @@ use serde_json::{Value, json}; use photocraft_engine::actions_cmds::{self, Action}; +use crate::icons; use crate::PhotocraftApp; use crate::theme::Tokens; @@ -821,6 +822,86 @@ fn display_order(rows: &[Row]) -> Vec { order } +struct SetHeaderResult { + toggled: bool, + save: bool, +} + +fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, tokens: &Tokens) -> SetHeaderResult { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, !collapsed, set)); + if response.hovered() { + ui.painter().rect_filled(rect, 0.0, tokens.hover.gamma_multiply(0.5)); + } + let triangle = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0)); + let points = if collapsed { + vec![triangle.left_top(), triangle.right_center(), triangle.left_bottom()] + } else { + vec![triangle.left_top(), triangle.right_top(), triangle.center_bottom()] + }; + ui.painter().add(egui::Shape::convex_polygon(points, tokens.text_dim, Stroke::NONE)); + icons::paint( + ui, + Rect::from_center_size(pos2(rect.left() + 30.0, rect.center().y), vec2(16.0, 16.0)), + if collapsed { "folder" } else { "folder-open" }, + 12.0, + tokens.icon, + ); + ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, set, egui::FontId::proportional(12.0), tokens.text); + let summary = crate::i18n::trn(crate::i18n::current(), count, "{n} action", "{n} actions"); + ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, summary, egui::FontId::proportional(11.0), tokens.text_faint); + let toggled = response.clicked(); + let mut save = false; + response.context_menu(|ui| { + if ui.button(tl!("Save Set…")).clicked() { + save = true; + ui.close(); + } + }); + SetHeaderResult { toggled, save } +} + +fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str) { + egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.label(tl!("Keyboard Shortcuts")); + let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default(); + let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(¤t).unwrap_or((0, false, false)); + for number in std::iter::once(0).chain(1..=12) { + let label = if number == 0 { tl!("None").to_string() } else { format!("F{number}") }; + if ui.selectable_label(key == number, label).clicked() { + let chosen = if number == 0 { String::new() } else { photocraft_engine::atn_cmds::function_key_name(number, shift, command) }; + let _ = assign_shortcut(app, name, &chosen); + ui.close(); + } + } + ui.add_enabled_ui(key > 0, |ui| { + let command_label = if cfg!(target_os = "macos") { tl!("Command") } else { tl!("Ctrl") }; + let toggled = ui.checkbox(&mut shift, tl!("Shift")).changed() | ui.checkbox(&mut command, command_label).changed(); + if toggled { + let _ = assign_shortcut(app, name, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); + } + }); + ui.separator(); + ui.menu_button(tl!("Color"), |ui| { + for (id, label) in [ + ("", tl!("None")), + ("red", tl!("Red")), + ("orange", tl!("Orange")), + ("yellow", tl!("Yellow")), + ("green", tl!("Green")), + ("blue", tl!("Blue")), + ("violet", tl!("Violet")), + ("gray", tl!("Gray")), + ] { + if ui.selectable_label(swatch == id, label).clicked() { + let _ = app.run("actions.setColor", json!({"action": index, "color": id})); + ui.close(); + } + } + }); + }); +} + pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let recording = app.session.actions.recording; @@ -900,38 +981,14 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { { shown_set = Some(set); let collapsed = app.ui.actions.collapsed_sets.iter().any(|c| c == set); - let (hr, hresp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); - hresp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, !collapsed, set)); - if hresp.hovered() { - ui.painter().rect_filled(hr, 0.0, t.hover.gamma_multiply(0.5)); - } - let tri = Rect::from_center_size(pos2(hr.left() + 12.0, hr.center().y), vec2(8.0, 8.0)); - let pts = if collapsed { - vec![tri.left_top(), tri.right_center(), tri.left_bottom()] - } else { - vec![tri.left_top(), tri.right_top(), tri.center_bottom()] - }; - ui.painter().add(egui::Shape::convex_polygon(pts, t.text_dim, Stroke::NONE)); - crate::icons::paint( - ui, - Rect::from_center_size(pos2(hr.left() + 30.0, hr.center().y), vec2(16.0, 16.0)), - if collapsed { "folder" } else { "folder-open" }, - 12.0, - t.icon, - ); - ui.painter().text(pos2(hr.left() + 44.0, hr.center().y), Align2::LEFT_CENTER, set, egui::FontId::proportional(12.0), t.text); let count = rows.iter().filter(|r| r.set.as_deref() == Some(set)).count() as u64; - let summary = crate::i18n::trn(crate::i18n::current(), count, "{n} action", "{n} actions"); - ui.painter().text(pos2(hr.right() - 8.0, hr.center().y), Align2::RIGHT_CENTER, summary, egui::FontId::proportional(11.0), t.text_faint); - if hresp.clicked() { + let result = draw_set_header(ui, set, count, collapsed, &t); + if result.toggled { set_toggled = Some(set.to_string()); } - hresp.context_menu(|ui| { - if ui.button(tl!("Save Set…")).clicked() { - save_set = Some(set.to_string()); - ui.close(); - } - }); + if result.save { + save_set = Some(set.to_string()); + } } if set.as_deref().is_some_and(|set| app.ui.actions.collapsed_sets.iter().any(|c| c == set)) { continue; @@ -1012,45 +1069,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } // Clicks inside stay open, so Shift and Command can both be ticked; every item that // finishes closes the menu itself. - egui::Popup::context_menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.label(tl!("Keyboard Shortcuts")); - let current = app.session.prefs().shortcuts.get(&shortcut_id(name)).cloned().unwrap_or_default(); - // Photoshop's Action Options: a function key, with Shift and Command (#7646). - let (key, mut shift, mut command) = photocraft_engine::atn_cmds::parse_function_key(¤t).unwrap_or((0, false, false)); - for n in std::iter::once(0).chain(1..=12) { - let label = if n == 0 { tl!("None").to_string() } else { format!("F{n}") }; - if ui.selectable_label(key == n, label).clicked() { - let chosen = if n == 0 { String::new() } else { photocraft_engine::atn_cmds::function_key_name(n, shift, command) }; - let _ = assign_shortcut(app, name, &chosen); - ui.close(); - } - } - ui.add_enabled_ui(key > 0, |ui| { - let command_label = if cfg!(target_os = "macos") { tl!("Command") } else { tl!("Ctrl") }; - let toggled = ui.checkbox(&mut shift, tl!("Shift")).changed() | ui.checkbox(&mut command, command_label).changed(); - if toggled { - let _ = assign_shortcut(app, name, &photocraft_engine::atn_cmds::function_key_name(key, shift, command)); - } - }); - ui.separator(); - ui.menu_button(tl!("Color"), |ui| { - for (id, label) in [ - ("", tl!("None")), - ("red", tl!("Red")), - ("orange", tl!("Orange")), - ("yellow", tl!("Yellow")), - ("green", tl!("Green")), - ("blue", tl!("Blue")), - ("violet", tl!("Violet")), - ("gray", tl!("Gray")), - ] { - if ui.selectable_label(swatch == id, label).clicked() { - let _ = app.run("actions.setColor", json!({"action": i, "color": id})); - ui.close(); - } - } - }); - }); + action_context_menu(app, &resp, i, name, swatch); if resp.double_clicked() && !button_mode { // Photoshop renames in place when the name itself is double-clicked. if resp.interact_pointer_pos().is_some_and(|p| name_rect.expand2(vec2(4.0, 13.0)).contains(p)) { diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index eb5bcc7374..d6a96112a7 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, vec2, widgets}; /// Photoshop's brush preset picker chip: a soft/hard round tip preview with the size underneath. /// Draw a round brush tip preview (hard core fading to a soft edge). diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 273893ae5a..90cfa9d8e6 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, PhotocraftApp, Rect, RichText, Sense, Stroke, StrokeKind, Tokens, c32, pos2, theme, vec2, widgets}; /// The Color panel's foreground and background chips. A click picks the colour the field edits, /// framed; a double-click opens the Color Picker on it. diff --git a/crates/ui-egui/src/panels/dock.rs b/crates/ui-egui/src/panels/dock.rs index 99f2afc7a8..4bc72ab57b 100644 --- a/crates/ui-egui/src/panels/dock.rs +++ b/crates/ui-egui/src/panels/dock.rs @@ -3,7 +3,7 @@ use super::info::info_panel; use super::layers::{channels, layers}; use super::navigator::navigator; use super::properties::{adjustments_grid, properties_body}; -use super::*; +use super::{PhotocraftApp, Stroke, Tokens, icons, pos2}; // ----------------------------------------------------------------------------- dock diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 7af5b3e3c1..939ef07e6b 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -1,5 +1,5 @@ use super::layer_drag::dropped_on; -use super::*; +use super::{Align2, Color32, HistorySource, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, Tool, Value, empty, icons, json, pos2, vec2, widgets}; pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 41a16d9f97..56a60e82d0 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, RichText, Tokens, Value, empty, json, theme, widgets}; /// The active document's pixel under the pointer, if the pointer is over the image. pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> { diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs index fd9a5d9b47..f778ccec75 100644 --- a/crates/ui-egui/src/panels/layer_drag.rs +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -1,5 +1,5 @@ use super::layers::footer_label; -use super::*; +use super::{Layer, LayerId, MaskKind, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Value, icons, json, pos2, vec2}; /// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them. /// diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index 959ca07da8..ba4720ae33 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -1,6 +1,8 @@ use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, start_fx_drag, starts_mask_drag}; use super::layers::simple_lock_toggle; -use super::*; +use super::{ + Color32, CornerRadius, Layer, LayerContent, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Value, icons, json, pos2, theme, vec2, widgets, +}; /// How a Layers panel row is selected: in the (multi-)selection, the primary/active layer, and /// whether several layers are selected. diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 1d548ce270..fe0f8c9577 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -4,7 +4,7 @@ use super::layer_drag::{ }; use super::layer_row::{RowSel, layer_row}; use super::options_bar::{LAYER_PCT_W, body_text_width, pct_action, scrub_pct_label}; -use super::*; +use super::{BlendMode, Layer, LayerId, MaskKind, PhotocraftApp, Rect, Sense, Tokens, Value, empty, icons, json, label, pos2, theme, vec2, widgets}; // ----------------------------------------------------------------------------- layers diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index a6bfbf00c8..b588288c47 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, empty, icons, pos2, vec2, widgets}; pub(super) fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index e24c3b4e6b..2ee6356919 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1,6 +1,7 @@ use super::brush_controls::{brush_preset_chip, mixer_load_swatch, paint_mode_dropdown, smoothing_field, smoothing_options, tool_mode_dropdown}; use super::properties::{select_and_mask_button, selection_mode_buttons}; -use super::*; +use photocraft_paint::BrushSettings; +use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, vec2, widgets}; // Custom controls also need to bring keyboard focus into a scroll viewport. pub(super) fn reveal_focused_control(ui: &egui::Ui) { @@ -130,511 +131,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let brush_before = app.session.tools.brush.clone(); let mut brush = brush_before.clone(); let b = &mut brush; - match app.ui.tool { - Tool::Brush | Tool::Eraser if t.pro => { - // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). - let block = crate::eraser_ui::block_mode(app, app.ui.tool); - ui.add_enabled_ui(!block, |ui| { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - }); - widgets::vline(ui, 22.0); - // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662). - if app.ui.tool == Tool::Eraser { - crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); - } else { - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); - } - ui.add_enabled_ui(!block, |ui| { - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { - b.pressure_opacity = !b.pressure_opacity; - } - }); - // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop). - ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| { - percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); - let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); - if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { - b.build_up = !b.build_up; - } - }); - opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, 58.0); - smoothing_options(ui, b); - widgets::vline(ui, 22.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() { - b.pressure_size = !b.pressure_size; - } - } - // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard). - Tool::Pencil => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - if !t.pro { - opt_label(ui, tl!("Size")); - widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); - widgets::vline(ui, 22.0); - } - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 }); - opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 }); - widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase")); - } - Tool::Brush | Tool::Eraser => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). - let block = crate::eraser_ui::block_mode(app, app.ui.tool); - ui.add_enabled_ui(!block, |ui| { - opt_label(ui, tl!("Size")); - widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); - }); - widgets::vline(ui, 22.0); - if app.ui.tool == Tool::Eraser { - crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); - } else { - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); - } - // A Pencil-mode Eraser is always hard and at full flow (Photoshop). - let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); - ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); - opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, 66.0); - widgets::vline(ui, 22.0); - widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")); - widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")); - } - Tool::MixerBrush => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - mixer_load_swatch(app, ui); - let m = &mut b.mixer; - for (icon, on, tip) in [ - ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")), - ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")), - ] { - if icons::button(ui, icon, 24.0, *on, tip).clicked() { - *on = !*on; - } - } - widgets::vline(ui, 22.0); - for (label, value) in [ - (tl!("Wet"), &mut b.mixer.wet), - (tl!("Load"), &mut b.mixer.load), - (tl!("Mix"), &mut b.mixer.mix), - (tl!("Flow"), &mut b.mixer.flow), - ] { - percent_field(ui, label, value, 0.0..=100.0, 62.0); - } - widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); - } - Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { - ui.spacing_mut().item_spacing.x = 2.0; - for (i, (icon, tip)) in [ - ("square", tl!("New selection").to_string()), - ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), - ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), - ( - "squares-subtract", - crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), - ), - ] - .iter() - .enumerate() - { - if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { - app.ui.selection_mode = i as u8; - } - } - ui.spacing_mut().item_spacing.x = 8.0; - widgets::vline(ui, 22.0); - let (units, size) = fixed_size_units(app); - let o = &mut app.ui.tool_options; - opt_label(ui, tl!("Feather")); - widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0); - // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard). - ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias"))); - widgets::vline(ui, 22.0); - // A single row or column has no style or size: Photoshop greys them. - let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee); - ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style"))); - let styles = [ - ("normal".to_string(), tl!("Normal")), - ("fixedRatio".to_string(), tl!("Fixed Ratio")), - ("fixedSize".to_string(), tl!("Fixed Size")), - ]; - if ui - .add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", tl!("Style"), &mut o.marquee_style, &styles, 96.0)) - .inner - { - (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) }; - } - let fixed = sized && o.marquee_style != "normal"; - let fixed_size = o.marquee_style == "fixedSize"; - // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910). - let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units }; - ui.add_enabled_ui(fixed, |ui| { - let mut picked = None; - opt_label(ui, tl!("Width")); - if fixed_size { - picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]); - } else { - widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); - } - if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() { - std::mem::swap(&mut o.marquee_width, &mut o.marquee_height); - } - opt_label(ui, tl!("Height")); - if fixed_size { - picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked); - } else { - widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); - } - if let Some(name) = picked { - o.marquee_unit = name.into(); - } - }); - widgets::vline(ui, 22.0); - select_and_mask_button(app, ui); - } - Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => { - selection_mode_buttons(app, ui); - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Feather")); - widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::vline(ui, 22.0); - if app.ui.tool == Tool::MagneticLasso { - let o = &mut app.ui.tool_options; - opt_label(ui, tl!("Width")); - widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0) - .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)")); - opt_label(ui, tl!("Contrast")); - widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0) - .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings")); - opt_label(ui, tl!("Frequency")); - widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0) - .on_hover_text(tl!("How often fastening points are placed by themselves")); - if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() { - o.magnetic_pressure = !o.magnetic_pressure; - } - widgets::vline(ui, 22.0); - } - select_and_mask_button(app, ui); - if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) { - hint( - ui, - &crate::i18n::fmt( - tl!("Click the first point or press {key} to close · Esc cancels"), - &[("key", &crate::shortcuts::pretty("Enter"))], - ), - ); - } else if app.ui.tool == Tool::Lasso { - hint(ui, tl!("Hold Alt while drawing for straight segments")); - } - if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() { - hint( - ui, - &crate::i18n::fmt( - tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"), - &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))], - ), - ); - } - } - Tool::MagicWand => { - selection_mode_buttons(app, ui); - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Tolerance")); - widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers")); - widgets::vline(ui, 22.0); - if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { - let r = app.run("select.subject", json!({})); - crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso")); - } - select_and_mask_button(app, ui); - } - Tool::PaintBucket => { - opt_label(ui, tl!("Fill")); - let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern); - if widgets::dropdown(ui, "bucket-src", tl!("Source"), &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) { - app.ui.tool_options.bucket_fill_pattern = src == 1; - } - opt_label(ui, tl!("Mode")); - if let Some(modes) = crate::blend_keys::tool_modes(tool) { - let o = &mut app.ui.tool_options; - let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; - if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { - o.bucket_clear = m.is_none(); - if let Some(m) = m { - o.bucket_blend_mode = m; - } - } - } - opt_label(ui, tl!("Opacity")); - widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); - opt_label(ui, tl!("Tolerance")); - widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers")); - } - Tool::Gradient => { - // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels). - let mut classic = app.ui.tool_options.gradient_classic; - if widgets::dropdown(ui, "gradient-mode", tl!("Mode"), &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) - { - app.ui.tool_options.gradient_classic = classic; - } - // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels): - // both paint with the same engine-owned preset (#1651), and either swatch - // click opens the Gradient Editor window, as in Photoshop. - if crate::gradient_ui::preset_swatch(app, ui) { - app.ui.panels.gradient_editor = true; - } - widgets::vline(ui, 22.0); - ui.spacing_mut().item_spacing.x = 2.0; - let before = app.ui.tool_options.clone(); - for (style, icon, tip) in [ - ("linear", "gradient", tl!("Linear Gradient")), - ("radial", "circle", tl!("Radial Gradient")), - ("angle", "rotate-cw", tl!("Angle Gradient")), - ("reflected", "arrow-left-right", tl!("Reflected Gradient")), - ("diamond", "diamond", tl!("Diamond Gradient")), - ] { - if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() { - app.ui.tool_options.gradient_style = style.into(); - } - } - ui.spacing_mut().item_spacing.x = 8.0; - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Mode")); - let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); - // The wheel over it steps the mode, as over the Layers panel's (#2061). - widgets::dropdown_wheel_hovered( - ui, - "gradient-blend-mode", - tl!("Blend Mode"), - &mut app.ui.tool_options.gradient_blend_mode, - &opts, - 96.0, - ); - opt_label(ui, tl!("Opacity")); - let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); - // Live while scrubbed, one undo step per scrub (#5012). - let drag_key = r.id.with("gradient-opacity-drag"); - if r.drag_started() { - let n = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(drag_key, n)); - } - if r.changed() { - let drag = if r.dragged() { ui.data(|d| d.get_temp::(drag_key)) } else { None }; - crate::gradient_ui::opacity_changed(app, drag); - } - widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse")); - widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither")); - // Live mode: the options also change a selected gradient fill layer. - crate::gradient_ui::options_changed(app, &before); - } - Tool::PerspectiveCrop => crate::perspective_crop_ui::options_bar(app, ui), - Tool::Crop => { - let before_ratio = crate::crop_ui::preset_ratio(app); - let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height))); - // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919). - crate::crop_presets::dropdown(app, ui); - let o = &mut app.ui.tool_options; - let mut ratio_base = None; - if o.crop_ratio == crate::crop_size::WHR { - crate::crop_size::fields(o, ui); - } else { - // Keep partial edits in ToolOptions so the first side survives a frame; - // Original Ratio shows the document's numbers, as Photoshop does. - let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); - let decimals = crate::crop_size::RATIO_DECIMALS; - let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals); - let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); - let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals); - let (cw, ch) = (fw.changed(), fh.changed()); - if swap { - std::mem::swap(&mut rw, &mut rh); - } - if cw || ch || swap { - crate::crop_size::set_custom_ratio_fields(o, rw, rh); - } - // Every ratio typed or scrubbed in one edit fits from the frame the edit - // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752). - let base_id = egui::Id::unique("crop-ratio-edit-base"); - if cw || ch { - ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect); - } - if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) { - ui.data_mut(|d| d.remove::<[f64; 4]>(base_id)); - } else if let Some(base) = ratio_base { - ui.data_mut(|d| d.insert_temp(base_id, base)); - } - } - widgets::vline(ui, 22.0); - if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { - crate::crop_size::clear_ratio(o); - } - crate::crop_straighten::options_button(&mut app.crop.straighten, ui); - crate::crop_overlay::options_button(o, ui); - let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui); - widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels")); - // Fill: what a turned or extending crop puts where the image doesn't reach - // (#3823). Generative Expand is not offered. - ui.label(tl!("Fill:")); - widgets::dropdown( - ui, - "crop-fill", - tl!("Fill:"), - &mut o.crop_content_aware, - &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))], - 150.0, - ); - if crate::crop_ui::preset_ratio(app) != before_ratio { - match ratio_base { - Some(base) => crate::crop_ui::apply_ratio_from(app, base), - None => crate::crop_ui::apply_ratio(app), - } - } - if pick_shield_color { - crate::crop_shield::pick_custom_color(app); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icons::button( - ui, - "check", - 26.0, - false, - &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]), - ) - .clicked() - { - crate::canvas::commit_crop(app); - } - if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() { - crate::crop_ui::cancel(app); - } - }); - } - // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275). - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui), - Tool::Move => { - let o = &mut app.ui.tool_options; - widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:")); - widgets::dropdown( - ui, - "move-target", - tl!("Auto-Select:"), - &mut o.move_target, - &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))], - 76.0, - ); - widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls")); - widgets::vline(ui, 22.0); - crate::align_bar::options(app, ui); - } - Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), - Tool::Zoom => { - // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in - // Photoshop: one setting, shown in both places (zoom_window_fit.rs). - let mut fit = app.session.prefs().general.zoom_resizes_windows; - if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).changed() { - app.session.prefs.edit(|p| p.general.zoom_resizes_windows = fit); - } - widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom")); - hint( - ui, - &crate::i18n::fmt( - tl!("Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out"), - &[("key", &crate::shortcuts::pretty("Alt"))], - ), - ); - if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].fit_pending = true; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - } - if widgets::secondary_button(ui, "100%", 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].zoom = 1.0; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - } - Tool::RotateView => { - hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); - if let Some(i) = app.session.active_index() { - ui.label(tl!("Angle")); - let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); - if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed() - && let Some(v) = app.ui.views.get_mut(i) - { - v.rotation = crate::rotate_view::wrap_deg(angle); - } - if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked() - && let Some(v) = app.ui.views.get_mut(i) - { - v.rotation = 0.0; - } - } - } - Tool::Hand => { - hint(ui, tl!("Drag to pan · hold Space with any tool")); - if widgets::secondary_button(ui, "100%", 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].zoom = 1.0; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].fit_pending = true; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fill_pending = false; - } - if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].fill_pending = true; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; - } - } - // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`. - _ => {} - } + tool_specific_options(app, ui, t, tool, b); // Painting symmetry is independent of visual theme. Keep the options-bar // action available for Brush, Pencil and Eraser in every palette (#2659). if matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser) { @@ -648,6 +145,515 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } +/// The per-tool options of the bar: the brush, mixer, marquee, pencil and view controls. +fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, tool: Tool, b: &mut BrushSettings) { +match app.ui.tool { + Tool::Brush | Tool::Eraser if t.pro => { + // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). + let block = crate::eraser_ui::block_mode(app, app.ui.tool); + ui.add_enabled_ui(!block, |ui| { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + }); + widgets::vline(ui, 22.0); + // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662). + if app.ui.tool == Tool::Eraser { + crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); + } else { + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + } + ui.add_enabled_ui(!block, |ui| { + percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); + if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { + b.pressure_opacity = !b.pressure_opacity; + } + }); + // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop). + ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| { + percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); + let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); + if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { + b.build_up = !b.build_up; + } + }); + opt_label(ui, tl!("Smoothing")); + smoothing_field(ui, b, 58.0); + smoothing_options(ui, b); + widgets::vline(ui, 22.0); + if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() { + b.pressure_size = !b.pressure_size; + } + } + // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard). + Tool::Pencil => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + if !t.pro { + opt_label(ui, tl!("Size")); + widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); + widgets::vline(ui, 22.0); + } + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); + percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 }); + opt_label(ui, tl!("Smoothing")); + smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 }); + widgets::vline(ui, 22.0); + widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase")); + } + Tool::Brush | Tool::Eraser => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). + let block = crate::eraser_ui::block_mode(app, app.ui.tool); + ui.add_enabled_ui(!block, |ui| { + opt_label(ui, tl!("Size")); + widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); + }); + widgets::vline(ui, 22.0); + if app.ui.tool == Tool::Eraser { + crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); + } else { + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + } + // A Pencil-mode Eraser is always hard and at full flow (Photoshop). + let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); + ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); + ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); + ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); + opt_label(ui, tl!("Smoothing")); + smoothing_field(ui, b, 66.0); + widgets::vline(ui, 22.0); + widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")); + widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")); + } + Tool::MixerBrush => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + mixer_load_swatch(app, ui); + let m = &mut b.mixer; + for (icon, on, tip) in [ + ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")), + ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")), + ] { + if icons::button(ui, icon, 24.0, *on, tip).clicked() { + *on = !*on; + } + } + widgets::vline(ui, 22.0); + for (label, value) in [ + (tl!("Wet"), &mut b.mixer.wet), + (tl!("Load"), &mut b.mixer.load), + (tl!("Mix"), &mut b.mixer.mix), + (tl!("Flow"), &mut b.mixer.flow), + ] { + percent_field(ui, label, value, 0.0..=100.0, 62.0); + } + widgets::vline(ui, 22.0); + widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); + } + Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + ui.spacing_mut().item_spacing.x = 2.0; + for (i, (icon, tip)) in [ + ("square", tl!("New selection").to_string()), + ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), + ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), + ( + "squares-subtract", + crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), + ), + ] + .iter() + .enumerate() + { + if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { + app.ui.selection_mode = i as u8; + } + } + ui.spacing_mut().item_spacing.x = 8.0; + widgets::vline(ui, 22.0); + let (units, size) = fixed_size_units(app); + let o = &mut app.ui.tool_options; + opt_label(ui, tl!("Feather")); + widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0); + // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard). + ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias"))); + widgets::vline(ui, 22.0); + // A single row or column has no style or size: Photoshop greys them. + let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee); + ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style"))); + let styles = [ + ("normal".to_string(), tl!("Normal")), + ("fixedRatio".to_string(), tl!("Fixed Ratio")), + ("fixedSize".to_string(), tl!("Fixed Size")), + ]; + if ui + .add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", tl!("Style"), &mut o.marquee_style, &styles, 96.0)) + .inner + { + (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) }; + } + let fixed = sized && o.marquee_style != "normal"; + let fixed_size = o.marquee_style == "fixedSize"; + // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910). + let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units }; + ui.add_enabled_ui(fixed, |ui| { + let mut picked = None; + opt_label(ui, tl!("Width")); + if fixed_size { + picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]); + } else { + widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); + } + if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() { + std::mem::swap(&mut o.marquee_width, &mut o.marquee_height); + } + opt_label(ui, tl!("Height")); + if fixed_size { + picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked); + } else { + widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); + } + if let Some(name) = picked { + o.marquee_unit = name.into(); + } + }); + widgets::vline(ui, 22.0); + select_and_mask_button(app, ui); + } + Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => { + selection_mode_buttons(app, ui); + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Feather")); + widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::vline(ui, 22.0); + if app.ui.tool == Tool::MagneticLasso { + let o = &mut app.ui.tool_options; + opt_label(ui, tl!("Width")); + widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0) + .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)")); + opt_label(ui, tl!("Contrast")); + widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0) + .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings")); + opt_label(ui, tl!("Frequency")); + widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0) + .on_hover_text(tl!("How often fastening points are placed by themselves")); + if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() { + o.magnetic_pressure = !o.magnetic_pressure; + } + widgets::vline(ui, 22.0); + } + select_and_mask_button(app, ui); + if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) { + hint( + ui, + &crate::i18n::fmt( + tl!("Click the first point or press {key} to close · Esc cancels"), + &[("key", &crate::shortcuts::pretty("Enter"))], + ), + ); + } else if app.ui.tool == Tool::Lasso { + hint(ui, tl!("Hold Alt while drawing for straight segments")); + } + if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() { + hint( + ui, + &crate::i18n::fmt( + tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"), + &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))], + ), + ); + } + } + Tool::MagicWand => { + selection_mode_buttons(app, ui); + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Tolerance")); + widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers")); + widgets::vline(ui, 22.0); + if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { + let r = app.run("select.subject", json!({})); + crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso")); + } + select_and_mask_button(app, ui); + } + Tool::PaintBucket => { + opt_label(ui, tl!("Fill")); + let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern); + if widgets::dropdown(ui, "bucket-src", tl!("Source"), &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) { + app.ui.tool_options.bucket_fill_pattern = src == 1; + } + opt_label(ui, tl!("Mode")); + if let Some(modes) = crate::blend_keys::tool_modes(tool) { + let o = &mut app.ui.tool_options; + let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; + if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { + o.bucket_clear = m.is_none(); + if let Some(m) = m { + o.bucket_blend_mode = m; + } + } + } + opt_label(ui, tl!("Opacity")); + widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + opt_label(ui, tl!("Tolerance")); + widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers")); + } + Tool::Gradient => { + // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels). + let mut classic = app.ui.tool_options.gradient_classic; + if widgets::dropdown(ui, "gradient-mode", tl!("Mode"), &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) + { + app.ui.tool_options.gradient_classic = classic; + } + // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels): + // both paint with the same engine-owned preset (#1651), and either swatch + // click opens the Gradient Editor window, as in Photoshop. + if crate::gradient_ui::preset_swatch(app, ui) { + app.ui.panels.gradient_editor = true; + } + widgets::vline(ui, 22.0); + ui.spacing_mut().item_spacing.x = 2.0; + let before = app.ui.tool_options.clone(); + for (style, icon, tip) in [ + ("linear", "gradient", tl!("Linear Gradient")), + ("radial", "circle", tl!("Radial Gradient")), + ("angle", "rotate-cw", tl!("Angle Gradient")), + ("reflected", "arrow-left-right", tl!("Reflected Gradient")), + ("diamond", "diamond", tl!("Diamond Gradient")), + ] { + if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() { + app.ui.tool_options.gradient_style = style.into(); + } + } + ui.spacing_mut().item_spacing.x = 8.0; + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Mode")); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + // The wheel over it steps the mode, as over the Layers panel's (#2061). + widgets::dropdown_wheel_hovered( + ui, + "gradient-blend-mode", + tl!("Blend Mode"), + &mut app.ui.tool_options.gradient_blend_mode, + &opts, + 96.0, + ); + opt_label(ui, tl!("Opacity")); + let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + // Live while scrubbed, one undo step per scrub (#5012). + let drag_key = r.id.with("gradient-opacity-drag"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(drag_key, n)); + } + if r.changed() { + let drag = if r.dragged() { ui.data(|d| d.get_temp::(drag_key)) } else { None }; + crate::gradient_ui::opacity_changed(app, drag); + } + widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse")); + widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither")); + // Live mode: the options also change a selected gradient fill layer. + crate::gradient_ui::options_changed(app, &before); + } + Tool::PerspectiveCrop => crate::perspective_crop_ui::options_bar(app, ui), + Tool::Crop => { + let before_ratio = crate::crop_ui::preset_ratio(app); + let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height))); + // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919). + crate::crop_presets::dropdown(app, ui); + let o = &mut app.ui.tool_options; + let mut ratio_base = None; + if o.crop_ratio == crate::crop_size::WHR { + crate::crop_size::fields(o, ui); + } else { + // Keep partial edits in ToolOptions so the first side survives a frame; + // Original Ratio shows the document's numbers, as Photoshop does. + let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); + let decimals = crate::crop_size::RATIO_DECIMALS; + let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals); + let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); + let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals); + let (cw, ch) = (fw.changed(), fh.changed()); + if swap { + std::mem::swap(&mut rw, &mut rh); + } + if cw || ch || swap { + crate::crop_size::set_custom_ratio_fields(o, rw, rh); + } + // Every ratio typed or scrubbed in one edit fits from the frame the edit + // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752). + let base_id = egui::Id::unique("crop-ratio-edit-base"); + if cw || ch { + ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect); + } + if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) { + ui.data_mut(|d| d.remove::<[f64; 4]>(base_id)); + } else if let Some(base) = ratio_base { + ui.data_mut(|d| d.insert_temp(base_id, base)); + } + } + widgets::vline(ui, 22.0); + if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { + crate::crop_size::clear_ratio(o); + } + crate::crop_straighten::options_button(&mut app.crop.straighten, ui); + crate::crop_overlay::options_button(o, ui); + let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui); + widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels")); + // Fill: what a turned or extending crop puts where the image doesn't reach + // (#3823). Generative Expand is not offered. + ui.label(tl!("Fill:")); + widgets::dropdown( + ui, + "crop-fill", + tl!("Fill:"), + &mut o.crop_content_aware, + &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))], + 150.0, + ); + if crate::crop_ui::preset_ratio(app) != before_ratio { + match ratio_base { + Some(base) => crate::crop_ui::apply_ratio_from(app, base), + None => crate::crop_ui::apply_ratio(app), + } + } + if pick_shield_color { + crate::crop_shield::pick_custom_color(app); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icons::button( + ui, + "check", + 26.0, + false, + &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]), + ) + .clicked() + { + crate::canvas::commit_crop(app); + } + if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() { + crate::crop_ui::cancel(app); + } + }); + } + // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275). + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui), + Tool::Move => { + let o = &mut app.ui.tool_options; + widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:")); + widgets::dropdown( + ui, + "move-target", + tl!("Auto-Select:"), + &mut o.move_target, + &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))], + 76.0, + ); + widgets::vline(ui, 22.0); + widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls")); + widgets::vline(ui, 22.0); + crate::align_bar::options(app, ui); + } + Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), + Tool::Zoom => { + // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in + // Photoshop: one setting, shown in both places (zoom_window_fit.rs). + let mut fit = app.session.prefs().general.zoom_resizes_windows; + if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).changed() { + app.session.prefs.edit(|p| p.general.zoom_resizes_windows = fit); + } + widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom")); + hint( + ui, + &crate::i18n::fmt( + tl!("Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out"), + &[("key", &crate::shortcuts::pretty("Alt"))], + ), + ); + if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fit_pending = true; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + } + if widgets::secondary_button(ui, "100%", 0.0).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].zoom = 1.0; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + } + Tool::RotateView => { + hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); + if let Some(i) = app.session.active_index() { + ui.label(tl!("Angle")); + let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); + if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = crate::rotate_view::wrap_deg(angle); + } + if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = 0.0; + } + } + } + Tool::Hand => { + hint(ui, tl!("Drag to pan · hold Space with any tool")); + if widgets::secondary_button(ui, "100%", 0.0).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].zoom = 1.0; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fit_pending = true; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fill_pending = false; + } + if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fill_pending = true; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fit_pending = false; + } + } + // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`. + _ => {} +} +} + /// Width of the Layers panel's Opacity and Fill fields, with room for their pop-up slider's ▾. pub(super) const LAYER_PCT_W: f32 = 66.0 + widgets::POPUP_ARROW_W; diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index b06e3145f7..fcd33e89cb 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -369,6 +369,49 @@ pub(crate) struct Place<'a> { const GRID_GAP: f32 = 4.0; const GRID_INSET: f32 = 8.0; +struct GroupHeaderContext<'a> { + panel: &'a str, + open: bool, + state: &'a mut PresetUi, + tokens: &'a Tokens, + events: &'a mut Vec, +} + +fn draw_group_header(ui: &mut egui::Ui, group: &GroupView, context: GroupHeaderContext<'_>) -> (Rect, Option, Option) { + let GroupHeaderContext { panel, open, state, tokens, events } = context; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + if response.hovered() || response.dragged() { + ui.painter().rect_filled(rect, 2.0, tokens.hover.gamma_multiply(0.5)); + } + let triangle = Rect::from_center_size(pos2(rect.left() + 9.0, rect.center().y), vec2(12.0, 12.0)); + crate::icons::paint(ui, triangle, if open { "chevron-down" } else { "chevron-right" }, 10.0, tokens.text_dim); + let folder = Rect::from_center_size(pos2(rect.left() + 25.0, rect.center().y), vec2(14.0, 14.0)); + crate::icons::paint(ui, folder, if open { "folder-open" } else { "folder" }, 12.0, tokens.icon); + ui.painter().text(pos2(rect.left() + 37.0, rect.center().y), Align2::LEFT_CENTER, &group.name, FontId::proportional(11.5), tokens.text); + if response.clicked() { + let key = format!("{panel}/{}", group.name); + if !state.toggled.remove(&key) { + state.toggled.insert(key); + } + } + response.context_menu(|ui| { + if ui.button(tl!("Rename Group…")).clicked() { + state.renaming = Some((panel.to_string(), format!("group:{}", group.name), group.name.clone())); + ui.close(); + } + if ui.button(tl!("Delete Group")).clicked() { + events.push(Ev::DeleteGroup(group.name.clone())); + ui.close(); + } + }); + let drag = if response.dragged() { ui.ctx().pointer_interact_pos() } else { None }; + if drag.is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } + let released = if response.drag_stopped() { ui.ctx().pointer_interact_pos() } else { None }; + (rect, drag, released) +} + pub(crate) fn browser( ui: &mut egui::Ui, st: &mut PresetUi, @@ -427,41 +470,12 @@ pub(crate) fn browser( for &gi in &display { let Some(g) = groups.get(gi) else { continue }; let open = group_open(st, panel, gi, &g.name); - let (hr, hresp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); - if hresp.hovered() || hresp.dragged() { - ui.painter().rect_filled(hr, 2.0, t.hover.gamma_multiply(0.5)); + let (hr, header_drag, header_release) = draw_group_header(ui, g, GroupHeaderContext { panel, open, state: st, tokens: &t, events: &mut ev }); + if let Some(position) = header_drag { + drag = Some((gi, position)); } - let tri = Rect::from_center_size(pos2(hr.left() + 9.0, hr.center().y), vec2(12.0, 12.0)); - crate::icons::paint(ui, tri, if open { "chevron-down" } else { "chevron-right" }, 10.0, t.text_dim); - let fold = Rect::from_center_size(pos2(hr.left() + 25.0, hr.center().y), vec2(14.0, 14.0)); - crate::icons::paint(ui, fold, if open { "folder-open" } else { "folder" }, 12.0, t.icon); - ui.painter().text(pos2(hr.left() + 37.0, hr.center().y), Align2::LEFT_CENTER, &g.name, FontId::proportional(11.5), t.text); - if hresp.clicked() { - let k = format!("{panel}/{}", g.name); - if !st.toggled.remove(&k) { - st.toggled.insert(k); - } - } - hresp.context_menu(|ui| { - if ui.button(tl!("Rename Group…")).clicked() { - st.renaming = Some((panel.to_string(), format!("group:{}", g.name), g.name.clone())); - ui.close(); - } - if ui.button(tl!("Delete Group")).clicked() { - ev.push(Ev::DeleteGroup(g.name.clone())); - ui.close(); - } - }); - if hresp.dragged() - && let Some(p) = ui.ctx().pointer_interact_pos() - { - drag = Some((gi, p)); - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } - if hresp.drag_stopped() - && let Some(p) = ui.ctx().pointer_interact_pos() - { - released = Some((gi, p)); + if let Some(position) = header_release { + released = Some((gi, position)); } headers.push((gi, hr, g.name.clone())); if !open { diff --git a/crates/ui-egui/src/panels/preset_panels/panels.rs b/crates/ui-egui/src/panels/preset_panels/panels.rs index 27a441fa5f..7aa89c5ccc 100644 --- a/crates/ui-egui/src/panels/preset_panels/panels.rs +++ b/crates/ui-egui/src/panels/preset_panels/panels.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + Align2, Color32, CornerRadius, Ev, FontId, GroupView, ItemView, PhotocraftApp, Place, Pos2, Rect, Sense, Stroke, TextureHandle, Tokens, Tool, Value, + browser, canvas_drop_rect, empty, generic, json, paint_gradient, pattern_texture, pos2, run, shape_texture, style_texture, vec2, +}; // ------------------------------------------------------------------ Gradients diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 43400674bc..0607c5ca30 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{CornerRadius, Layer, LayerContent, LayerId, PhotocraftApp, Rect, RichText, Sense, Stroke, Tokens, empty, icons, json, pos2, theme, vec2, widgets}; // ----------------------------------------------------------------------------- properties diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index 0f0c87ad58..8e531b47b6 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -130,16 +130,9 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l if t.pro { ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); } - let (name, on) = match index { - None => (tl!("Smart Filters").to_string(), sm.filters_enabled), - Some(i) => (filter_label(&sm.smart_filters[i]), sm.smart_filters[i].visible && sm.filters_enabled), - }; + let (name, on, shown) = filter_row_label(sm, index); let eye = Rect::from_center_size(pos2(rect.left() + indent + if index.is_none() { 9.0 } else { 41.0 }, rect.center().y), vec2(18.0, 18.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("sf-eye", l.id.0, index)), Sense::click()); - let shown = match index { - None => sm.filters_enabled, - Some(i) => sm.smart_filters[i].visible, - }; if shown { icons::paint(ui, eye, "eye", 12.0, if on { t.icon } else { t.text_faint }); } @@ -153,11 +146,7 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l // The shared mask scales with the thumbnail setting (hidden at None); the header name // follows it, while filter names stay aligned past their eyes. let mask_left = rect.left() + indent + 28.0; - let x = match index { - None if mask_size > 0.0 => mask_left + mask_size + 8.0, - None => mask_left, - Some(_) => rect.left() + indent + 60.0, - }; + let x = filter_label_x(rect.left(), indent, mask_size, index); if index.is_none() && mask_size > 0.0 { let sw = Rect::from_min_size(pos2(mask_left, rect.center().y - mask_size / 2.0), vec2(mask_size, mask_size)); if let Some(mask) = &sm.filter_mask { @@ -237,6 +226,24 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l } } +fn filter_row_label(sm: &SmartObject, index: Option) -> (String, bool, bool) { + match index { + None => (tl!("Smart Filters").to_string(), sm.filters_enabled, sm.filters_enabled), + Some(i) => { + let filter = &sm.smart_filters[i]; + (filter_label(filter), filter.visible && sm.filters_enabled, filter.visible) + } + } +} + +fn filter_label_x(left: f32, indent: f32, mask_size: f32, index: Option) -> f32 { + match index { + None if mask_size > 0.0 => left + indent + 28.0 + mask_size + 8.0, + None => left + indent + 28.0, + Some(_) => left + indent + 60.0, + } +} + /// What a click on the filter mask thumbnail does: target it for painting (selecting the smart /// object), ⌥ view it alone (⇧⌥ as an overlay), ⇧ disable or enable it. fn filter_mask_click(l: &Layer, sm: &SmartObject, m: egui::Modifiers) -> Vec<(String, Value)> { diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs index 007a5805a3..843b85d6dc 100644 --- a/crates/ui-egui/src/panels/status_bar.rs +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, RichText, Tokens, label, vec2, widgets}; // ----------------------------------------------------------------------------- status bar diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs index 10c797eb20..d93315af10 100644 --- a/crates/ui-egui/src/panels/title_bar.rs +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{PhotocraftApp, Sense, Tokens, icons, theme, vec2, widgets}; // ----------------------------------------------------------------------------- title bar diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 6fb61129b9..c6c7a3567d 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -1,5 +1,5 @@ use super::options_bar::reveal_focused_control; -use super::*; +use super::{Align2, Color32, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Tool, c32, icons, json, pos2, vec2}; // ----------------------------------------------------------------------------- toolbar diff --git a/crates/ui-egui/src/prefs/prefs_ui/appearance.rs b/crates/ui-egui/src/prefs/prefs_ui/appearance.rs index bf08302397..87405f606e 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/appearance.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/appearance.rs @@ -1,6 +1,6 @@ use super::dialogs::open_preferences; use super::fields::{choice_label, color_of, preference_matches}; -use super::*; +use super::{AppearanceMode, Color32, DarkTheme, LightTheme, Map, PhotocraftApp, RichText, SavedTheme, Sense, ThemeKind, Tokens, Value, json, prefs, vec2}; /// The GPU canvas colours from Preferences › Transparency & Gamut. pub fn canvas_style(app: &PhotocraftApp) -> crate::gpu_canvas::CanvasStyle { diff --git a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs index 8a1b298100..c1519b48d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs @@ -1,5 +1,5 @@ use super::shortcuts::shortcut_items; -use super::*; +use super::{BTreeMap, DialogKind, Map, PhotocraftApp, RichText, SECTIONS, Tokens, Value, json, prefs}; // ------------------------------------------------------------------ menu routing diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index cd1c867521..2258a3f7be 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -2,7 +2,7 @@ use super::appearance::{AppearanceRows, appearance_rows, system_theme}; use super::dialogs::{mismatch_body, presets_body, presets_io_body, settings_height}; use super::graphics::{gpu_memory_lines, gpu_status_rows, memory_usage_row, read_at_launch, rendering_mode_row}; use super::shortcuts::shortcuts_body; -use super::*; +use super::{Color32, Map, PhotocraftApp, RichText, SECTIONS, Sense, Tokens, Value, json, prefs, vec2}; // ------------------------------------------------------------------ bodies diff --git a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs index 63930425ea..166f5ed299 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs @@ -1,5 +1,5 @@ use super::fields::choice_label; -use super::*; +use super::{Map, PhotocraftApp, RichText, Tokens, Value, json, prefs}; /// Performance › Graphics: the compositor's GPU memory budget and whether the active document's /// layers fit it (the GPU Memory preference sets it). diff --git a/crates/ui-egui/src/prefs/prefs_ui/save.rs b/crates/ui-egui/src/prefs/prefs_ui/save.rs index 78408b5e1f..9dba6f78f2 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/save.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/save.rs @@ -1,6 +1,6 @@ use super::appearance::{canvas_style, sync_animations, sync_appearance, sync_display_scale, sync_tooltips}; use super::startup::{load, presets_store, recovery, sync_rulers}; -use super::*; +use super::{DocId, HashMap, PhotocraftApp, Value, prefs}; /// Per-frame upkeep: theme sync, persistence, autosave and the history log. pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs index 73b7d475d9..3c0bf1d4a4 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs @@ -1,5 +1,5 @@ use super::dialogs::toolbar_tab; -use super::*; +use super::{BTreeMap, Map, PhotocraftApp, RichText, Tokens, Value, default_shortcut, json, prefs, vec2}; /// Every shortcut-bearing command (engine registry plus shell commands): (id, label, menu path, /// default shortcut), menu items first in Photoshop order. diff --git a/crates/ui-egui/src/prefs/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs index 30da36a2a3..1d4005f17a 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/startup.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/startup.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{JobEvent, JobOutcome, PhotocraftApp, Started, Value, json, prefs}; /// View › Rulers follows `unitsAndRulers.showRulers` when the preference changes (at launch, from /// `prefs.set` or a reset), so documents open with the rulers as last set. diff --git a/crates/ui-egui/src/screenshot_tests.rs b/crates/ui-egui/src/screenshot_tests.rs index 4d23b0607b..9771548b59 100644 --- a/crates/ui-egui/src/screenshot_tests.rs +++ b/crates/ui-egui/src/screenshot_tests.rs @@ -509,114 +509,151 @@ fn actual_callback(output: &egui::FullOutput) -> Option)>>>; +type ScreenshotEncodes = std::rc::Rc)>>>; + +struct ActualCallbackFixture { + app: crate::PhotocraftApp, + ctx: Context, + writes: ScreenshotWrites, + encodes: ScreenshotEncodes, + reply: std::sync::mpsc::Receiver, + document: Option, + old_geometry: CaptureGeometry, + old_pixels: std::sync::Weak, +} + +fn actual_callback_fixture() -> ActualCallbackFixture { use std::cell::RefCell; use std::rc::Rc; - // Unchanged success, resize, DPI change, and minimized are separate real app instances. + + let writes = Rc::new(RefCell::new(Vec::new())); + let encodes = Rc::new(RefCell::new(Vec::new())); + let (written, encoded) = (writes.clone(), encodes.clone()); + let services = crate::Services { + automation_write: Some(Box::new(move |path, bytes| { + written.borrow_mut().push((path.to_owned(), bytes.to_vec())); + Ok(()) + })), + encode_png: Some(Box::new(move |w, h, rgba| { + encoded.borrow_mut().push((w, h, rgba.get(..4).unwrap_or_default().to_vec())); + let image = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, rgba.to_vec()).map_err(|error| error.to_string())?; + photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &photocraft_codecs::EncodeOptions::default()).map_err(|error| error.to_string()) + })), + ..Default::default() + }; + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); + let ctx = Context::default(); + for _ in 0..4 { + actual_capture_frame(&mut app, &ctx, vec2(600.0, 400.0), 1.0, false); + } + let old_geometry = app.captures.last_geometry().expect("the old real UI geometry"); + let document = app.document_identity(); + let (tx, reply) = std::sync::mpsc::channel(); + app.captures.admit(91, Some("fixture/current.png".into()), tx, document, 0.0, super::screenshot::now()).unwrap(); + let mut callback = None; + for _ in 0..8 { + let output = actual_capture_frame(&mut app, &ctx, vec2(600.0, 400.0), 1.0, false); + if let Some(found) = actual_callback(&output) { + callback = Some(found); + break; + } + } + let old_image = Arc::new(ColorImage::filled(old_geometry.expected_pixels().unwrap(), Color32::RED)); + let old_pixels = Arc::downgrade(&old_image); + callback.expect("actual app issued one screenshot callback").complete(old_image); + assert!(writes.borrow().is_empty() && encodes.borrow().is_empty(), "the real callback only stores pixels"); + ActualCallbackFixture { app, ctx, writes, encodes, reply, document, old_geometry, old_pixels } +} + +#[test] +fn completed_callback_revalidates_next_raw_input_before_actual_app_writes() { for (size, scale, minimized) in [(vec2(600.0, 400.0), 1.0, false), (vec2(640.0, 400.0), 1.0, false), (vec2(600.0, 400.0), 2.0, false), (vec2(600.0, 400.0), 1.0, true)] { - let changed = size != vec2(600.0, 400.0) || scale != 1.0 || minimized; - let writes = Rc::new(RefCell::new(Vec::new())); - let encodes = Rc::new(RefCell::new(Vec::new())); - let (written, encoded) = (writes.clone(), encodes.clone()); - let services = crate::Services { - automation_write: Some(Box::new(move |path, bytes| { - written.borrow_mut().push((path.to_owned(), bytes.to_vec())); - Ok(()) - })), - encode_png: Some(Box::new(move |w, h, rgba| { - encoded.borrow_mut().push((w, h, rgba.get(..4).unwrap_or_default().to_vec())); - let image = - photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, rgba.to_vec()).map_err(|error| error.to_string())?; - photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &photocraft_codecs::EncodeOptions::default()) - .map_err(|error| error.to_string()) - })), - ..Default::default() - }; - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.run("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); - let ctx = Context::default(); - for _ in 0..4 { - actual_capture_frame(&mut app, &ctx, vec2(600.0, 400.0), 1.0, false); + let mut fixture = actual_callback_fixture(); + if size == vec2(600.0, 400.0) && scale == 1.0 && !minimized { + verify_unchanged_capture(&mut fixture); + } else { + verify_changed_capture(&mut fixture, size, scale, minimized); } - let old = app.captures.last_geometry().expect("the old real UI geometry"); - let document = app.document_identity(); - let (tx, rx) = std::sync::mpsc::channel(); - app.captures.admit(91, Some("fixture/current.png".into()), tx, document, 0.0, super::screenshot::now()).unwrap(); - let mut callback = None; - for _ in 0..8 { - let output = actual_capture_frame(&mut app, &ctx, vec2(600.0, 400.0), 1.0, false); - if let Some(found) = actual_callback(&output) { - callback = Some(found); - break; - } - } - let old_image = Arc::new(ColorImage::filled(old.expected_pixels().unwrap(), Color32::RED)); - let old_pixels = Arc::downgrade(&old_image); - callback.expect("actual app issued one screenshot callback").complete(old_image); - assert!(writes.borrow().is_empty() && encodes.borrow().is_empty(), "the real callback only stores pixels"); - let output = actual_capture_frame(&mut app, &ctx, size, scale, minimized); - if changed { - assert!(writes.borrow().is_empty() && encodes.borrow().is_empty(), "no stale encode/write on the first changed input"); - assert!(old_pixels.upgrade().is_none(), "old pixels are released on geometry rejection"); - let current = app.captures.last_geometry().unwrap(); - assert!(current.logical_size != old.logical_size || current.pixels_per_point != old.pixels_per_point || current.minimized != old.minimized); - if minimized { - // A minimized surface cannot be retried. It fails once, then an independent - // request after restoration proves that cancellation releases its budget. - let reply = rx.try_recv().expect("one minimized error"); - assert_eq!(reply["ok"], false, "{reply}"); - assert!(reply["error"].as_str().unwrap().contains("minimized")); - assert_eq!(app.captures.pending(), 0); - assert_eq!(app.captures.reserved_bytes(), 0); - assert!(actual_callback(&output).is_none()); - actual_capture_frame(&mut app, &ctx, size, scale, false); - let (tx, restored_rx) = std::sync::mpsc::channel(); - app.captures.admit(92, Some("fixture/restored.png".into()), tx, document, 0.0, super::screenshot::now()).unwrap(); - for _ in 0..8 { - let output = actual_capture_frame(&mut app, &ctx, size, scale, false); - if let Some(callback) = actual_callback(&output) { - callback.complete(Arc::new(ColorImage::filled(app.captures.last_geometry().unwrap().expected_pixels().unwrap(), Color32::BLUE))); - break; - } - } - actual_capture_frame(&mut app, &ctx, size, scale, false); - let reply = restored_rx.try_recv().expect("the restored window accepts a new request"); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(writes.borrow().len(), 1); - assert!(writes.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n")); - assert_eq!(encodes.borrow().len(), 1); - assert_eq!(encodes.borrow()[0].2, [0, 0, 255, 255]); - assert_eq!(app.captures.pending(), 0); - assert_eq!(app.captures.reserved_bytes(), 0); - assert!(rx.try_recv().is_err() && restored_rx.try_recv().is_err()); - continue; - } - assert!(rx.try_recv().is_err(), "bounded retry has not delivered a stale success"); - let mut retry = actual_callback(&output); - for _ in 0..8 { - if retry.is_some() { - break; - } - retry = actual_callback(&actual_capture_frame(&mut app, &ctx, size, scale, minimized)); - } - retry - .expect("the actual app reissues at bounded current geometry") - .complete(Arc::new(ColorImage::filled(current.expected_pixels().unwrap(), Color32::BLUE))); - actual_capture_frame(&mut app, &ctx, size, scale, minimized); - assert_eq!(encodes.borrow().first().map(|entry| entry.2.as_slice()), Some([0, 0, 255, 255].as_slice()), "only the new callback image is encoded"); - } - let reply = rx.try_recv().expect("one response after the valid callback"); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(writes.borrow().len(), 1); - assert!(writes.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n"), "real PNG encoding and automation_write ran"); - assert_eq!(encodes.borrow().len(), 1); - assert_eq!(app.captures.pending(), 0); - assert_eq!(app.captures.reserved_bytes(), 0); - actual_capture_frame(&mut app, &ctx, size, scale, minimized); - assert_eq!(writes.borrow().len(), 1, "no duplicate output"); - assert!(rx.try_recv().is_err()); } } + +fn verify_unchanged_capture(fixture: &mut ActualCallbackFixture) { + actual_capture_frame(&mut fixture.app, &fixture.ctx, vec2(600.0, 400.0), 1.0, false); + assert_successful_capture(fixture, vec2(600.0, 400.0), 1.0, false); +} + +fn verify_changed_capture(fixture: &mut ActualCallbackFixture, size: egui::Vec2, scale: f32, minimized: bool) { + let output = actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, minimized); + assert!(fixture.writes.borrow().is_empty() && fixture.encodes.borrow().is_empty(), "no stale encode/write on the first changed input"); + assert!(fixture.old_pixels.upgrade().is_none(), "old pixels are released on geometry rejection"); + let current = fixture.app.captures.last_geometry().unwrap(); + assert!( + current.logical_size != fixture.old_geometry.logical_size + || current.pixels_per_point != fixture.old_geometry.pixels_per_point + || current.minimized != fixture.old_geometry.minimized + ); + if minimized { + verify_minimized_capture(fixture, size, scale, &output); + return; + } + assert!(fixture.reply.try_recv().is_err(), "bounded retry has not delivered a stale success"); + let mut retry = actual_callback(&output); + for _ in 0..8 { + if retry.is_some() { + break; + } + retry = actual_callback(&actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, minimized)); + } + retry + .expect("the actual app reissues at bounded current geometry") + .complete(Arc::new(ColorImage::filled(current.expected_pixels().unwrap(), Color32::BLUE))); + actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, minimized); + assert_eq!(fixture.encodes.borrow().first().map(|entry| entry.2.as_slice()), Some([0, 0, 255, 255].as_slice()), "only the new callback image is encoded"); + assert_successful_capture(fixture, size, scale, minimized); +} + +fn verify_minimized_capture(fixture: &mut ActualCallbackFixture, size: egui::Vec2, scale: f32, output: &egui::FullOutput) { + let reply = fixture.reply.try_recv().expect("one minimized error"); + assert_eq!(reply["ok"], false, "{reply}"); + assert!(reply["error"].as_str().unwrap().contains("minimized")); + assert_eq!(fixture.app.captures.pending(), 0); + assert_eq!(fixture.app.captures.reserved_bytes(), 0); + assert!(actual_callback(output).is_none()); + actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, false); + let (tx, restored_rx) = std::sync::mpsc::channel(); + fixture.app.captures.admit(92, Some("fixture/restored.png".into()), tx, fixture.document, 0.0, super::screenshot::now()).unwrap(); + for _ in 0..8 { + let output = actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, false); + if let Some(callback) = actual_callback(&output) { + callback.complete(Arc::new(ColorImage::filled(fixture.app.captures.last_geometry().unwrap().expected_pixels().unwrap(), Color32::BLUE))); + break; + } + } + actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, false); + let reply = restored_rx.try_recv().expect("the restored window accepts a new request"); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(fixture.writes.borrow().len(), 1); + assert!(fixture.writes.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(fixture.encodes.borrow().len(), 1); + assert_eq!(fixture.encodes.borrow()[0].2, [0, 0, 255, 255]); + assert_eq!(fixture.app.captures.pending(), 0); + assert_eq!(fixture.app.captures.reserved_bytes(), 0); + assert!(fixture.reply.try_recv().is_err() && restored_rx.try_recv().is_err()); +} + +fn assert_successful_capture(fixture: &mut ActualCallbackFixture, size: egui::Vec2, scale: f32, minimized: bool) { + let reply = fixture.reply.try_recv().expect("one response after the valid callback"); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(fixture.writes.borrow().len(), 1); + assert!(fixture.writes.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n"), "real PNG encoding and automation_write ran"); + assert_eq!(fixture.encodes.borrow().len(), 1); + assert_eq!(fixture.app.captures.pending(), 0); + assert_eq!(fixture.app.captures.reserved_bytes(), 0); + actual_capture_frame(&mut fixture.app, &fixture.ctx, size, scale, minimized); + assert_eq!(fixture.writes.borrow().len(), 1, "no duplicate output"); + assert!(fixture.reply.try_recv().is_err()); +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index d330884a0a..53d3c2e7f0 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + CaptionStyle, Document, FileDialogFn, OsEvent, Value, dds_options_ui, jobs_ui, jpeg_options_ui, monitor_status, native_menu, screen_picker, + targa_options_ui, +}; /// The error a save gets while another save waits on its format prompt. pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG Options before starting another save"; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8fb058524a..eac69a2263 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -657,6 +657,11 @@ mod tests { #[test] fn tool_names_parse() { + basic_and_retouch_tool_names_parse(); + vector_tool_names_parse(); + } + + fn basic_and_retouch_tool_names_parse() { assert_eq!(Tool::from_name("brush"), Some(Tool::Brush)); assert_eq!(Tool::from_name("Rect"), Some(Tool::RectMarquee)); assert_eq!(Tool::from_name("RectMarquee"), Some(Tool::RectMarquee)); @@ -675,6 +680,9 @@ mod tests { assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); assert_eq!(Tool::ALL.len(), 68); + } + + fn vector_tool_names_parse() { assert_eq!(Tool::from_name("Vertical Type Mask Tool"), Some(Tool::VerticalTypeMask)); assert_eq!(Tool::from_name("addAnchorPoint"), Some(Tool::AddAnchorPoint)); assert_eq!(Tool::from_name("Delete Anchor Point Tool"), Some(Tool::DeleteAnchorPoint)); diff --git a/crates/ui-egui/src/state/color_panel.rs b/crates/ui-egui/src/state/color_panel.rs index 4b1ac89ee8..29dfebc471 100644 --- a/crates/ui-egui/src/state/color_panel.rs +++ b/crates/ui-egui/src/state/color_panel.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Deserialize, Serialize}; /// Selected tab per dock card. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/ui-egui/src/state/panel_state.rs b/crates/ui-egui/src/state/panel_state.rs index 4cc2d67184..387f6ce915 100644 --- a/crates/ui-egui/src/state/panel_state.rs +++ b/crates/ui-egui/src/state/panel_state.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Deserialize, Serialize}; /// Photoshop-style Layers panel display preferences; part of serialized UI state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 2b6702f317..cd96f525a1 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Tool { diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 6855ddeb12..8b8bad1630 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -1,5 +1,5 @@ use super::tool::Tool; -use super::*; +use super::{Deserialize, Serialize}; /// Options-bar state for tools (Photoshop keeps these per tool). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/ui-egui/src/state/transform.rs b/crates/ui-egui/src/state/transform.rs index ed14318721..5eb2064f0d 100644 --- a/crates/ui-egui/src/state/transform.rs +++ b/crates/ui-egui/src/state/transform.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Deserialize, Serialize}; /// Edit › Transform's mode: what a handle drag does with no modifier keys held. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 822d79e148..88672fe75c 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1180,52 +1180,197 @@ pub mod live { let mut unknown = Vec::new(); let Some(obj) = v.as_object() else { return unknown }; for (k, val) in obj { - macro_rules! c { - ($($f:ident),*) => { - match k.as_str() { - $(stringify!($f) => { if let Some(c) = color(val) { t.$f = c; } })* - "radius_sm" => { if let Some(x) = val.as_f64() { t.radius_sm = x as f32; } } - "radius" => { if let Some(x) = val.as_f64() { t.radius = x as f32; } } - "radius_lg" => { if let Some(x) = val.as_f64() { t.radius_lg = x as f32; } } - _ => unknown.push(k.clone()), + if override_chrome_color(t, k, val) || override_text_color(t, k, val) || override_accent_color(t, k, val) { + continue; + } + match k.as_str() { + "radius_sm" => { + if let Some(x) = val.as_f64() { + t.radius_sm = x as f32; } - }; + } + "radius" => { + if let Some(x) = val.as_f64() { + t.radius = x as f32; + } + } + "radius_lg" => { + if let Some(x) = val.as_f64() { + t.radius_lg = x as f32; + } + } + _ => unknown.push(k.clone()), } - c!( - caption_close, - caption_close_text, - chrome, - canvas, - canvas_dot, - dock, - card, - card_border, - field, - field_border, - hover, - pressed, - text, - text_dim, - text_faint, - icon, - accent, - accent_soft, - accent_border, - accent_text, - separator, - shadow, - primary_bg, - primary_text, - danger, - warning, - tab_strip, - row_selected, - scrim - ); } unknown } + fn override_chrome_color(t: &mut Tokens, key: &str, value: &serde_json::Value) -> bool { + match key { + "caption_close" => { + if let Some(c) = color(value) { + t.caption_close = c; + } + } + "caption_close_text" => { + if let Some(c) = color(value) { + t.caption_close_text = c; + } + } + "chrome" => { + if let Some(c) = color(value) { + t.chrome = c; + } + } + "canvas" => { + if let Some(c) = color(value) { + t.canvas = c; + } + } + "canvas_dot" => { + if let Some(c) = color(value) { + t.canvas_dot = c; + } + } + "dock" => { + if let Some(c) = color(value) { + t.dock = c; + } + } + "card" => { + if let Some(c) = color(value) { + t.card = c; + } + } + "card_border" => { + if let Some(c) = color(value) { + t.card_border = c; + } + } + "field" => { + if let Some(c) = color(value) { + t.field = c; + } + } + "field_border" => { + if let Some(c) = color(value) { + t.field_border = c; + } + } + _ => return false, + } + true + } + + fn override_text_color(t: &mut Tokens, key: &str, value: &serde_json::Value) -> bool { + match key { + "hover" => { + if let Some(c) = color(value) { + t.hover = c; + } + } + "pressed" => { + if let Some(c) = color(value) { + t.pressed = c; + } + } + "text" => { + if let Some(c) = color(value) { + t.text = c; + } + } + "text_dim" => { + if let Some(c) = color(value) { + t.text_dim = c; + } + } + "text_faint" => { + if let Some(c) = color(value) { + t.text_faint = c; + } + } + "icon" => { + if let Some(c) = color(value) { + t.icon = c; + } + } + "separator" => { + if let Some(c) = color(value) { + t.separator = c; + } + } + "shadow" => { + if let Some(c) = color(value) { + t.shadow = c; + } + } + "primary_bg" => { + if let Some(c) = color(value) { + t.primary_bg = c; + } + } + "primary_text" => { + if let Some(c) = color(value) { + t.primary_text = c; + } + } + _ => return false, + } + true + } + + fn override_accent_color(t: &mut Tokens, key: &str, value: &serde_json::Value) -> bool { + match key { + "accent" => { + if let Some(c) = color(value) { + t.accent = c; + } + } + "accent_soft" => { + if let Some(c) = color(value) { + t.accent_soft = c; + } + } + "accent_border" => { + if let Some(c) = color(value) { + t.accent_border = c; + } + } + "accent_text" => { + if let Some(c) = color(value) { + t.accent_text = c; + } + } + "danger" => { + if let Some(c) = color(value) { + t.danger = c; + } + } + "warning" => { + if let Some(c) = color(value) { + t.warning = c; + } + } + "tab_strip" => { + if let Some(c) = color(value) { + t.tab_strip = c; + } + } + "row_selected" => { + if let Some(c) = color(value) { + t.row_selected = c; + } + } + "scrim" => { + if let Some(c) = color(value) { + t.scrim = c; + } + } + _ => return false, + } + true + } + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs b/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs index 271118de40..b5a16773f1 100644 --- a/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs +++ b/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs @@ -1,6 +1,9 @@ //! Compact live-gradient Properties controls, sharing the editor's stop interaction. -use super::*; +use super::{ + Color32, Fill, GradientStyle, Layer, LayerId, Marker, PhotocraftApp, Rect, Sense, Sink, Stroke, StrokeKind, Tokens, c32, cmds, edit_stop_color, fill_of, + json, preset_stop_color, selection_after_edit, stops_editor_for, strip_key, vec2, widgets, +}; use crate::{icons, props_layout, theme}; const STYLES: [(GradientStyle, &str); 5] = [ @@ -215,6 +218,7 @@ pub(super) fn stop_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink #[cfg(test)] mod tests { use super::*; + use egui::pos2; use egui_kittest::{ Harness, kittest::{NodeT, Queryable}, diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index b3bba8d8f1..44bea250aa 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -1,6 +1,9 @@ use super::commit::{commit, start_steps}; use super::preview::{Above, preview_image}; -use super::*; +use super::{ + Arc, BezierMesh, CAS_ONLY_SCALES, Color32, DocId, Document, Follow, Homography, LOCKED, LayerContent, LayerId, MadeLayer, PhotocraftApp, Steps, + TransformPreview, TransformSession, Warp, WarpStyle, corners, json, +}; /// Start Free Transform on the active layer (or its selected pixels), or on the targeted unlinked /// layer mask, alpha channel or Quick Mask. diff --git a/crates/ui-egui/src/tools/transform_tool/commit.rs b/crates/ui-egui/src/tools/transform_tool/commit.rs index 23ab10e429..eebc7120ce 100644 --- a/crates/ui-egui/src/tools/transform_tool/commit.rs +++ b/crates/ui-egui/src/tools/transform_tool/commit.rs @@ -1,6 +1,8 @@ use super::begin::{fold_made, rect_to_quad_affine, take_back_made, warps_type}; use super::options_bar::{rotate_about_pivot, scale_about_pivot}; -use super::*; +use super::{ + Arc, DocId, JobEvent, JobId, JobOutcome, LayerContent, LayerId, MadeLayer, PhotocraftApp, Step, Steps, TransformPreview, TransformSession, corners, json, +}; /// Undo and Redo while the commit runs in the background (Free Transform, or Warp). const STILL_APPLYING: &str = "Free Transform is still being applied"; diff --git a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs index 49f594e08f..0114e57754 100644 --- a/crates/ui-egui/src/tools/transform_tool/drag_modes.rs +++ b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs @@ -1,5 +1,5 @@ use super::pointer::{Gesture, Hit, carry_pivot}; -use super::*; +use super::{Homography, LayerContent, LayerId, PhotocraftApp, TransformMode, TransformSession}; /// The same effective modifiers drive the geometry and decide whether Ctrl is a distortion /// gesture rather than the ordinary snap override. Keep type and Content-Aware Scale refusals. diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 6c70e029fd..fc1babfbdb 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -3,7 +3,10 @@ use super::drag_modes::{HandleIndicator, handle_indicator}; use super::options_bar::{quad_scale, readout}; use super::pointer::{Hit, handle_at, rotate_dir, rotation_degrees}; use super::warp::{on_section_edge, quick_split_kind, single_patch}; -use super::*; +use super::{ + BezierMesh, Color32, DocId, HANDLE_PX, Homography, LayerId, PhotocraftApp, Pos2, SplitTool, Stroke, TransformPreview, TransformSession, ViewXform, Warp, + WarpDrag, WarpStyle, corners, pos2, vec2, +}; /// The distort or skew pointer at screen point `at`, where [`super::cursor`] hid the system /// pointer over a handle. The canvas calls it from its cursor branch, so nothing is drawn where a diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index e2f1ad20ac..c9393810b5 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -2,7 +2,7 @@ use super::begin::{enter_warp, leave_warp, warps_type}; use super::commit::{cancel, commit}; use super::pointer::point_on_quad; use super::warp::edit_session_warp; -use super::*; +use super::{BezierMesh, Homography, PhotocraftApp, SplitTool, Stroke, TransformSession, Warp, WarpStyle, json, vec2}; /// How much the box enlarges its pixels: the longest edge relative to the original (picks the /// preview's texture level and filter). diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index e11f0c97c9..87ccfe2f49 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -2,7 +2,10 @@ use super::begin::warps_type; use super::commit::{commit, committing, moves_type}; use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, handle_indicator, mode_allows, mode_mods}; use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer}; -use super::*; +use super::{ + CursorIcon, HANDLE_PX, Homography, LayerContent, LayerId, PhotocraftApp, ToolEvent, TransformMode, TransformPreview, TransformSession, ViewXform, + WarpStyle, handle_tolerance, +}; /// Which part of the box a document point hits. #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] diff --git a/crates/ui-egui/src/tools/transform_tool/preview.rs b/crates/ui-egui/src/tools/transform_tool/preview.rs index d39d6575f3..b9edbc67e8 100644 --- a/crates/ui-egui/src/tools/transform_tool/preview.rs +++ b/crates/ui-egui/src/tools/transform_tool/preview.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, Document, LayerContent, LayerId, ViewXform, pos2}; /// Texels of the moving pixels over `b`: full resolution unless the long side exceeds the GPU's /// `max_side` (#91: this used to be capped at 2048 px, so big layers previewed blurry), plus the diff --git a/crates/ui-egui/src/tools/transform_tool/warp.rs b/crates/ui-egui/src/tools/transform_tool/warp.rs index 90b372a36f..ca918d5d06 100644 --- a/crates/ui-egui/src/tools/transform_tool/warp.rs +++ b/crates/ui-egui/src/tools/transform_tool/warp.rs @@ -1,5 +1,5 @@ use super::begin::warps_type; -use super::*; +use super::{BezierMesh, CursorIcon, PhotocraftApp, SplitTool, ToolEvent, ViewXform, Warp, WarpDrag, WarpStyle, json}; /// An anchor or a handle on a section line. The inner control points of a patch are not shown. pub(super) fn on_section_edge(i: usize, j: usize) -> bool { diff --git a/crates/ui-egui/src/tools/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs index 05fea9244c..6c4b5a2ebe 100644 --- a/crates/ui-egui/src/tools/type_tool/defaults.rs +++ b/crates/ui-egui/src/tools/type_tool/defaults.rs @@ -1,5 +1,5 @@ use super::editing::edit_home; -use super::*; +use super::{LayerId, PhotocraftApp, TextLayer, hex, json, text_layer}; /// Representative for the displayed properties: the edit layer, else a selected type layer. pub(crate) fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> { diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index 33d49ccf4c..57c3a3177f 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -1,7 +1,7 @@ use super::ime::interrupt_incoming; use super::ime_edit::note_ime_application_change; use super::layout::{hit_layer, hit_offset, shows_own_layout}; -use super::*; +use super::{LayerId, PhotocraftApp, TextEdit, TextLayer, active_doc_id, byte_range, current_text, json, selected_range, session_key, text_layer}; /// Start editing an existing type layer. Like Photoshop, editing shows the text as the type /// engine lays it out, so a PSD layer is re-rendered first (inside the edit session's history diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index 9035387c1e..571febc0fe 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -1,5 +1,5 @@ use super::defaults::apply; -use super::*; +use super::{Arc, HashMap, PhotocraftApp, PoisonError, json}; /// Font families: bundled, system, and those the host serves (`photocraft_text::served`, fetched /// when picked). Cached until the shared engine registers fonts or the served catalog changes. diff --git a/crates/ui-egui/src/tools/type_tool/ime.rs b/crates/ui-egui/src/tools/type_tool/ime.rs index 09994a338d..4f9f606bed 100644 --- a/crates/ui-egui/src/tools/type_tool/ime.rs +++ b/crates/ui-egui/src/tools/type_tool/ime.rs @@ -1,6 +1,6 @@ use super::editing::edit_home; use super::ime_edit::{ime_geometry, reconcile_preedit}; -use super::*; +use super::{Arc, HashMap, ImeContextTracker, ImeMutationStamp, ImeTarget, LayerId, PhotocraftApp, TextEdit, ViewXform, active_doc_id, current_text}; /// Per-editor IME owner/generation bookkeeping for the custom Type tool. /// diff --git a/crates/ui-egui/src/tools/type_tool/ime_edit.rs b/crates/ui-egui/src/tools/type_tool/ime_edit.rs index c13abf716e..33296343d3 100644 --- a/crates/ui-egui/src/tools/type_tool/ime_edit.rs +++ b/crates/ui-egui/src/tools/type_tool/ime_edit.rs @@ -3,7 +3,9 @@ use super::ime::{ ImeCommitted, ImeEmitted, ResetContext, bind_reset_context, ime_target, interrupt_incoming, remember_incoming, reset_route_eligible, sync_incoming, }; use super::layout::layout; -use super::*; +use super::{ + CommittedText, ImeObservation, LayerId, PhotocraftApp, Point, Pos2, Range, TextEdit, ViewXform, byte_of, current_text, json, text_char_count, text_layer, +}; /// UTF-8 byte offsets of the caret, anchor and pre-edit, found in one traversal. /// diff --git a/crates/ui-egui/src/tools/type_tool/ime_tests.rs b/crates/ui-egui/src/tools/type_tool/ime_tests.rs index 71fab4c0f7..5617eebe5b 100644 --- a/crates/ui-egui/src/tools/type_tool/ime_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/ime_tests.rs @@ -172,118 +172,129 @@ fn external_edit_invalidates_the_preedit_and_rejects_its_late_commit() { for bytes in [false, true] { for split in [false, true] { for discard in [false, true] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, Vec::new()); - // Compose in the middle of committed text, so an application edit before it - // moves a still-in-range (but wrong) character range. - insert(&mut app, "def"); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.caret = 3; - ed.anchor = 3; - } - let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("composing descriptor"); - assert_eq!(layer_text(&app), "abcにdef"); - assert_eq!(payload(&composing).text, "abcdef", "the preview is not committed text"); - let layer = app.ui.text_edit.as_ref().unwrap().layer; - let session = app.ui.text_edit.as_ref().unwrap().session.clone(); - // The control channel edits the same layer without passing through `insert`. - app.run("type.edit", json!({"layer": layer, "replace": {"start": 0, "end": 1, "text": ""}, "coalesce": session})).unwrap(); - assert_eq!(layer_text(&app), "bcにdef"); - let revision = app.session.active().unwrap().revision; - let history = app.session.active().unwrap().history.entries(); - let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); - let unchanged = |app: &PhotocraftApp| { - assert_eq!(layer_text(app), "bcにdef"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries(), history); - assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); - }; - - // The old range (3,1) now covers `d`: report unavailable, cancel the - // composition and do not present `d` as the composition. A discarded pass - // must retain both latches until a descriptor is actually delivered. - let invalidated = if discard { - ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); - let mut passes = Vec::new(); - let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { - handle_keys(&mut app, ui.ctx()); - let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_overlay(&mut app, ui.painter(), &xf); - if passes.is_empty() { - ui.ctx().request_discard("invalidated preedit descriptor regression"); - } - let discarded = ui.ctx().will_discard(); - let before = (app.type_ime.stale, app.type_ime.interrupt); - sync_ime(&mut app, ui.ctx()); - finish_reset_pass(&mut app, ui.ctx()); - let unavailable = ui.ctx().output(|out| out.ime.as_ref().expect("pass descriptor").surrounding_text.available().is_none()); - passes.push((discarded, before, (app.type_ime.stale, app.type_ime.interrupt), unavailable)); - }); - out.textures_delta.clear(); - assert_eq!(passes.first(), Some(&(true, (true, true), (true, true), true)), "discard cannot consume invalidation"); - assert_eq!(passes.last(), Some(&(false, (true, true), (false, false), true)), "the accepted pass delivers it once"); - out.platform_output.ime.expect("descriptor") - } else { - run(&mut app, &ctx, Vec::new()).expect("descriptor") - }; - assert!(invalidated.surrounding_text.available().is_none()); - assert!(invalidated.should_interrupt_composition); - assert_eq!( - (invalidated.owner, invalidated.context_generation, invalidated.purpose), - (composing.owner, composing.context_generation, composing.purpose) - ); - assert_eq!(invalidated.change_cause, ImeChangeCause::Other); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); - assert!(app.type_ime.preedit.is_none()); - unchanged(&app); - - let recovered = run(&mut app, &ctx, Vec::new()).expect("idle descriptor"); - assert_eq!(payload(&recovered).text, "bcにdef"); - assert_eq!((payload(&recovered).cursor, payload(&recovered).anchor), (6, 6)); - assert!(!recovered.should_interrupt_composition, "a delivered reset is not replayed"); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "idle availability does not accept an old terminal"); - unchanged(&app); - - // The pending deletion and commit belonged to the cancelled composition: - // neither combined nor split delivery may replace `d` or grow undo history. - let mut events = vec![terminal_delete(bytes)]; - if split { - run(&mut app, &ctx, events).expect("rejected deletion descriptor"); - unchanged(&app); - for _ in 0..3 { - run(&mut app, &ctx, Vec::new()); - } - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); - events = Vec::new(); - } - events.push(egui::Event::Ime(egui::ImeEvent::Commit("に".into()))); - let late = run(&mut app, &ctx, events).expect("descriptor"); - assert_eq!(layer_text(&app), "bcにdef"); - assert_eq!(late.change_cause, ImeChangeCause::Other); - assert_eq!(payload(&late).text, "bcにdef"); - unchanged(&app); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "terminal input cannot acknowledge cancellation"); - - let fresh = - run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]).expect("fresh preview descriptor"); - assert_eq!(layer_text(&app), "bcにdQef"); - assert_eq!(payload(&fresh).text, "bcにdef", "fresh preview is excluded from committed text"); - assert!(!fresh.should_interrupt_composition); - let committed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]).expect("fresh commit descriptor"); - assert_eq!(layer_text(&app), "bcにdQef"); - assert_eq!(payload(&committed).text, "bcにdQef"); - assert_eq!(committed.change_cause, ImeChangeCause::InputMethod); - let direct = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]).expect("direct commit descriptor"); - assert_eq!(layer_text(&app), "bcにdQRef"); - assert_eq!(payload(&direct).text, "bcにdQRef"); - assert_eq!(direct.change_cause, ImeChangeCause::InputMethod); + external_edit_case(bytes, split, discard); } } } } +fn external_edit_case(bytes: bool, split: bool, discard: bool) { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, Vec::new()); + // Compose in the middle of committed text, so an application edit before it + // moves a still-in-range (but wrong) character range. + insert(&mut app, "def"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.caret = 3; + ed.anchor = 3; + } + let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("composing descriptor"); + assert_eq!(layer_text(&app), "abcにdef"); + assert_eq!(payload(&composing).text, "abcdef", "the preview is not committed text"); + let layer = app.ui.text_edit.as_ref().unwrap().layer; + let session = app.ui.text_edit.as_ref().unwrap().session.clone(); + // The control channel edits the same layer without passing through `insert`. + app.run("type.edit", json!({"layer": layer, "replace": {"start": 0, "end": 1, "text": ""}, "coalesce": session})).unwrap(); + assert_eq!(layer_text(&app), "bcにdef"); + let revision = app.session.active().unwrap().revision; + let history = app.session.active().unwrap().history.entries(); + let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); + let unchanged = |app: &PhotocraftApp| { + assert_eq!(layer_text(app), "bcにdef"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries(), history); + assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); + }; + + // The old range (3,1) now covers `d`: report unavailable, cancel the + // composition and do not present `d` as the composition. A discarded pass + // must retain both latches until a descriptor is actually delivered. + let invalidated = invalidated_descriptor(&mut app, &ctx, discard); + assert!(invalidated.surrounding_text.available().is_none()); + assert!(invalidated.should_interrupt_composition); + assert_eq!((invalidated.owner, invalidated.context_generation, invalidated.purpose), (composing.owner, composing.context_generation, composing.purpose)); + assert_eq!(invalidated.change_cause, ImeChangeCause::Other); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); + assert!(app.type_ime.preedit.is_none()); + unchanged(&app); + + let recovered = run(&mut app, &ctx, Vec::new()).expect("idle descriptor"); + assert_eq!(payload(&recovered).text, "bcにdef"); + assert_eq!((payload(&recovered).cursor, payload(&recovered).anchor), (6, 6)); + assert!(!recovered.should_interrupt_composition, "a delivered reset is not replayed"); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "idle availability does not accept an old terminal"); + unchanged(&app); + + // The pending deletion and commit belonged to the cancelled composition: + // neither combined nor split delivery may replace `d` or grow undo history. + let mut events = reject_cancelled_deletion(&mut app, &ctx, bytes, split, &unchanged); + events.push(egui::Event::Ime(egui::ImeEvent::Commit("に".into()))); + let late = run(&mut app, &ctx, events).expect("descriptor"); + assert_eq!(layer_text(&app), "bcにdef"); + assert_eq!(late.change_cause, ImeChangeCause::Other); + assert_eq!(payload(&late).text, "bcにdef"); + unchanged(&app); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "terminal input cannot acknowledge cancellation"); + + let fresh = run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]).expect("fresh preview descriptor"); + assert_eq!(layer_text(&app), "bcにdQef"); + assert_eq!(payload(&fresh).text, "bcにdef", "fresh preview is excluded from committed text"); + assert!(!fresh.should_interrupt_composition); + let committed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]).expect("fresh commit descriptor"); + assert_eq!(layer_text(&app), "bcにdQef"); + assert_eq!(payload(&committed).text, "bcにdQef"); + assert_eq!(committed.change_cause, ImeChangeCause::InputMethod); + let direct = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]).expect("direct commit descriptor"); + assert_eq!(layer_text(&app), "bcにdQRef"); + assert_eq!(payload(&direct).text, "bcにdQRef"); + assert_eq!(direct.change_cause, ImeChangeCause::InputMethod); +} + +/// Delivers the deletion of the cancelled composition. With `split`, it is rejected on its own +/// first. Returns the events that the caller still has to deliver. +fn reject_cancelled_deletion(app: &mut PhotocraftApp, ctx: &egui::Context, bytes: bool, split: bool, unchanged: &dyn Fn(&PhotocraftApp)) -> Vec { + let mut events = vec![terminal_delete(bytes)]; + if split { + run(app, ctx, events).expect("rejected deletion descriptor"); + unchanged(app); + for _ in 0..3 { + run(app, ctx, Vec::new()); + } + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); + events = Vec::new(); + } + events +} + +fn invalidated_descriptor(app: &mut PhotocraftApp, ctx: &egui::Context, discard: bool) -> egui::output::IMEOutput { + if discard { + ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); + let mut passes = Vec::new(); + let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { + handle_keys(app, ui.ctx()); + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(app, ui.painter(), &xf); + if passes.is_empty() { + ui.ctx().request_discard("invalidated preedit descriptor regression"); + } + let discarded = ui.ctx().will_discard(); + let before = (app.type_ime.stale, app.type_ime.interrupt); + sync_ime(app, ui.ctx()); + finish_reset_pass(app, ui.ctx()); + let unavailable = ui.ctx().output(|out| out.ime.as_ref().expect("pass descriptor").surrounding_text.available().is_none()); + passes.push((discarded, before, (app.type_ime.stale, app.type_ime.interrupt), unavailable)); + }); + out.textures_delta.clear(); + assert_eq!(passes.first(), Some(&(true, (true, true), (true, true), true)), "discard cannot consume invalidation"); + assert_eq!(passes.last(), Some(&(false, (true, true), (false, false), true)), "the accepted pass delivers it once"); + out.platform_output.ime.expect("descriptor") + } else { + run(app, ctx, Vec::new()).expect("descriptor") + } +} + #[test] fn target_change_interrupts_and_rejects_the_late_commit() { let ctx = context(); diff --git a/crates/ui-egui/src/tools/type_tool/keys.rs b/crates/ui-egui/src/tools/type_tool/keys.rs index 98820ab0a5..09fdc0e179 100644 --- a/crates/ui-egui/src/tools/type_tool/keys.rs +++ b/crates/ui-egui/src/tools/type_tool/keys.rs @@ -9,7 +9,7 @@ use super::ime::{ use super::ime_edit::{ime_delete_bytes, ime_delete_chars, ime_update}; use super::layout::layout; use super::pointer::word_boundary; -use super::*; +use super::{LayerId, PhotocraftApp, byte_of, current_text, json, text_char_count, text_layer}; /// Caret on the neighbouring line (±1; a column in vertical type), keeping the position /// along the line. Works in line space, so it serves both orientations. diff --git a/crates/ui-egui/src/tools/type_tool/layout.rs b/crates/ui-egui/src/tools/type_tool/layout.rs index adfb3e910d..45e7cafa3a 100644 --- a/crates/ui-egui/src/tools/type_tool/layout.rs +++ b/crates/ui-egui/src/tools/type_tool/layout.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Affine, Arc, Document, LayerContent, LayerId, PhotocraftApp, Point, PoisonError, TextLayer, TextLayout, text_layer}; /// Layout of a type layer (cached per document revision) and its text → document transform. pub fn layout(app: &mut PhotocraftApp, id: LayerId) -> Option<(Arc, Affine, String)> { diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index 55ff499ca3..e2616982ff 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -2,7 +2,7 @@ use super::defaults::{apply, formatting_params, open_color_picker, shown_scale, use super::editing::{cancel, commit_with}; use super::fonts::{font_picker, fonts_ready, selected_style, style_label, styles}; use super::keys::is_vertical; -use super::*; +use super::{Color32, LayerId, PhotocraftApp, Stroke, byte_of, json, text_layer}; /// Photoshop's Type options bar. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/tools/type_tool/overlay.rs b/crates/ui-egui/src/tools/type_tool/overlay.rs index 31a6022df3..fbac016e3d 100644 --- a/crates/ui-egui/src/tools/type_tool/overlay.rs +++ b/crates/ui-egui/src/tools/type_tool/overlay.rs @@ -1,7 +1,7 @@ use super::editing::edit_home; use super::ime_edit::{ime_offsets, ime_preedit_is_current}; use super::layout::layout; -use super::*; +use super::{Color32, LayerId, PhotocraftApp, Point, Pos2, Stroke, ViewXform, byte_of, text_layer}; /// Selection highlight, caret and text frame over the canvas. pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { diff --git a/crates/ui-egui/src/tools/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs index 7211b17f3d..09ebeb70c9 100644 --- a/crates/ui-egui/src/tools/type_tool/panel.rs +++ b/crates/ui-egui/src/tools/type_tool/panel.rs @@ -3,7 +3,7 @@ use super::fonts::{axis_sliders, font_picker, fonts_ready, selected_style, style use super::options_bar::{ align_glyph, apply_kerning, direction_glyph, direction_items, icon_label, kerning_at, kerning_field, kerning_label, num_field, styles_at, toggle_cell, }; -use super::*; +use super::{Color32, LayerId, PhotocraftApp, Stroke, json, text_layer}; /// The Character panel's OpenType buttons, in Photoshop's order: (feature tag, command id, /// tooltip). The tooltips are the Type › OpenType menu labels. diff --git a/crates/ui-egui/src/tools/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs index 2249907954..39cce1c91c 100644 --- a/crates/ui-egui/src/tools/type_tool/pointer.rs +++ b/crates/ui-egui/src/tools/type_tool/pointer.rs @@ -1,7 +1,7 @@ use super::defaults::default_style_params; use super::editing::{begin_edit, commit_with}; use super::layout::{hit_layer, hit_offset, layout, to_text}; -use super::*; +use super::{BoxResize, LayerId, PLACEHOLDER, PhotocraftApp, Point, TextEdit, TextLayout, active_doc_id, byte_of, current_text, json, session_key, text_layer}; /// Smallest paragraph box a handle drag leaves, in text-space px. pub(super) const MIN_BOX: f32 = 4.0; diff --git a/crates/ui-egui/src/tools/vector_ui/curvature.rs b/crates/ui-egui/src/tools/vector_ui/curvature.rs index 097ad9d207..5506beb8f7 100644 --- a/crates/ui-egui/src/tools/vector_ui/curvature.rs +++ b/crates/ui-egui/src/tools/vector_ui/curvature.rs @@ -1,5 +1,5 @@ use super::pen::{cancel_stale, pen_commit}; -use super::*; +use super::{PenPath, PhotocraftApp}; /// Recompute a Curvature Pen path's handles from its anchors and corner points. pub(super) fn curvature_refresh(pen: &mut PenPath, closed: bool) { diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 1147810733..e87dd825d9 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -1,6 +1,6 @@ use super::path_ops::active_path_name; use super::shapes::is_shape_tool; -use super::*; +use super::{GradientChoices, LayerContent, PaintChange, PhotocraftApp, Tokens, Tool, Value, json, paint_param, swatch}; // --------------------------------------------------------------------------------------------- // Options bars diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index a50708c6ae..a0f3ca4e6d 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -1,6 +1,6 @@ use super::paths_panel::{PathEntry, PathRow, path_rows}; use super::pen::pen_commit; -use super::*; +use super::{Affine, Document, LayerContent, Path, PhotocraftApp, Tool, Value, json}; /// The path that path commands act on without a name: the one selected in the Paths panel, else /// the work path while it is shown (not after Make Selection hid it, #6079), else the selected diff --git a/crates/ui-egui/src/tools/vector_ui/paths_panel.rs b/crates/ui-egui/src/tools/vector_ui/paths_panel.rs index 81ba9f11f5..1d02f3fdd7 100644 --- a/crates/ui-egui/src/tools/vector_ui/paths_panel.rs +++ b/crates/ui-egui/src/tools/vector_ui/paths_panel.rs @@ -1,6 +1,6 @@ use super::overlay::path_lines; use super::shapes::hex; -use super::*; +use super::{Color32, Document, LayerContent, Path, PhotocraftApp, Rect, Sense, Stroke, Tokens, Value, json, pos2, vec2}; // --------------------------------------------------------------------------------------------- // Paths panel diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index 9236cf8528..56b6d79449 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -1,7 +1,7 @@ use super::curvature::{curvature_hit, curvature_refresh}; -use super::path_ops::targeted_vector_mask; +use super::path_ops::{targeted_vector_mask, work_path_shown}; use super::shapes::{fill_param, stroke_param}; -use super::*; +use super::{Document, Path, PenPath, PhotocraftApp, Resumed, Tool, Value, json}; // --------------------------------------------------------------------------------------------- // Pen diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index d931d1ca5b..dc72a120f0 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -1,6 +1,6 @@ use super::options::solid_paint; use super::overlay::path_lines; -use super::*; +use super::{Affine, Color32, PhotocraftApp, Tokens, Tool, ToolOptions, Value, ViewXform, json, paint_param}; pub fn is_shape_tool(t: Tool) -> bool { matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape) diff --git a/crates/ui-egui/src/widgets/angle_dial.rs b/crates/ui-egui/src/widgets/angle_dial.rs index 7a6c82f6b1..a21b453ded 100644 --- a/crates/ui-egui/src/widgets/angle_dial.rs +++ b/crates/ui-egui/src/widgets/angle_dial.rs @@ -2,7 +2,7 @@ //! Drop Shadow's light (#882), Motion Blur and the other direction angles of the filter //! dialogs (#3152) share it, as Photoshop's dialogs do. -use super::*; +use super::{Response, Sense, Stroke, Tokens, Ui, value_field, vec2}; /// `Label (dial) [field°]` for a direction in document angles: counter-clockwise from three /// o'clock, y up. The dial points anywhere in -180..=180; the result is clamped to `range`, and @@ -61,6 +61,7 @@ pub fn angle_dial_row(ui: &mut Ui, label: &str, angle: &mut f32, range: std::ops #[cfg(test)] mod tests { use super::*; + use egui::Vec2; use egui_kittest::kittest::Queryable; fn click(h: &mut egui_kittest::Harness<'_, f32>, delta: Vec2) { diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index c6ac810d23..41ad5509bc 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -1,5 +1,5 @@ use super::panel::surface; -use super::*; +use super::{Color32, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2, theme, vec2}; /// iOS-style toggle switch. pub fn toggle(ui: &mut Ui, on: &mut bool, label: &str) -> Response { diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 0c71e0746a..e246afcded 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -1,5 +1,5 @@ use super::dropdown::swatch_popup; -use super::*; +use super::{Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2}; /// Cached RGB data; drawing work is bounded by the 256 display bins, never the image size. pub fn rgb_histogram(ui: &mut Ui, histogram: &photocraft_algo::histogram::RgbHistogram, height: f32) -> egui::Response { diff --git a/crates/ui-egui/src/widgets/color_count.rs b/crates/ui-egui/src/widgets/color_count.rs index da65928ad7..03da8cf31f 100644 --- a/crates/ui-egui/src/widgets/color_count.rs +++ b/crates/ui-egui/src/widgets/color_count.rs @@ -1,6 +1,6 @@ //! Integer-only Indexed Color field and a linear slider with common palette sizes. -use super::*; +use super::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, pos2, surface, theme, vec2}; const STOPS: [u32; 6] = [8, 16, 32, 64, 128, 256]; @@ -102,6 +102,7 @@ pub fn color_count_row(ui: &mut Ui, label: &str, count: &mut u32) -> Response { #[cfg(test)] mod tests { use super::*; + use egui::Pos2; use egui_kittest::{Harness, kittest::Queryable}; #[test] diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index f1ef01940a..6f83b0edd2 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,7 +1,7 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; use super::slider::wheel_notches_of; -use super::*; +use super::{Pos2, Rect, Response, Ui, Vec2, type_ahead}; /// A compact labelled dropdown in the studio style. pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index 143320e330..439662724e 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -3,7 +3,7 @@ use super::scrub::{label_scrub_response, take_label_scrub}; use super::slider::slider; use super::text_field::first_field_id; use super::units::{FieldUnits, field_resolution_id, fmt_num, fmt_num_prec, fmt_num2, parse_num_in, plain, unit_of_suffix}; -use super::*; +use super::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2, theme, vec2}; /// Monospace numeric field with a dimmed unit suffix, Photoshop style. Drag to scrub. Typed /// arithmetic (`1920/2`) applies on Enter, Tab or click-away, and a unit after a number converts diff --git a/crates/ui-egui/src/widgets/panel.rs b/crates/ui-egui/src/widgets/panel.rs index 43c52b1cf4..7833edc2bc 100644 --- a/crates/ui-egui/src/widgets/panel.rs +++ b/crates/ui-egui/src/widgets/panel.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Color32, CornerRadius, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, pos2, theme, vec2}; /// Match the Spectrum application-menu padding and blue/white hover state in /// secondary menus (status bar, dock hamburger, layer context menus; #2187). diff --git a/crates/ui-egui/src/widgets/scrub.rs b/crates/ui-egui/src/widgets/scrub.rs index 45056106bb..8602af4e61 100644 --- a/crates/ui-egui/src/widgets/scrub.rs +++ b/crates/ui-egui/src/widgets/scrub.rs @@ -1,4 +1,4 @@ -use super::*; +use super::{Rect, Response, Sense, Ui}; /// A drag on a value field's label this frame, for the value field drawn next on the label's row /// (Photoshop's scrubby labels). Left by [`scrub_label`], taken by that field. diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs index 49363da87e..c4112fecb5 100644 --- a/crates/ui-egui/src/widgets/slider.rs +++ b/crates/ui-egui/src/widgets/slider.rs @@ -1,7 +1,7 @@ use super::fields::{FieldOpts, value_field_in}; use super::panel::surface; use super::scrub::scrub_label_within; -use super::*; +use super::{Color32, Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, vec2}; /// Thin-track slider with a round knob. `gradient` paints the track (e.g. hue spectrum). pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>) -> Response { diff --git a/crates/ui-egui/src/widgets/text_field.rs b/crates/ui-egui/src/widgets/text_field.rs index 3a009d3635..b377fbf098 100644 --- a/crates/ui-egui/src/widgets/text_field.rs +++ b/crates/ui-egui/src/widgets/text_field.rs @@ -1,5 +1,5 @@ use super::panel::surface; -use super::*; +use super::{Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, theme, vec2}; /// The most characters a [`text_field`] holds unless its caller sets a limit: far beyond any /// search, name or hex value, yet a pasted multi-gigabyte string is cut at the field instead of diff --git a/crates/ui-egui/src/widgets/units.rs b/crates/ui-egui/src/widgets/units.rs index 388dddf26c..c4ea21dbde 100644 --- a/crates/ui-egui/src/widgets/units.rs +++ b/crates/ui-egui/src/widgets/units.rs @@ -1,5 +1,5 @@ use super::fields::{FieldOpts, value_field_in}; -use super::*; +use super::{Response, Ui}; /// A size dialog's unit key (`px`, `in`, `cm`, `mm`, `pt`, `pica`, `percent`) as a unit. pub fn unit_of_key(key: &str) -> photocraft_engine::prefs::Unit {